diff --git "a/1196.jsonl" "b/1196.jsonl" new file mode 100644--- /dev/null +++ "b/1196.jsonl" @@ -0,0 +1,704 @@ +{"seq_id":"575121766","text":"import sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\ndimensions=[1,2,3,4]\n\nprint(\"Legendre dimensional analysis \\n\")\n\np_bdt = []\nfor dim in range(1,5):\n temp = np.loadtxt(\"../bdt_legendre/\"+str(dim)+'Dlegendre4contrib_bdt_p_values')\n p_bdt.append(temp)\n\nprint(\"Boosted decision tree : \", p_bdt)\n\np_svm = []\nfor dim in range(1,5):\n temp = np.loadtxt(\"../svm_legendre/\"+str(dim)+'Dlegendre4contrib_svm_p_values')\n p_svm.append(temp)\n\nprint(\"Support vector machine : \", p_svm)\n\n\np_nn = []\nfor dim in range(1,5):\n temp = np.loadtxt(\"../nn_legendre/\"+str(dim)+'Dlegendre4contrib_nn_4layers_100neurons_onehot_p_values')\n p_nn.append(temp)\n\nprint(\"Neural Network : \", p_nn)\n\np_miranda_3bins = [1.2212453270876722e-15, 0.012266775041445577,0.18759112444309145,0.29341559120156957]\n#for dim in range(1,5):\n #temp = np.loadtxt(os.environ['MLToolsDir']+\"/Dalitz_simplified/optimisation/miranda/legendre_4contrib_\"+str(dim)+'D_optimisation_miranda_values')\n #p_miranda_3bins.append(temp)\n\nprint(\"Miranda 3 bins: \", p_miranda_3bins)\n\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nax.plot(dimensions,p_bdt,label=\"bdt \",color='darkorange')\nax.plot(dimensions,p_svm,label=\"svm \",color='lawngreen')\n\nax.plot(dimensions,p_nn,label=\"nn 4l 100n \",color='blueviolet')\n\nax.plot(dimensions,p_miranda_3bins,label=\"Miranda 3bins\",color='darkred')\n\nplt.ylim([0,1])\nax.set_xlabel(\"Number of dimensions\")\nax.set_ylabel(\"P value\")\nax.set_title(\"Dimensionality analysis legendre 4 contrib\")\nax.legend(loc='upper right')\nfig_name=\"legendre4contrib_dimensionality_analysis\"\nfig.savefig(fig_name)\nfig.savefig(\"../bdt_legendre/\"+fig_name)\nfig.savefig(\"../svm_legendre/\"+fig_name)\nfig.savefig(\"../nn_legendre/\"+fig_name)\nprint(\"Saved the figure as\" , fig_name+\".png\")\n\n\n","sub_path":"Dalitz_simplified/evaluation_of_optimised_classifiers/legendre_analysis/plot_gauss_dimenionality_analysis.py","file_name":"plot_gauss_dimenionality_analysis.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"640120594","text":"from django.shortcuts import render\nfrom django.core import serializers\nfrom datetime import datetime, timedelta\n\n\nfrom sensor import models\nfrom .proxy import Proxy\nfrom . import utils\n\n\n\ndef get_latest_sample():\n latest_sample = models.Sample.objects.using('data').latest('date')\n return utils.dateify_sample(latest_sample)\n\ndef get_last24hr():\n time_threshold = datetime.now() - timedelta(hours=24)\n results = models.Sample.objects.using('data').filter(date__gt=time_threshold)\n return results\n\ndef index(request):\n dates = Proxy.get_dates()\n all_samples = get_last24hr()\n all_samples = list(map(utils.dateify_sample, all_samples))\n\n temperatures = list(map(lambda sample: sample.temperature, all_samples))\n times = map(lambda sample: sample.time, all_samples)\n\n min_temp = min(temperatures)\n max_temp = max(temperatures)\n if len(temperatures) > 0:\n avg_temp = sum(temperatures) / len(temperatures)\n else:\n avg_temp = 0\n\n times = '[' + ', '.join(f'\"{t}\"' for t in times) + ']'\n temperatures = '[' + ', '.join(str(t) for t in temperatures) + ']'\n\n\n return render(request, 'index.html', {\n 'dates': dates, \n 'latest_sample': get_latest_sample(),\n 'all_samples': all_samples,\n 'temperatures': temperatures,\n 'times': times,\n 'min_temp': min_temp,\n 'max_temp': max_temp,\n 'avg_temp': avg_temp,\n })\n\n\ndef date(request, date:str):\n dates = Proxy.get_dates()\n weekday = utils.get_weekday(date)\n images = _get_images(date)\n return render(request, 'date.html', {\n 'dates': dates,\n 'date': date,\n 'weekday': weekday,\n 'images': images,\n 'latest_sample': get_latest_sample()\n })\n\n\ndef image(request, date:str, img:str):\n data = Proxy.get_image(date, img)\n dates = Proxy.get_dates()\n date = _get_image_date(img)\n weekday = utils.get_weekday(date)\n time = _get_image_time(img)\n return render(request, 'image.html', {\n 'date': date,\n 'time': time,\n 'data': data,\n 'image': img,\n 'weekday': weekday,\n 'dates': dates,\n 'latest_sample': get_latest_sample()\n })\n\n\ndef next_image(request, date:str, img:str):\n date, img = _next_image(date, img)\n return image(request, date, img)\n\n\ndef prev_image(request, date:str, img:str):\n date, img = _next_image(date, img, next_image=False)\n return image(request, date, img)\n\n\ndef _next_image(date:str, img:str, next_image: bool = True) -> str:\n \"\"\" Helper method to get the next image.\n \"next\" can be either next as future, or previous.\n \"\"\"\n images = Proxy.get_images(date)\n \n pos = images.index(img)\n direction = 1 if next_image else -1\n new_pos = pos + direction\n\n\n if new_pos == len(images) or new_pos < 0:\n dates = Proxy.get_dates()\n date_pos = dates.index(date)\n\n if new_pos < 0:\n # Go BACK in time\n date_pos -= 1\n new_img_pos = -1\n\n else:\n # Go FORWARD in time\n date_pos += 1\n if date_pos == len(dates):\n date_pos = -1\n new_img_pos = 0\n\n date = dates[date_pos]\n img = Proxy.get_images(date)[new_img_pos]\n else:\n img = images[new_pos]\n \n return date, img\n\n\ndef _get_image_date(img: str) -> str:\n return _get_image_name(img).split('_')[0]\n\n\ndef _get_image_time(img: str) -> str:\n return _get_image_name(img).split('_')[1] \\\n .replace('-', ':')\n\n\ndef _get_image_name(img: str) -> str:\n return img.split('.jpg')[0]\n\n\ndef _get_images(date:str) -> tuple:\n \"\"\" Helper method to get images and create their names. \"\"\"\n images = Proxy.get_images(date)\n names = map(_get_image_time, images)\n return zip(images, names)","sub_path":"potato_image_server/potato_image_server/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"96824813","text":"import os\nfrom kafka import KafkaConsumer\n\nkafka_server = os.environ['KAFKA_IP']\n\ndef main():\n consumer = KafkaConsumer(\n 'test',\n group_id='kafka',\n bootstrap_servers=kafka_server+':9092',\n auto_offset_reset='earliest'\n )\n print(consumer)\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"test/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"500763979","text":"import smach_ros\n\n\nclass FeedbackActionState(smach_ros.SimpleActionState):\n def __init__(self, action_topic, action, goal, outcomes, input_keys=None, output_keys=None):\n if input_keys is None:\n input_keys = []\n if output_keys is None:\n output_keys = []\n\n super(FeedbackActionState, self).__init__(action_topic, action, goal,\n outcomes=outcomes, input_keys=input_keys, output_keys=output_keys)\n","sub_path":"march_state_machine/src/march_state_machine/states/feedback_action_state.py","file_name":"feedback_action_state.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"52579721","text":"# -*- encoding: utf-8 -*-\n#\n# Creation Date: 11-01-2015\n# Last Modified: 07-10-2016\n#\n# bri_conr's ideas, maps 96 zeros of zeros starting at a height 1200 and wrapped once around the unit circle.\n# bri_conr claims that those distribution are not random.\n#\n# This file verify this properties.\n#\n# Note 1: We try different options to map zeros onto unit circle.\n# One option is to follows bri_conr's ideas, 96 zeros of zeros starting at a height 1200\n# and wrapped once around the unit circle. \"Wrapped once around\" means \"re-scale\" the zeros\n#\n# Another option is that, we do not do this \"wrapped once around unit circle\". Then in this case,\n# the plotting is very much like \"random\" numbers\n#\n# Note 2: We also try above options to map prime numbers onto unit circle. It turns out that,\n# prime numbers will behave much like \"random\" numbers regardless if we do \"wrapped once around unit circle\"\n# or not.\n#\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom get_prime_list import get_prime_list\nfrom zeros_map_onto_unit_circl import plot_selected_zeros_on_unit_circle_exp_j_gamma\n\n# num_of_points chosen at random on [0,1] and mapped to the circle by exp(2 π i x)\ndef plot_random_points_on_unit_circle(num_of_points):\n\n random_arr = np.random.rand(1,num_of_points)\n random_arr *=2*np.pi\n random_phase = 1j*random_arr\n random_data = np.exp(random_phase)\n\n real_part = random_data[0].real\n imag_part = random_data[0].imag\n\n plt.figure()\n plt.plot(real_part, imag_part, 'k.')\n plt.grid(True)\n\n title_str = 'random, num_of_points = %d'%(num_of_points)\n plt.title(title_str)\n\n plt.ylim((-1.2,1.2))\n plt.xlim((-1.2,1.2))\n\n# plot primes on unit circle\n# each prime number will correspond to an phase.\n# We support two options: use wrap_around_once or not\n# Note:\n# start is the starting position in prime list. For example, start = 100, which\n# means the 100th prime number\ndef plot_primes_points_on_unit_circle(start, num_of_points, wrap_around_once = True):\n\n prime_max = 120000\n prime_list = get_prime_list(prime_max)\n\n prime_arr = prime_list[start:(start + num_of_points)]\n prime_arr = np.asarray(prime_arr)\n\n # NOT wrap around once\n if(wrap_around_once == False):\n prime_phase = 1j*prime_arr\n\n # Wrapped around once\n else:\n begin = prime_arr[0]\n end = prime_arr[num_of_points - 1]\n\n prime_wrap_around_once_arr = (prime_arr - begin)*(2*np.pi)/(end - begin)\n\n # print prime_wrap_around_once_arr\n prime_phase = 1j*prime_wrap_around_once_arr\n\n prime_data = np.exp(prime_phase)\n\n real_part = prime_data.real\n imag_part = prime_data.imag\n\n plt.figure()\n plt.plot(real_part, imag_part, 'k.')\n plt.grid(True)\n\n title_str = 'prime, start %d, num_of_points = %d, wrap_around = %d'%(start, num_of_points, wrap_around_once)\n plt.title(title_str)\n\n plt.ylim((-1.2,1.2))\n plt.xlim((-1.2,1.2))\n\n# ===============================================================================================\n# For num_of_points, it is better to try other number, for example:\n# num_of_points = 96*4\n# num_of_points = 96*10\n# to see the effect of \"equidistribution\"\nif __name__=='__main__':\n\n np.set_printoptions(precision=4)\n np.set_printoptions(suppress=True)\n\n #\n num_of_points = 96\n\n # ======================================================================================\n # plot zeros, wrap_around_once option (which is bri_conr used in his plot)\n # ======================================================================================\n start = 1200\n wrap_around_once = True\n plot_selected_zeros_on_unit_circle_exp_j_gamma(start, num_of_points, wrap_around_once)\n\n start = 0\n plot_selected_zeros_on_unit_circle_exp_j_gamma(start, num_of_points, wrap_around_once)\n\n start = 10000\n plot_selected_zeros_on_unit_circle_exp_j_gamma(start, num_of_points, wrap_around_once)\n\n start = 90000\n plot_selected_zeros_on_unit_circle_exp_j_gamma(start, num_of_points, wrap_around_once)\n\n # ======================================================================================\n # plot zeros, NOT wrap around\n # ======================================================================================\n start = 1200\n wrap_around_once = False\n plot_selected_zeros_on_unit_circle_exp_j_gamma(start, num_of_points, wrap_around_once)\n\n start = 0\n plot_selected_zeros_on_unit_circle_exp_j_gamma(start, num_of_points, wrap_around_once)\n\n start = 10000\n plot_selected_zeros_on_unit_circle_exp_j_gamma(start, num_of_points, wrap_around_once)\n\n start = 90000\n plot_selected_zeros_on_unit_circle_exp_j_gamma(start, num_of_points, wrap_around_once)\n\n # ======================================================================================\n # plot prime numbers, NOT wrap around\n # ======================================================================================\n start = 1200\n wrap_around_once = False\n plot_primes_points_on_unit_circle(start, num_of_points, wrap_around_once)\n\n start = 0\n plot_primes_points_on_unit_circle(start, num_of_points, wrap_around_once)\n\n start = 1000\n plot_primes_points_on_unit_circle(start, num_of_points, wrap_around_once)\n\n start = 9000\n plot_primes_points_on_unit_circle(start, num_of_points, wrap_around_once)\n\n # ======================================================================================\n # plot prime numbers, wrap around around\n # ======================================================================================\n start = 1200\n wrap_around_once = True\n plot_primes_points_on_unit_circle(start, num_of_points, wrap_around_once)\n\n start = 0\n plot_primes_points_on_unit_circle(start, num_of_points, wrap_around_once)\n\n start = 1000\n plot_primes_points_on_unit_circle(start, num_of_points, wrap_around_once)\n\n start = 9000\n plot_primes_points_on_unit_circle(start, num_of_points, wrap_around_once)\n\n # ======================================================================================\n # plot random number\n # ======================================================================================\n plot_random_points_on_unit_circle(num_of_points)\n\n # try again, which will get different random numbers\n plot_random_points_on_unit_circle(num_of_points)\n\n # try again, which will get different random numbers\n plot_random_points_on_unit_circle(num_of_points)\n\n plt.show()","sub_path":"py_code/zet_zeros/zeros_vs_random_on_unit_circle.py","file_name":"zeros_vs_random_on_unit_circle.py","file_ext":"py","file_size_in_byte":6558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"585039108","text":"# data.world-py\n# Copyright 2017 data.world, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the\n# License.\n#\n# You may obtain a copy of the License at\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\n# implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n# This product includes software developed at\n# data.world, Inc.(http://data.world/).\n\nfrom __future__ import absolute_import\n\nimport os\nfrom os import path\n\nimport pytest\nimport responses\nfrom doublex import assert_that, Spy, called\nfrom hamcrest import (equal_to, has_entries, has_properties, is_, described_as,\n empty, raises, calling, has_key)\n\nfrom datadotworld.client._swagger import (\n DatasetsApi,\n DownloadApi,\n SparqlApi,\n SqlApi,\n UploadsApi,\n UserApi,\n StreamsApi,\n)\nfrom datadotworld.client._swagger.rest import ApiException\nfrom datadotworld.client._swagger.models import (\n DatasetSummaryResponse,\n FileBatchUpdateRequest,\n FileCreateOrUpdateRequest,\n FileSourceCreateOrUpdateRequest,\n PaginatedDatasetResults,\n UserDataResponse,\n)\nfrom datadotworld.client.api import RestApiClient, RestApiError\n\n\nclass TestApiClient:\n @pytest.fixture()\n def datasets_api(self):\n with Spy(DatasetsApi) as api:\n api.get_dataset = lambda o, d: DatasetSummaryResponse(o, d)\n api.create_dataset_with_http_info = lambda o, b, **kwargs: (\n {}, 200, {'Location': 'https://data.world/agentid/datasetid'})\n return api\n\n @pytest.fixture()\n def uploads_api(self):\n with Spy(UploadsApi) as api:\n api.get_dataset = lambda o, d: DatasetSummaryResponse(o, d)\n return api\n\n @pytest.fixture()\n def download_api(self):\n with Spy(DownloadApi) as api:\n api.download_dataset\n api.download_file\n return api\n\n @pytest.fixture()\n def sql_api(self):\n with Spy(SqlApi) as api:\n api.sql_post\n return api\n\n @pytest.fixture()\n def sparql_api(self):\n with Spy(SparqlApi) as api:\n api.sparql_post\n return api\n\n @pytest.fixture()\n def user_api(self):\n with Spy(UserApi) as api:\n api.get_user_data = lambda: UserDataResponse()\n api.fetch_liked_datasets = lambda: PaginatedDatasetResults()\n api.fetch_datasets = lambda: PaginatedDatasetResults()\n api.fetch_contributing_datasets = lambda: PaginatedDatasetResults()\n return api\n\n @pytest.fixture()\n def streams_api(self):\n with Spy(StreamsApi) as api:\n api.append_records\n return api\n\n @pytest.fixture()\n def api_client(self, config, datasets_api, uploads_api, download_api,\n sql_api, sparql_api, user_api, streams_api):\n client = RestApiClient(config)\n client._datasets_api = datasets_api\n client._uploads_api = uploads_api\n client._download_api = download_api\n client._sql_api = sql_api\n client._sparql_api = sparql_api\n client._user_api = user_api\n client._streams_api = streams_api\n return client\n\n def test_get_dataset(self, api_client, dataset_key):\n dataset = api_client.get_dataset(dataset_key)\n assert_that(dataset, has_entries(\n {'owner': equal_to('agentid'), 'id': equal_to('datasetid')}))\n\n def test_create_dataset(self, api_client):\n create_request = {'title': 'Dataset', 'visibility': 'OPEN',\n 'license': 'Public Domain'}\n dataset_key = api_client.create_dataset('agentid', **create_request)\n assert_that(dataset_key,\n equal_to('https://data.world/agentid/datasetid'))\n\n def test_update_dataset(self, api_client, datasets_api, dataset_key):\n patch_request = {'tags': ['tag1', 'tag2']}\n api_client.update_dataset(dataset_key, **patch_request)\n assert_that(datasets_api.patch_dataset,\n called().times(1).with_args(equal_to('agentid'),\n equal_to('datasetid'),\n has_properties(patch_request)))\n\n def test_replace_dataset(self, api_client, datasets_api, dataset_key):\n replace_request = {'visibility': 'OPEN'}\n api_client.replace_dataset(dataset_key, **replace_request)\n assert_that(datasets_api.replace_dataset,\n called().times(1).with_args(equal_to('agentid'),\n equal_to('datasetid'),\n has_properties(\n replace_request)))\n\n def test_delete_dataset(self, api_client, datasets_api, dataset_key):\n api_client.delete_dataset(dataset_key)\n assert_that(datasets_api.delete_dataset,\n called().times(1).with_args(equal_to('agentid'),\n equal_to('datasetid')))\n\n def test_add_files_via_url(self, api_client, datasets_api, dataset_key):\n file_update_request = {'filename.ext':\n {'url': 'https://acme.inc/filename.ext'}}\n file_update_object = FileBatchUpdateRequest(\n files=[FileCreateOrUpdateRequest(\n name='filename.ext',\n source=FileSourceCreateOrUpdateRequest(\n url='https://acme.inc/filename.ext'))])\n\n api_client.add_files_via_url(dataset_key, file_update_request)\n assert_that(datasets_api.add_files_by_source,\n called().times(1).with_args(equal_to('agentid'),\n equal_to('datasetid'),\n equal_to(file_update_object)))\n\n def test_sync_files(self, api_client, datasets_api, dataset_key):\n api_client.sync_files(dataset_key)\n assert_that(datasets_api.sync,\n called().times(1).with_args('agentid', 'datasetid'))\n\n def test_upload_files(self, api_client, uploads_api, dataset_key):\n files = ['filename.ext']\n api_client.upload_files(dataset_key, files)\n assert_that(uploads_api.upload_files,\n called().times(1).with_args(equal_to('agentid'),\n equal_to('datasetid'),\n equal_to(files)))\n\n def test_upload_file(self, api_client, uploads_api, dataset_key):\n name = 'filename.ext'\n api_client.upload_file(dataset_key, name)\n assert_that(uploads_api.upload_file,\n called().times(1).with_args(equal_to('agentid'),\n equal_to('datasetid'),\n equal_to(name)))\n\n def test_delete_files(self, api_client, datasets_api, dataset_key):\n files = ['filename.ext']\n api_client.delete_files(dataset_key, files)\n assert_that(datasets_api.delete_files_and_sync_sources,\n called().times(1).with_args(equal_to('agentid'),\n equal_to('datasetid'),\n equal_to(files)))\n\n def test_rest_api_error(self):\n apix = ApiException(status=400, reason=\"boom\")\n e = RestApiError(cause=apix)\n assert_that(e.status, equal_to(400))\n assert_that(e.reason, equal_to(\"boom\"))\n assert_that(e.body, equal_to(None))\n assert_that(e.cause, equal_to(apix))\n\n # TODO Test CRUD exception cases\n\n def test_download_datapackage(self, helpers, config,\n test_datapackages_path, api_client,\n dataset_key):\n datapackage_zip = path.join(test_datapackages_path,\n 'the-simpsons-by-the-data.zip')\n with responses.RequestsMock() as rsps, open(datapackage_zip,\n 'rb') as file:\n @helpers.validate_request_headers()\n def datapackage_endpoint(_):\n return 200, {}, file.read()\n\n rsps.add_callback(\n rsps.GET,\n 'https://download.data.world/datapackage/agentid/datasetid',\n datapackage_endpoint)\n\n datapackage = api_client.download_datapackage(dataset_key,\n config.cache_dir)\n\n assert_that(datapackage, equal_to(\n path.join(config.cache_dir, 'datapackage.json')))\n assert_that(path.isfile(datapackage),\n described_as('%0 is a file', is_(True), datapackage))\n\n data_subdirectory = path.join(config.cache_dir, 'data')\n assert_that(path.isdir(data_subdirectory),\n described_as('%0 is a directory', is_(True),\n data_subdirectory))\n assert_that(os.listdir(config.tmp_dir),\n described_as('%0 is empty', empty(), config.tmp_dir))\n\n def test_download_datapackage_error(self, helpers, config,\n test_datapackages_path, api_client,\n dataset_key):\n datapackage_zip = path.join(test_datapackages_path,\n 'the-simpsons-by-the-data.zip')\n with responses.RequestsMock() as rsps, open(datapackage_zip,\n 'rb') as file: # noqa\n @helpers.validate_request_headers()\n def datapackage_endpoint(_):\n return 400, {}, ''\n\n rsps.add_callback(\n rsps.GET,\n 'https://download.data.world/datapackage/agentid/datasetid',\n datapackage_endpoint)\n\n assert_that(\n calling(api_client.download_datapackage).with_args(\n dataset_key, config.cache_dir),\n raises(RestApiError))\n\n def test_download_datapackage_existing_dest_dir(\n self, config, api_client, dataset_key):\n os.mkdir(config.cache_dir)\n assert_that(\n calling(api_client.download_datapackage).with_args(\n dataset_key, config.cache_dir),\n raises(ValueError))\n\n def test_download_dataset(self, api_client, dataset_key, download_api):\n api_client.download_dataset(dataset_key)\n assert_that(download_api.download_dataset,\n called().times(1).with_args('agentid', 'datasetid'))\n\n def test_download_file(self, api_client, dataset_key, download_api):\n api_client.download_file(dataset_key, 'file')\n assert_that(download_api.download_file,\n called().times(1).with_args('agentid', 'datasetid',\n 'file'))\n\n def test_sql(self, api_client, dataset_key, sql_api):\n api_client.sql(dataset_key, 'query', sql_api_mock=sql_api)\n assert_that(sql_api.sql_post,\n called().times(1).with_args('agentid', 'datasetid',\n 'query', sql_api_mock=sql_api))\n\n def test_sparql(self, api_client, dataset_key, sparql_api):\n api_client.sparql(dataset_key, 'query', sparql_api_mock=sparql_api)\n assert_that(sparql_api.sparql_post,\n called().times(1).with_args('agentid', 'datasetid',\n 'query',\n sparql_api_mock=sparql_api))\n\n def test_get_user_data(self, api_client):\n user_data_response = api_client.get_user_data()\n assert_that(user_data_response,\n has_key(equal_to('display_name')))\n\n def test_fetch_liked_datasets(self, api_client, user_api):\n liked_datasets = api_client.fetch_liked_datasets()\n assert_that(user_api.fetch_liked_datasets(),\n has_properties(liked_datasets))\n\n def test_fetch_contributing_datasets(self, api_client, user_api):\n contributing_datasets = api_client.fetch_contributing_datasets()\n assert_that(user_api.fetch_contributing_datasets(),\n has_properties(contributing_datasets))\n\n def test_fetch_datasets(self, api_client, user_api):\n user_datasets = api_client.fetch_datasets()\n assert_that(user_api.fetch_datasets(),\n has_properties(user_datasets))\n\n def test_append_records(self, api_client, dataset_key, streams_api):\n body = {'content': 'content'}\n api_client.append_records(dataset_key, 'streamid', body,\n streams_api_mock=streams_api)\n assert_that(streams_api.append_records,\n called().times(1).with_args('agentid', 'datasetid',\n 'streamid', body,\n streams_api_mock=streams_api))\n","sub_path":"tests/datadotworld/client/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":13379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"30209372","text":"# -*- coding: utf-8 -*-\n\n__all__ = ['Request', 'Response']\n\nimport logging\nimport httplib\nimport cgi\nfrom webob import Request as _Request, Response\nfrom webob.multidict import MultiDict, NoVars, UnicodeMultiDict\n\nfrom ..utils import cached_property\n\nlogger = logging.getLogger(__name__)\n\n\n\nclass Request(_Request):\n '''\n Patched webob Request class\n '''\n\n def __init__(self, *args, **kwargs):\n super(Request, self).__init__(*args, **kwargs)\n self._prefixes = []\n self._subdomain = ''\n\n def add_prefix(self, prefix):\n self._prefixes.append(prefix)\n\n def add_subdomain(self, subdomain):\n if self._subdomain and subdomain:\n self._subdomain = subdomain + '.' + self._subdomain\n elif subdomain:\n self._subdomain = subdomain\n\n # We need to inject code which works with\n # prefixes\n @property\n def prefixed_path(self):\n path = self.path\n if self._prefixes:\n length = sum(map(len, self._prefixes))\n path = path[length:]\n return path\n\n @property\n def prefixed_path_qs(self):\n path = self.path_qs\n if self._prefixes:\n length = sum(map(len, self._prefixes))\n path = path[length:]\n return path\n\n @property\n def subdomain(self):\n if self.headers.get('Host'):\n server_name = self.headers.get('Host').split(':')[0]\n else:\n server_name = self.server_name\n path = server_name.decode('idna')\n if self._subdomain:\n path = path[:-len(self._subdomain)-1]\n return path\n\n @cached_property\n def FILES(self):\n return self._sub_post(lambda x: isinstance(x[1], cgi.FieldStorage))\n\n @cached_property\n def POST(self):\n return self._sub_post(lambda x: not isinstance(x[1], cgi.FieldStorage))\n\n def _sub_post(self, condition):\n post = super(Request, self).str_POST\n if isinstance(post, NoVars):\n return post\n return UnicodeMultiDict(MultiDict(filter(condition, post.items())),\n encoding=self.charset,\n errors=self.unicode_errors,\n decode_keys=self.decode_param_names)\n","sub_path":"insanities/web/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"166008852","text":"import json\n\nfrom QueryHandling.QueryProcess import processQuery\nfrom indexing.indexer import load_index\nfrom matching.Matching_functions import build_vectors, query_vector, getmatches\n\n\ndef loadQueries():\n file = open('../Documents/queries.txt', 'r')\n queries = file.read()\n file.close()\n return [q for q in queries.split('\\n') if q]\n\n\ndef loadRelevance():\n file = open('../Documents/relevance.txt', 'r')\n text = file.read()\n file.close()\n relevances = [r for r in text.split('\\n') if r]\n final_relevance = [relevance.split() for relevance in relevances]\n return final_relevance\n\n\ndef save_json(path, data):\n try:\n file = open(path, \"w\")\n file.write(json.dumps(data))\n file.close()\n return True\n\n except:\n print(\"EXCEPTION: while save JSON file: \" + path)\n return False\n\n\ndef load_json(path):\n try:\n file = open(path, \"r\")\n data = json.loads(file.read())\n file.close()\n return data\n except:\n print(\"EXCEPTION: while load JSON file: \" + path)\n return False\n\n\ndef test(Vectors, index):\n queries = loadQueries()\n relevances = loadRelevance()\n test_cases = {}\n final = 0\n for query, relevance in zip(queries, relevances):\n query = processQuery(query)\n query_terms = query.split()\n queryVector = query_vector(query_terms, index)\n results = getmatches(queryVector, Vectors)\n results = [x[1] for x in results]\n results = [r.replace(\".txt\", \"\") for r in results]\n shared_res = set(relevance) & set(results)\n total = len(shared_res)\n res = total / len(relevance)\n dif1 = len(results) - len(shared_res)\n dif1 /= 423\n res -= dif1\n test_cases[query] = res\n final += res\n\n final /= len(queries)\n return final\n\n\nif __name__ == '__main__':\n index = load_index('../indexfiles/index.json')\n Vectors = build_vectors(index)\n save_json('../indexfiles/Vectors.json', Vectors)\n results = test(Vectors, index)\n print(results)\n","sub_path":"Testing/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"576155627","text":"from openerp.osv import osv, fields\r\nfrom datetime import date\r\n#from openerp.addons.base_status.base_state import base_state\r\nimport time \r\nimport datetime\r\nimport logging\r\nfrom openerp.tools.translate import _\r\n\r\nfrom time import gmtime, strftime\r\n_logger = logging.getLogger(__name__)\r\n\r\nclass dincelproduct_inventory(osv.Model):\r\n\t_name = \"dincelproduct.inventory\"\r\n\t\r\n\tdef create_if(self, cr, uid, product_id, product_length, context=None):\r\n\t\t_obj=\tself.pool.get('dincelproduct.product')\r\n\t\t_ids = \t_obj.search(cr, uid, [('product_id', '=', product_id), ('product_len', '=', product_length)], limit=1)\r\n\t\tif _ids:\t\r\n\t\t\t_id=_ids[0]\r\n\t\telse:\r\n\t\t\tvals={\r\n\t\t\t\t'product_id':product_id,\r\n\t\t\t\t'product_len':product_length,\r\n\t\t\t}\r\n\t\t\tprod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)\t\r\n\t\t\tif prod:\r\n\t\t\t\tvals['name'] = prod.name\r\n\t\t\t \r\n\t\t\t_id = _obj.create(cr, uid, vals, context=context)\r\n\t\t\t\r\n\t\treturn _id\t\r\n\t\r\n\t#>>straignt qty no to LM nor M2 or other....eg 20 panels of 3,000mm, etc HERE 20=qty_qty \t\r\n\t#>>by production, by purchase, un-reserve, etc\r\n\tdef qty_increment(self, cr, uid, product_id, product_length, qty_qty, context=None):\r\n\t\t_obj\t= self.pool.get('dincelproduct.product')\r\n\t\t_id \t= self.create_if(cr, uid, product_id, product_length)\r\n\t\t_item \t= _obj.browse(cr, uid, _id)\r\n\t\t_qty_qty = float(_item.qty_qty)+float(qty_qty)\r\n\t\t_obj.write(cr, uid, [_id], {'qty_qty': _qty_qty}, context=context)\t\r\n\t\treturn True\r\n\r\n\t#>>straignt qty no to LM nor M2 or other....eg 20 panels of 3,000mm, etc HERE 20=qty_qty \t\r\n\t#>>by loss, by reserve, shipment, etc [note reserve==ship, no need to deduct when reserve is shipped]\r\n\tdef qty_decrement(self, cr, uid, product_id, product_length, qty_qty, context=None):\r\n\t\t_obj\t= self.pool.get('dincelproduct.product')\r\n\t\t_id \t= self.create_if(cr, uid, product_id, product_length)\r\n\t\t_item \t= _obj.browse(cr, uid, _id)\r\n\t\t_qty_qty = float(_item.qty_qty)-float(qty_qty)\r\n\t\t_obj.write(cr, uid, [_id], {'qty_qty': _qty_qty}, context=context)\t\r\n\t\treturn True\r\n\t\t\r\n\tdef qty_available(self, cr, uid, product_id, product_length, context=None):\r\n\t\t_obj\t= self.pool.get('dincelproduct.product')\r\n\t\t_id \t= self.create_if(cr, uid, product_id, product_length)\r\n\t\t_item \t= _obj.browse(cr, uid, _id)\r\n\t\treturn _item.qty_qty\r\n\t\t\r\nclass dincelproduct_product(osv.Model):\r\n\t_name = \"dincelproduct.product\"\r\n\t\r\n\t#def qty_reserved_net(self, cr, uid, ids, product_id, product_len, origin=None, context=None):\r\n\t#\treturn self.qty_stock_reserved(cr, uid, ids, product_id, product_len,origin=origin, context=context)\r\n\t'''context = context or {}\r\n\tqty_reserve=0\r\n\t\t \r\n\t_obj\t= self.pool.get('stock.move.tmp')\t\r\n\targs \t= [(\"product_id\", \"=\", product_id),(\"order_length\", \"=\", product_len),('state','=','reserve')]\r\n\ttmpids = _obj.search(cr, uid, args, context=context)\r\n\t#_logger.error(\"qty_reserved_netqty_reserved_net[\"+str(tmpids)+\"]args[\"+str(args)+\"]\")\r\n\tfor o in _obj.browse(cr, uid, tmpids, context=context):\r\n\t\tqty_reserve+=o.product_qty\r\n\t\r\n\t#qty_net = record.qty_available-qty_reserve\r\n\t\r\n\treturn qty_reserve\r\n\t'''\r\n\tdef qty_produced_net(self, cr, uid, ids, product_id, order_length, order_id, context=None):\r\n\t\tsql =\"SELECT SUM(product_qty) FROM stock_move_tmp WHERE move_type in('mo-sales','mo-stock') AND product_id='\"+str(product_id)+\"' AND order_id='\"+str(order_id)+\"'\"\r\n\t\tif order_length:\r\n\t\t\tsql += \" AND order_length=\"+str(int(order_length))+\" \" #>>>due to numeric/float fignure no quote added ''>>>\r\n\t\tcr.execute(sql)\r\n\t\tres = cr.fetchone()\r\n\t\tif res and res[0]!= None:\r\n\t\t\t_qty=(res[0])\r\n\t\t\tif order_length:\r\n\t\t\t\t_qty = int(_qty/((order_length)/1000))\r\n\t\telse:\r\n\t\t\t_qty=0\r\n\t\treturn \t_qty\r\n\t\t\r\n\tdef qty_delivered_net(self, cr, uid, ids, product_id, order_length, order_id, context=None):\r\n\t\tsql =\"SELECT SUM(product_qty) FROM stock_move_tmp WHERE move_type in('damage','lost','sales') AND product_id='\"+str(product_id)+\"' AND order_id='\"+str(order_id)+\"' \"\r\n\t\tif order_length:\r\n\t\t\tsql += \" AND order_length=\"+str(int(order_length))+\" \" #>>>due to numeric/float fignure no quote added ''>>>\r\n\t\t\r\n\t\tcr.execute(sql)\r\n\t\tres = cr.fetchone()\r\n\t\tif res and res[0]!= None:\r\n\t\t\t_qty=(res[0])\r\n\t\t\t#_logger.error(\"qty_delivered_netqty_delivered_netsql1ty111[\"+str(_qty)+\"]\")\r\n\t\t\tif order_length:\r\n\t\t\t\t_qty = int(_qty/((order_length)/1000))\r\n\t\t\t\t#_logger.error(\"qty_delivered_netqty_delivered_netsql2222[\"+str(_qty)+\"]\")\r\n\t\telse:\r\n\t\t\t_qty=0\r\n\t\treturn \t_qty\r\n\t\t\r\n\tdef qty_reserved_delivered_net(self, cr, uid, ids, product_id, order_length, order_id, context=None):\r\n\t\tsql =\"SELECT SUM(product_qty) FROM stock_move_tmp WHERE move_type in('reserve-deliverd') AND product_id='\"+str(product_id)+\"' AND order_id='\"+str(order_id)+\"' \"\r\n\t\tif order_length:\r\n\t\t\tsql += \" AND order_length=\"+str(int(order_length))+\" \" #>>>due to numeric/float fignure no quote added ''>>>\r\n\t\t\r\n\t\tcr.execute(sql)\r\n\t\tres = cr.fetchone()\r\n\t\tif res and res[0]!= None:\r\n\t\t\t_qty=(res[0])\r\n\t\t\tif order_length:\r\n\t\t\t\t_qty = int(_qty/((order_length)/1000))\r\n\t\telse:\r\n\t\t\t_qty=0\r\n\t\treturn \t_qty\r\n\t\r\n\t#for available but less reserved....\r\n\tdef qty_stock_reserved_new_all(self, cr, uid, ids, product_id, order_length, context=None):\r\n\t\tsql =\"SELECT SUM(product_qty) FROM stock_move_tmp WHERE move_type in('reserve') AND product_id='\"+str(product_id)+\"' \"\r\n\t\tif order_length:\r\n\t\t\tsql += \" AND order_length='\"+str(int(order_length))+\"' \" #>>>due to numeric/float fignure no quote added ''>>>\r\n\t\tcr.execute(sql)\r\n\t\tres = cr.fetchone()\r\n\t\tif res and res[0]!= None:\r\n\t\t\t_qty=(res[0])\r\n\t\t\tif order_length:\r\n\t\t\t\t_qty = int(_qty/((order_length)/1000))\r\n\t\telse:\r\n\t\t\t_qty=0\r\n\t\treturn \t_qty\t\r\n\t\t\r\n\tdef qty_stock_reserved_new(self, cr, uid, ids, product_id, order_length, order_id, context=None):\r\n\t\tsql =\"SELECT SUM(product_qty) FROM stock_move_tmp WHERE move_type in('reserve') AND product_id='\"+str(product_id)+\"' AND order_id='\"+str(order_id)+\"' \"\r\n\t\tif order_length:\r\n\t\t\tsql += \" AND order_length='\"+str(int(order_length))+\"' \" #>>>due to numeric/float fignure no quote added ''>>>\r\n\t\tcr.execute(sql)\r\n\t\tres = cr.fetchone()\r\n\t\tif res and res[0]!= None:\r\n\t\t\t_qty=(res[0])\r\n\t\t\tif order_length:\r\n\t\t\t\t_qty = int(_qty/((order_length)/1000))\r\n\t\telse:\r\n\t\t\t_qty=0\r\n\t\treturn \t_qty\t\r\n\t\t\r\n\tdef qty_stock_reservedxx(self, cr, uid, ids, product_id, product_len, origin=None, context=None):\r\n\t\tcontext = context or {}\r\n\t\t_qty\t= 0 \r\n\t\tif product_id:\r\n\t\t\t_po = self.pool.get('product.product').browse(cr, uid, product_id, context=context)\t\r\n\t\t\targs \t= [(\"product_id\", \"=\", product_id),('state','=','reserve')]\r\n\r\n\t\t\tif _po.x_prod_cat in['stocklength','customlength']:\t#==\"customlength\":\r\n\t\t\t\targs += [(\"order_length\", \"=\", product_len)]\r\n\r\n\t\t\tif not origin:\r\n\t\t\t\targs += [(\"origin\", \"=\", origin)]\r\n\t\t\t\t\r\n\t\t\t_obj\t= self.pool.get('stock.move.tmp')\t\r\n\t\t\t\r\n\t\t\ttmpids = _obj.search(cr, uid, args, context=context)\r\n\t\t\tif tmpids:\r\n\t\t\t\tfor o in _obj.browse(cr, uid, tmpids, context=context):\r\n\t\t\t\t\tif o.order_length:\r\n\t\t\t\t\t\t_qty+=(o.product_qty/(0.001*o.order_length))\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\t_qty+=o.product_qty\r\n\t\treturn _qty\r\n\t\t\r\n\tdef qty_stock_onhand(self, cr, uid, ids, product_id, product_len =False, context=None):\r\n\t\tcontext = context or {}\r\n\t\tqty_in\t= 0\r\n\t\tqty_out\t= 0\t \r\n\t\t\r\n\t\t_obj\t= self.pool.get('stock.move.tmp')\t\r\n\t\targs \t= [(\"product_id\", \"=\", product_id),('state','in',['produced', 'purchased'])]\r\n\t\tif product_len:\r\n\t\t\targs+=[(\"order_length\", \"=\", product_len)]\r\n\t\t\t\r\n\t\ttmpids = _obj.search(cr, uid, args, context=context)\r\n\t\tfor o in _obj.browse(cr, uid, tmpids, context=context):\r\n\t\t\tif o.order_length:\r\n\t\t\t\tqty_in+=(o.product_qty/(0.001*o.order_length))\r\n\t\t\telse:\r\n\t\t\t\tqty_in+=o.product_qty\r\n\t\t\r\n\t\targs \t= [(\"product_id\", \"=\", product_id),('state','in',['delivered', 'damaged'])]\r\n\t\tif product_len:\r\n\t\t\targs+=[(\"order_length\", \"=\", product_len)]\r\n\t\ttmpids = _obj.search(cr, uid, args, context=context)\r\n\t\tfor o in _obj.browse(cr, uid, tmpids, context=context):\r\n\t\t\tif o.order_length:\r\n\t\t\t\tqty_out+=(o.product_qty/(0.001*o.order_length))\r\n\t\t\telse:\r\n\t\t\t\tqty_out+=o.product_qty\r\n\t\t\r\n\t\t\r\n\t\treturn qty_in-qty_out\r\n\t\t\r\n\tdef _qty_panel_net(self, cr, uid, ids, values, arg, context):\r\n\t\tcontext = context or {}\r\n\t\tx={}\r\n\t\tfor record in self.browse(cr, uid, ids):\r\n\t\t\tif record.product_len>0:\r\n\t\t\t\tx[record.id]=record.qty_available/(record.product_len*0.001)\r\n\t\t\telse:\r\n\t\t\t\tx[record.id]=0\r\n\t\treturn x\t\t\r\n\t\r\n\tdef _qty_available_net(self, cr, uid, ids, values, arg, context):\r\n\t\tcontext = context or {}\r\n\t\tqty_reserve=0\r\n\t\tqty_net=0\r\n\t\tx={}\r\n\t\tfor record in self.browse(cr, uid, ids):\r\n\t\t\t \r\n\t\t\tqty_reserve = 0#self.qty_stock_reserved_new_all(cr, uid,ids,record.product_id.id, record.product_len)\r\n\t\t\t\r\n\t\t\tif record.product_len:\r\n\t\t\t\tqty_avail=(record.qty_available/(record.product_len*0.001))\r\n\t\t\telse:\r\n\t\t\t\tqty_avail=record.qty_available\r\n\t\t\tx[record.id]=qty_avail-qty_reserve\r\n\t\treturn x\r\n\t_columns = {\r\n\t\t'name': fields.char('Name'),\r\n\t\t'product_id': fields.many2one('product.product', 'Product'),\r\n\t\t'product_len': fields.float('Length'),\r\n\t\t'qty_available': fields.float('Qty LM'),\r\n\t\t'qty_qty': fields.float('Qty Qty'), #qty net in the stock,\r\n\t\t'is_custom': fields.boolean('Is Custom Length'),\r\n\t\t'qty_panel': fields.function(_qty_panel_net, method=True, string='Qty',type='float' ),\r\n\t\t'qty_available_net': fields.function(_qty_available_net, method=True, string='Quantity On Hand',type='float' ),\r\n\t\t'product_uom': fields.many2one('product.uom', 'Unit of Measure'),\r\n\t}\t\r\n\t_sql_constraints = [\r\n\t\t('product_uniq', 'unique(product_id, product_len)', 'The Product Length is not Unique!'),\r\n\t\t]\r\n\t_defaults = {\r\n\t\t'is_custom': False,\r\n\t}\r\n\t\r\n\t#def record_stok_move_new(self, cr, uid, order_id, product_id, movetype, qty, product_len =False, context=None):\r\n\tdef record_stock_mrp_new(self, cr, uid, production_id, product_id, product_qty,qty_origin, movetype, context=None): \r\n\t\t#DO NOTE RE CALC QTY MOVE ---already calculated in function call\r\n\t\t\r\n\t\t_mrp = self.pool.get('mrp.production').browse(cr, uid, production_id, context=context)\t\r\n\t\t \t\t\r\n\t\tvals = {\r\n\t\t\t'product_qty': product_qty,\r\n\t\t\t'qty_origin':qty_origin,\r\n\t\t\t'product_id': product_id,\r\n\t\t\t'product_uom': _mrp.product_uom.id,#product_uom_id,\r\n\t\t\t'origin': _mrp.origin, \r\n\t\t\t'order_length': _mrp.x_order_length,\r\n\t\t\t'location_dest_id':_mrp.location_dest_id.id,\r\n\t\t\t'move_type': movetype,\r\n\t\t}\r\n\t\tif _mrp.x_sale_order_id:\r\n\t\t\tvals['order_id'] = _mrp.x_sale_order_id.id\r\n\t\t\t\r\n\t\t#warehouse_dest_id--> TODO ..or derive from location_dest_id???\r\n\t\tif movetype == 'mo-stock' or movetype == 'mo-sales':\r\n\t\t\tvals['state']= \"produced\"\t\t#,_state=\"produced\"\r\n\t\t\t\r\n\t\tself.pool.get('stock.move.tmp').create(cr, uid, vals, context=context)\r\n\t\r\n\tdef record_stock_order_reserve_new(self, cr, uid, order_id, product_id, product_qty,qty_origin,_uom,_length, movetype, context=None): \r\n\t\t#DO NOTE RE CALC QTY MOVE ---already calculated in function call\r\n\t\t#_state=\"\"\r\n\t\t\r\n\t\t_so = self.pool.get('sale.order').browse(cr, uid, order_id, context=context)\t\r\n\t\t \t\t\r\n\t\tvals = {\r\n\t\t\t'product_qty': product_qty,\r\n\t\t\t'qty_origin':qty_origin,\r\n\t\t\t'product_id': product_id,\r\n\t\t\t'product_uom': _uom,#product_uom_id,\r\n\t\t\t'origin': _so.name, \r\n\t\t\t'order_length': _length,\r\n\t\t\t'move_type': movetype, #reserve\r\n\t\t}\r\n\t\t#'location_dest_id':_mrp.location_dest_id.id,\r\n\t\t#if _mrp.x_sale_order_id:\r\n\t\tvals['order_id'] = order_id\r\n\t\t\r\n\t\tvals['state']= \"reserve\"\t\t#,_state=\"produced\"\r\n\t\t\t\r\n\t\tself.pool.get('stock.move.tmp').create(cr, uid, vals, context=context)\r\n\t\t\r\n\t#def record_stock_delivered(self, cr, uid, order_id, product_id, product_qty, movetype, context=None): \r\n\tdef record_stock_shipped(self, cr, uid, order_id, product_id, uom_id, product_qty,qty_origin, order_length, _dest_id, _type, context=None):\r\n\t#DO NOTE RE CALC QTY MOVE ---already calculated in function call\r\n\t\t_order = self.pool.get('sale.order').browse(cr, uid, order_id, context=context)\t\r\n\t\t \t\t\r\n\t\tvals = {\r\n\t\t\t'product_qty': product_qty,\r\n\t\t\t'qty_origin':qty_origin,\r\n\t\t\t'product_id': product_id,\r\n\t\t\t'product_uom': uom_id,#product_uom_id,\r\n\t\t\t'origin': _order.name, \r\n\t\t\t'order_length': order_length,\r\n\t\t\t'order_id':order_id,\r\n\t\t\t'move_type': _type#'sales', #>>sales delivery type\r\n\t\t}\r\n\t\t\r\n\t\tif _dest_id:\r\n\t\t\tvals['location_dest_id']=_dest_id\r\n\t\t#warehouse_dest_id--> TODO ..or derive from location_dest_id???\r\n\t\t#if movetype == 'mo-stock':\r\n\t\tvals['state']= \"delivered\"\t\t#,_state=\"produced\"\r\n\t\t\t\r\n\t\tself.pool.get('stock.move.tmp').create(cr, uid, vals, context=context)\r\n\r\n\t\t\r\n\tdef record_stok_move_xx(self, cr, uid, origin, product_id, product_uom_id, movetype, qty, product_len =False, context=None):\r\n\t\t#if not product_len:\r\n\t\t#product_len= 0\r\n\t\t#DO NOTE RE CALC QTY MOVE ---alrady calculated in function call\r\n\t\t_len=0\r\n\t\t_opt=\"\"\r\n\t\t\r\n\t\t_po = self.pool.get('product.product').browse(cr, uid, product_id, context=context)\t\r\n\t\t\r\n\t\tis_custom \t= False\r\n\t\tif _po.x_prod_cat in['stocklength','customlength']:\t#==\"customlength\":\r\n\t\t\t_len \t= product_len\r\n\t\t\t#qty \t= qty*product_len*0.001#NONONONO0000\r\n\t\t\tif _po.x_prod_cat=='customlength':\r\n\t\t\t\tis_custom \t= True\r\n\t\targs = [(\"product_id\", \"=\", product_id),(\"product_len\", \"=\", _len)]\t\t\t\r\n\t\tvals = {\r\n\t\t\t'product_qty': qty,\r\n\t\t\t'product_id': product_id,\r\n\t\t\t'product_uom': product_uom_id,\r\n\t\t\t'origin': origin, \r\n\t\t\t'order_length': product_len,\r\n\t\t\t'state': movetype,\r\n\t\t}\r\n\t\t#_logger.error(\"stockproduct_uomproduct_uom_view_id[\"+str(vals)+\"]\")\r\n\t\tself.pool.get('stock.move.tmp').create(cr, uid, vals, context=context)\r\n\t\tif movetype in ['produced','add']:\r\n\t\t\t_opt=\"add\"\r\n\t\t#elif movetype in ['produced','add']:\t\r\n\t\t#if movetype='produced':\r\n\t\t#\tself.pool.get('stock.move.tmp').create(cr, uid, vals, context=context)\r\n\t\tresult = self.search(cr, uid, args, context=context)\r\n\t\tif result:\r\n\t\t\titem = self.browse(cr, uid, result[0], context=context)\r\n\t\t\tif _opt==\"add\":\r\n\t\t\t\tqty_available = item.qty_available+qty\r\n\t\t\telse:\r\n\t\t\t\tqty_available = item.qty_available-qty\r\n\t\t\tself.write(cr, uid, [item.id], {'qty_available': qty_available}, context=context)\r\n\t\telse:\r\n\t\t\t#po = self.pool.get('product.product').browse(cr, uid, product_id, context=context)\r\n\t\t\tif _opt==\"add\":\r\n\t\t\t\tqty_available = qty\r\n\t\t\telse:\t\r\n\t\t\t\tqty_available = -qty\r\n\t\t\tvals={\r\n\t\t\t\t'qty_available':qty_available,\r\n\t\t\t\t'product_id':product_id,\r\n\t\t\t\t'product_len':product_len,\r\n\t\t\t\t'is_custom':is_custom,\r\n\t\t\t\t'name':_po.name,\r\n\t\t\t}\r\n\t\t\tself.create(cr, uid, vals, context=context)\r\n\t\t#res = {}\r\n\r\nclass dincelproduct_stockmove(osv.Model):\t\r\n\t_inherit = \"stock.move\"\r\n\t_columns = {\t\r\n\t\t'x_order_length':fields.float(\"Ordered Length\"),\r\n\t}\r\n\t_defaults = {\r\n\t\t'x_order_length': 0,\r\n\t}\r\n\r\nclass dincelproduct_stockmove_tmp(osv.Model):\t\r\n\t_name = \"stock.move.tmp\"\r\n\t_columns = {\r\n\t\t'date':fields.datetime(\"Date\"),\r\n\t\t'origin': fields.char(\"Source\"),\r\n\t\t'partner_id': fields.many2one('res.partner', 'Partner'),\r\n\t\t'warehouse_id': fields.many2one('stock.warehouse', 'Source Warehouse'),\r\n\t\t'warehouse_dest_id': fields.many2one('stock.warehouse', 'Dest Warehouse'),\r\n\t\t'location_id': fields.many2one('stock.location', 'Source Location'),\r\n\t\t'location_dest_id': fields.many2one('stock.location', 'Dest Location'),\r\n\t\t'product_id': fields.many2one('product.product', 'Product'),\r\n\t\t'product_uom': fields.many2one('product.uom', 'Unit of Measure'),\r\n\t\t'product_qty': fields.float('Quantity'),\r\n\t\t'qty_origin': fields.float('Origin Qty'), #>> this is origin qty, non-LM in case of P-1,[product_qty = qty_origin >> in case of accs]\r\n\t\t#'qty_in': fields.float('Qty In'),\t -->>N/A this is calculated in runtime by using \"move_type\" value logic\r\n\t\t#'qty_out': fields.float('Qty Out'), -->>N/A this is calculated in runtime by using \"move_type\" value logic\r\n\t\t'order_length':fields.float(\"Ordered Length\"),\r\n\t\t'order_id': fields.many2one('sale.order', 'Sale Order Id'),\r\n\t\t'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type'),\r\n\t\t'move_type':fields.selection([\r\n\t\t\t\t\t('mo-sales','MO Sales'), #manufactured for sales\r\n\t\t\t\t\t('mo-stock','MO Stock'), #manufactured for stock item (no sales item assigned)\r\n\t\t\t\t\t('purchase','PO Stock'),\r\n\t\t\t\t\t('internal','Internal Stock'),\r\n\t\t\t\t\t('damage','Damage Stock'),\r\n\t\t\t\t\t('lost','Lost Stock'),\r\n\t\t\t\t\t('sales','Sales Delivered Stock'), #deliverd to customer\r\n\t\t\t\t\t('reserve', 'Sales Reserve'),\t\t#reserver for specific sales item\r\n\t\t\t\t\t('reserve-deliverd', 'Reserve Delivered'),\t\t#reserve and delivered for specific sales item\r\n\t\t\t\t\t],'Move Type'),\r\n\t\t'state': fields.selection([\r\n\t\t\t\t\t\t\t\t('reserve', 'Reserve'),\r\n\t\t\t\t\t\t\t\t('produced', 'Produced'),\r\n\t\t\t\t\t\t\t\t('purchased', 'Purchased'),\r\n\t\t\t\t\t\t\t\t('damaged', 'Damaged'),\r\n\t\t\t\t\t\t\t\t('delivered', 'Delivered'),\r\n\t\t\t\t\t\t\t\t('cancel', 'Cancelled'),\r\n\t\t\t\t\t\t\t\t('done', 'Move Done Delivered') \r\n\t\t\t\t\t\t\t\t], 'Status'), #todo not in USE**********\r\n\t}\r\n\t_defaults = {\r\n\t\t'qty_in':0,\r\n\t\t'qty_out':0,\r\n\t\t'date': datetime.datetime.now()#lambda *a: time.strftime('%Y-%m-%d %H:%M:%S.%f'),#fields.date.context_today,\r\n\t}\r\n\t_order = 'date desc'\t\r\n\t","sub_path":"dincelproduct/dincelproduct1.py","file_name":"dincelproduct1.py","file_ext":"py","file_size_in_byte":16840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"625512677","text":"def leiaint(msg):\n from termcolor import colored\n nume=0\n num=str(input(msg))\n while not num.isnumeric():\n num=input(colored('Error!!, type only integers numbers:','red'))\n nume=num\n return nume\n\nn=leiaint('Type a number:')\nprint(f'You typed the number {n}')\n","sub_path":"#100.1-Funções(Parte 2)/#104 - Validando entrada de dados em Python.py","file_name":"#104 - Validando entrada de dados em Python.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"150181826","text":"from copy import deepcopy\nimport logging\n\nfrom lintreview import git\nfrom lintreview.lint_config import build_review_config, load_config\nfrom lintreview.processor import Processor\nfrom lintreview.repo import GithubRepository\n\nlint_config = load_config()\nlogging.basicConfig(\n level=logging.INFO, format=\"%(asctime)s : %(levelname)s : %(name)s - %(message)s\"\n)\nlog = logging.getLogger(name=__name__)\n\n\ndef process_pull_request(user, repo_name, number, lintrc):\n review_config = build_review_config(lintrc, deepcopy(lint_config))\n if len(review_config.linters()) == 0:\n log.info(\"No configured linters, skipping processing.\")\n return\n\n try:\n log.info(\n f\"Loading pull request data from github. user={user} repo={repo_name} number={number}\"\n )\n\n repo = GithubRepository(lint_config, user, repo_name)\n pull_request = repo.pull_request(number)\n\n clone_url = pull_request.clone_url\n\n pr_head = pull_request.head\n target_branch = pull_request.target_branch\n\n if target_branch in review_config.ignore_branches():\n log.info(\n \"Pull request into ignored branch %s, skipping review.\", target_branch\n )\n return\n\n repo.create_status(pr_head, \"pending\", \"Lintreview processing\")\n\n # Clone/Update repository\n target_path = git.get_repo_path(user, repo_name, number, lint_config)\n git.clone_or_update(lint_config, clone_url, target_path, pr_head)\n\n processor = Processor(repo, pull_request, target_path, review_config)\n processor.load_changes()\n processor.run_tools()\n processor.publish()\n\n log.info(f\"Completed lint processing for {user}/{repo}/{number}\")\n\n except Exception as e:\n log.exception(e)\n finally:\n try:\n git.destroy(target_path)\n log.info(f\"Cleaned up pull request {user}/{repo}/{number}\")\n except Exception as e:\n log.exception(e)\n","sub_path":"lintreview/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"574024972","text":"import os\nimport sys\nimport django\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(BASE_DIR)\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", 'ultron.settings')\ndjango.setup()\n\nfrom django.contrib.auth import get_user_model\nfrom django.utils import timezone\n\nfrom client_api.models import Cpu, CpuCore\n\nimport random\n\n\ndef main():\n u = get_user_model().objects.first()\n\n for i in range(1000):\n cpu = Cpu.objects.create(\n user=u,\n mac_addr='as-12-62-b3-j1-Q8',\n time=timezone.now(),\n cores=2,\n clock=3.5\n )\n for j in range(2):\n CpuCore.objects.create(cpu=cpu, num=j, usage=random.choice(range(1001))/10)\n\n print(\"{0}'th cpu have created.\".format(i))\n print('done.')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"client_api/cpu_maker.py","file_name":"cpu_maker.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"441248592","text":"import unittest\n\nimport numpy as np\nfrom numpy.testing import assert_allclose\n\nfrom spitfire.chemistry.mechanism import ChemicalMechanismSpec\nfrom spitfire.chemistry.flamelet import Flamelet\nfrom test.utilities import load_chemistry_gold_standard, ignore_warnings\n\n\ndef load_gold_standard(variable_name):\n return load_chemistry_gold_standard('flamelet_nonadiabatic_unsteady_solve', variable_name)\n\n\nclass UnsteadySolveTest(unittest.TestCase):\n @ignore_warnings\n def test_unsteady_solve(self):\n tolerance = 1.e-8\n\n m = ChemicalMechanismSpec('hydrogen', 'burke')\n\n pressure = 101325.\n\n air = m.stream(stp_air=True)\n air.TP = 1400., pressure\n\n zstoich = 0.1\n\n fuel = m.mix_fuels_for_stoich_mixture_fraction(m.stream('X', 'H2:1'), m.stream('X', 'N2:1'), zstoich, air)\n fuel.TP = 300., pressure\n\n chi_max = 1.e3\n\n npts_interior = 32\n\n ft = Flamelet(mech_spec=m,\n pressure=pressure,\n oxy_stream=air,\n fuel_stream=fuel,\n max_dissipation_rate=chi_max,\n engine='griffon',\n grid_points=npts_interior + 2,\n grid_cluster_intensity=4.,\n initial_condition='unreacted',\n convection_coefficient=5.e4,\n convection_temperature=350.,\n radiation_temperature=350.,\n radiative_emissivity=1.,\n heat_transfer='nonadiabatic')\n\n ft.insitu_process_quantity(['temperature', 'mass fractions'])\n ft.integrate_to_steady(write_log=False)\n\n t = ft.solution_times\n T = ft.trajectory_data('temperature').ravel()\n Y = np.ndarray((npts_interior * t.size, m.gas.n_species))\n for idx, s in enumerate(m.gas.species_names):\n Y[:, idx] = ft.trajectory_data('mass fraction ' + s).ravel()\n\n gold_T = load_gold_standard('temperature')\n gold_Y = load_gold_standard('mass_fractions')\n\n self.assertIsNone(assert_allclose(gold_T, T,\n rtol=tolerance,\n atol=tolerance,\n err_msg='temperature diff',\n verbose=True))\n\n self.assertIsNone(assert_allclose(gold_Y, Y,\n rtol=tolerance,\n atol=tolerance,\n err_msg='mass fractions diff',\n verbose=True))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/chemistry/test_flamelet_nonadiabatic_unsteady_solve.py","file_name":"test_flamelet_nonadiabatic_unsteady_solve.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"576601807","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import division, print_function, absolute_import\n\nimport tflearn\nimport h5py, os\n\n# Residual blocks\n# 32 layers: n=5, 56 layers: n=9, 110 layers: n=18\nn = 5\n\n# Data loading\n# from tflearn.datasets import cifar10\n# (X, Y), (testX, testY) = cifar10.load_data()\n# Y = tflearn.data_utils.to_categorical(Y)\n# testY = tflearn.data_utils.to_categorical(testY)\n\nbase_dir = os.path.expanduser(\"/home/utopia/CVDATA/German_AI_Challenge_2018/session1\")\npath_training = os.path.join(base_dir, 'training.h5')\npath_validation = os.path.join(base_dir, 'validation.h5')\npath_s18_train = os.path.join(base_dir, 's18_train.h5')\npath_s18_val = os.path.join(base_dir, 's18_val.h5')\npath_s2_train_index = os.path.join(base_dir, 's2_train_index.h5')\npath_s2_val_index = os.path.join(base_dir, 's2_val_index.h5')\n\nfid_training = h5py.File(path_training, 'r')\nfid_validation = h5py.File(path_validation, 'r')\ns18_train = h5py.File(path_s18_train, 'r')\ns18_val = h5py.File(path_s18_val, 'r')\ns2_train_index = h5py.File(path_s2_train_index, 'r')\ns2_val_index = h5py.File(path_s2_val_index, 'r')\n\n# X = s18_train['s18_train']\n# X_test = s18_val['s18_val']\n\nX = s2_train_index['s2_train_index']\nX_test = s2_val_index['s2_val_index']\nY = fid_training['label']\nY_test = fid_validation['label']\n\n# Real-time data preprocessing\nimg_prep = tflearn.ImagePreprocessing()\nimg_prep.add_featurewise_zero_center(per_channel=True)\n\n# Real-time data augmentation\nimg_aug = tflearn.ImageAugmentation()\nimg_aug.add_random_flip_leftright()\nimg_aug.add_random_crop([32, 32], padding=4)\n\n# Building Residual Network\nnet = tflearn.input_data(shape=[None, 32, 32, 3] # ,\n # data_preprocessing=img_prep,\n # data_augmentation=img_aug\n )\nnet = tflearn.conv_2d(net, 16, 3, regularizer='L2', weight_decay=0.0001)\nnet = tflearn.resnext_block(net, n, 16, 32)\nnet = tflearn.resnext_block(net, 1, 32, 32, downsample=True)\nnet = tflearn.resnext_block(net, n - 1, 32, 32)\nnet = tflearn.resnext_block(net, 1, 64, 32, downsample=True)\nnet = tflearn.resnext_block(net, n - 1, 64, 32)\nnet = tflearn.batch_normalization(net)\nnet = tflearn.activation(net, 'relu')\nnet = tflearn.global_avg_pool(net)\n# Regression\nnet = tflearn.fully_connected(net, 17, activation='softmax')\nopt = tflearn.Momentum(0.1, lr_decay=0.1, decay_step=32000, staircase=True)\nnet = tflearn.regression(net, optimizer=opt, loss='categorical_crossentropy')\n# Training\nmodel = tflearn.DNN(net, tensorboard_verbose=0,\n checkpoint_path='model_ResNeXt5_s2index_epoch20', max_checkpoints=100,\n clip_gradients=0.)\n\n# model.load('lcz42_20181218_ResNeXt5_epoch10.tfl')\nprint('Load pre-existing model, restoring all weights')\nmodel.fit(X, Y, n_epoch=20, validation_set=(X_test, Y_test),\n show_metric=True, batch_size=128, shuffle=True,\n run_id='ResNeXt5_s2index_epoch20')\nmodel.save(\"lcz42_20181218_ResNeXt5_s2index_epoch20.tfl\")\n\nfid_training.close()\nfid_validation.close()\ns18_train.close()\ns18_val.close()\n","sub_path":"ResNeXt_LCZ42.py","file_name":"ResNeXt_LCZ42.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"132633494","text":"\"\"\"\nDemonstration of softmax selection policy for an n-armed bandit game\n- each arm is randomly assigned a reward probability\n- when an arm is selected, run n-trials and increment reward if random prob < the arm's prob\n- for every training iteration, select arm based on sampling of softmax of historical mean rewards\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom bandit_helper import softmax, generate_reward\n\nTRAINING_ITERATIONS = 500\nN_ARMS = 10 # number of arms\nARM_PROB = np.random.rand(N_ARMS) # hidden prob associated with each arm\n\n\ndef train_and_draw():\n \"\"\"\n run softmax selection for TRAINING_ITERATIONS and plot running mean\n \"\"\"\n list_action_values = np.ones(N_ARMS) # index=action, value=avg reward\n counts = np.zeros(N_ARMS)\n # initialise av distribution to be uniform at outset\n av_softmax = np.zeros(N_ARMS) # prob. dist of action_values\n av_softmax[:] = 1.0 / N_ARMS\n\n plt.xlabel('Plays')\n plt.ylabel('Avg Rewards')\n\n hist_reward = []\n for i in range(TRAINING_ITERATIONS):\n choice = np.random.choice(list(range(N_ARMS)), p=av_softmax)\n counts[choice] += 1\n k = counts[choice]\n rwd = generate_reward(ARM_PROB[choice])\n old_avg = list_action_values[choice]\n new_avg = old_avg + (1/k) * (rwd - old_avg)\n list_action_values[choice] = new_avg\n av_softmax = softmax(list_action_values)\n hist_reward.append(rwd)\n plt.scatter(i, np.mean(hist_reward))\n\n plt.show()\n\n\nif __name__ == '__main__':\n train_and_draw()\n","sub_path":"bandit_softmax.py","file_name":"bandit_softmax.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"76445082","text":"import os\nimport torch\nfrom torchvision import transforms\nfrom PIL import Image, ImageEnhance\nfrom PIL.ImageOps import invert\nfrom PIL.ImageFilter import GaussianBlur\n\n\nIMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.tif')\n\n\ndef ensure_dir(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\n\ndef sketch_filter(img, blur_radius=0.8, brightness_ratio=2, contrast_ratio=2):\n \"\"\" \n generate sketch images by applying filters to the photograph images.\n tested range of parameters:\n blur_radius - 0.8~1.5\n brightness_offset - 1.5~2.0\n contrast_offset - 1.5~3.0\n \"\"\"\n to_tensor = transforms.ToTensor()\n to_pil = transforms.ToPILImage()\n\n img_tensor_orig = to_tensor(img)\n img_blur = img.filter(GaussianBlur(blur_radius))\n img_tensor_blur = to_tensor(img_blur)\n\n img_mean = (1 + img_tensor_orig - img_tensor_blur) / 2\n\n img = to_pil(img_mean)\n\n img = ImageEnhance.Brightness(img).enhance(brightness_ratio)\n img = ImageEnhance.Contrast(img).enhance(contrast_ratio)\n \n return img\n\n\nif __name__ == '__main__':\n # test: sketch filter\n filename = '000001.jpg'\n img_dir = '../data/CelebA/img/img_align_celeba/'\n img_path = os.path.join(img_dir, filename)\n img_orig = Image.open(img_path)\n\n img_result = sketch_filter(img_orig)\n img_result.show()\n \n ","sub_path":"utils/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"188980621","text":"# 13 利用PCA来简化数据\r\n# PCA首先进行坐标系转换,然后在新的坐标系中选择具有较大方差的维度作为主要特征候选。\r\n# 例如,选取的第一个新坐标轴是原始数据中方差最大的方向。然后再选择与第一个新坐标轴正交的次大方差的第二个坐标轴。\r\n# 对比决策树:每一个根节点的选择都是在当前分类的数据情况下选择信息增益率最大的维度,该维度是原始数据特征的某一个特征。\r\n# PCA选择的新坐标轴不一定是原始特征的子集!\r\n# 那么,可以用PCA处理后选出新特征,再用决策树分类吗?能否为每个类选择出最合适的特征子集呢???\r\n# PCA降维处理后的信息损失评估?有什么注意事项吗?能否增加某些惩罚项防止数据信息损失较大?\r\n# 2维PCA可以可视化显示。但是,多维数据怎么观测在哪一个维度上分类效果更好?怎么利用PCA为每一个类找出最优特征子集?\r\n# 基于PCA的特性,特征权重也可以方差计算。一个类一个类逐个特征地找?\r\n# 决策树每次分类都是只根据一个特征根节点来对整个数据集进行划分。在同一层次,能否同时根据多个特征进行不同类的划分?\r\n# 就是说,每一层同时进行多个类别划分,每个特征都是对应各个类别最有贡献度的特征,这样比随机森林复杂度低、准确率高吧?\r\n# 上述是:决策树并多分类 算法设计主要思想。\r\n# K-NN算法每次都要进行全数据集的距离计算,这样算法效率太低了!能否事先用聚类对数据集进行划分,\r\n# 然后再用监督学习算法训练模型?怎么改进K-NN呢?计算各个类中心,离谁近就是哪家的呗?这是 K均值聚类?\r\n# K-NN算法每次都是进行距离度量,修改样本相似性度量标准,如:向量内积。 既然用到向量内积的话,那么也可以进行高维投影,\r\n# 然后使用“核技巧”计算样本相似性?这样就是 K-NN+核 啦。也可以使用信息熵度量。\r\n# 我发现算法的灵活使用主要就是算法思想的灵活组合嘛。\r\n# SVM多分类器~~~\r\n\r\n# 13-1 PCA算法:numpy中模块linalg的eig()方法,求解特征向量和特征值。\r\n\r\nfrom numpy import *\r\n\r\ndef loadDataSet(filename):\r\n fr = open(filename)\r\n stringArr = [line.strip().split('\\t') for line in fr.readlines()]\r\n datArr = [map(float, line) for line in stringArr] # 矩阵批处理\r\n return datArr\r\n\r\n\r\ndef pca(dataMat, topNFeat = 9999): # 输入要灵活...\r\n # 每列计算均值,得到1XN矩阵\r\n meanVals = mean(dataMat, axis=0)\r\n meanRemoved = dataMat - meanVals\r\n #\r\n covMat = cov(meanRemoved, rowvar=0)\r\n eigVals, eigVects = linalg.eig(mat(covMat))\r\n eigValInd = argsort(eigVals)\r\n eigValInd = eigValInd[:-(topNFeat + 1):-1]\r\n reEigVects = eigVects[:, eigValInd]\r\n lowDDataMat = meanRemoved * reEigVects\r\n reconMat = (lowDDataMat * reEigVects.T) + meanVals\r\n return lowDDataMat, reconMat\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"424622968","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('register/', views.register_view, name='register'),\n path('login/', views.login_view, name='login'),\n path('logout/', views.logout_view, name='logout'),\n path('create/', views.create_profile, name='create'),\n path('profile/', views.view_profile, name='profile'),\n path('update/', views.update_profile, name='update'),\n path('delete/', views.delete_profile, name='delete'),\n]\n","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"66286330","text":"# -*- coding: utf-8 -*-\nimport scrapy\n# 从...路径,引入...类\nfrom ITcast.items import ItcastItem\n\nclass ItcastSpider(scrapy.Spider):\n # 爬虫名,启动爬虫时需要的参数*必需\n name = \"itcast\"\n # 爬取域范围,允许爬虫在这个域名下进行爬取(可选)\n allowed_domains = [\"http://www.itcast.cn\"] #爬虫允许域的范围\n # 起始url列表,爬虫执行后第一批请求,将从这个列表里获取\n start_urls = [\"http://www.itcast.cn/channel/teacher.shtml\"] #爬虫第一次启动时会从这个列表里开始抓取\n\n # 处理响应文件\n def parse(self, response):\n # 节点列表\n node_list = response.xpath(\"//div[@class='li_txt']\")\n\n #用来存储所有的item字段的\n items = []\n for node in node_list:\n # 创建item字段对象,用来存储信息\n item = ItcastItem()\n # .extract() 将xpath对象转换为Unicode字符串\n name = node.xpath(\"./h3/text()\").extract()\n title = node.xpath(\"./h4/text()\").extract()\n info = node.xpath(\"./p/text()\").extract()\n\n item[\"name\"] = name[0]\n item[\"title\"] = title[0]\n item[\"info\"] = info[0]\n items.append(item)\n\n return items\n # pass\n","sub_path":"ITcast/ITcast/spiders/itcast.py","file_name":"itcast.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"436457603","text":"from django.shortcuts import render, redirect, reverse\nimport json\nfrom .models import *\nfrom django.http import HttpResponse, JsonResponse\nimport time\nfrom .methods import *\n# Create your views here.\n\ndef login(request):\n if request.method == \"POST\":\n sendMsg = {}\n recvMsg = request.body.decode()\n userData = json.loads(recvMsg)\n u = User.objects.filter(account=userData['account'])\n if u.exists():\n if userData['password'] == u[0].password:\n request.session['id'] = u[0].account\n request.session['name'] = u[0].petname\n request.session.set_expiry(0)\n sendMsg['state'] = \"success\"\n sendMsg['reason'] = \"success\"\n return JsonResponse(sendMsg)\n sendMsg['state'] = \"failed\"\n sendMsg['reason'] = \"login faile,account or password error !!!\"\n return JsonResponse(sendMsg)\n return render(request, 'blog/login.html')\n\ndef regist(request):\n if request.method == \"POST\":\n sendMsg = {}\n recvMsg = request.body.decode()\n userData = json.loads(recvMsg)\n account = userData['account']\n qAcc = User.objects.filter(account=account)\n if qAcc.exists():\n sendMsg['state'] = \"failed\"\n sendMsg['reason'] = \"account repeat\"\n return JsonResponse(sendMsg)\n password = userData['password']\n petname = userData['petname']\n email = userData['email']\n qEmail = User.objects.filter(email=email)\n if qEmail.exists():\n sendMsg['state'] = \"failed\"\n sendMsg['reason'] = \"email repeat\"\n return JsonResponse(sendMsg)\n phone = userData['phone']\n qPhone = User.objects.filter(phone=phone)\n if qPhone.exists():\n sendMsg['state'] = \"failed\"\n sendMsg['reason'] = \"phone repeat\"\n return JsonResponse(sendMsg)\n user = User(account=account, password=password, petname=petname, email=email, phone=phone, isDelete=False)\n user.save()\n request.session['id'] = account\n request.session['name'] = petname\n request.session.set_expiry(0)\n sendMsg['state'] = \"success\"\n sendMsg['reason'] = \"success\"\n return JsonResponse(sendMsg)\n return render(request, 'blog/regist.html')\n\ndef index(request):\n nums = get_typenums()\n typelist = get_typelist()\n bloglist = get_bloglist()\n return render(request, 'blog/index.html', {'typelist': typelist, 'bloglist': bloglist, 'nums': nums})\n\ndef logout(request):\n request.session.clear()\n request.session.delete('session_key')\n return redirect(reverse('blog:login'))\n\ndef writeBlog(request):\n id = request.session.get('id', None)\n if id == None:\n return redirect(reverse('blog:login'))\n if request.method == \"POST\":\n sendMsg = {}\n recvMsg = request.body.decode()\n data = json.loads(recvMsg)\n bid = str(int(time.time()))+'id'+request.session['id']#以用户名和时间戳形成的字符串设为id\n title = data['title']\n btype = data['btype']\n context = data['context']\n author = User.objects.get(account=request.session.get('id', None))\n blog = Blog(bid=bid, title=title, btype=btype, context=context, author=author, isDelete=False)\n blog.save()\n sendMsg['state'] = \"success\"\n sendMsg['reason'] = \"success\"\n return JsonResponse(sendMsg)\n return render(request, 'blog/write.html')\n\n\ndef readBlog(request):\n bid = request.GET.get('id')\n blog = Blog.objects.get(bid=bid)\n typelist = get_typelist()\n bloglist = get_bloglist()\n nums = get_typenums()\n author = blog.author.petname\n return render(request, 'blog/read.html', {'blog': blog, 'typelist': typelist, 'author': author, 'bloglist': bloglist, 'nums': nums})\n\ndef collect(request):\n uid = request.session.get('id', None)\n if uid == None:\n sendMsg = {'state': 'unlogin', 'reason': \"请先登录博客再添加收藏!!!\"}\n return JsonResponse(sendMsg)\n if request.method == \"POST\":\n sendMsg = {}\n recvMsg = request.body.decode()\n data = json.loads(recvMsg)\n bid = data['bid']\n c = Collect.objects.get_or_create(uid=uid, bid=bid, isDelete=False)\n if c[1]:\n sendMsg['state'] = \"success\"\n sendMsg['reason'] = \"success\"\n else:\n sendMsg['state'] = \"failed\"\n sendMsg['reason'] = \"此条博客已被收藏,不能重复收藏\"\n print(sendMsg)\n return JsonResponse(sendMsg)\n return render(request, 'blog/read.html')\n\ndef person(request):\n uid = request.session.get('id', None)\n if uid == None:\n return redirect(reverse('blog:login'))\n user = User.objects.get(account=uid)\n bloglist = get_person_bloglist(num=30,author=user)\n bnum = Blog.objects.filter(isDelete=False).filter(author=user).count()\n cnum = Collect.objects.filter(isDelete=False).filter(uid=uid).count()\n cblogs = get_collect_blog(uid=uid)\n if request.method == \"POST\":\n recvMsg = request.body.decode()\n data = json.loads(recvMsg)\n sendMsg = {}\n if data['itype'] == \"info\":\n user = User.objects.filter(isDelete=False).get(account=uid)\n user.petname = data['petname']\n user.phone = data['phone']\n user.email = data['email']\n user.save()\n sendMsg['state'] = \"success\"\n sendMsg['reason'] = \"修改信息成功!!!\"\n return JsonResponse(sendMsg)\n elif data['itype'] == \"pwd\":\n user = User.objects.filter(isDelete=False).get(account=uid)\n if user.password != data['oldpassword']:\n sendMsg['state'] = \"failed\"\n sendMsg['reason'] = \"旧密码错误!!!\"\n return JsonResponse(sendMsg)\n user.password = data['newpassword']\n user.save()\n sendMsg['state'] = \"success\"\n sendMsg['reason'] = \"密码修改成功,注销后旧密码失效!!!\"\n return JsonResponse(sendMsg)\n elif data['itype'] == \"rblog\":\n blog = Blog.objects.filter(isDelete=False).get(bid=data['bid'])\n sendMsg['state'] = \"success\"\n sendMsg['reason'] = blog.context\n return JsonResponse(sendMsg)\n elif data['itype'] == \"cblog\":\n blog = Blog.objects.filter(isDelete=False).get(bid=data['bid'])\n blog.title = data['title']\n blog.btype = data['btype']\n blog.context = data['context']\n blog.save()\n sendMsg['state'] = \"success\"\n sendMsg['reason'] = \"博客修改成功!!!\"\n return JsonResponse(sendMsg)\n elif data['itype'] == \"delblog\":\n blog = Blog.objects.filter(isDelete=False).get(bid=data['bid'])\n blog.isDelete = True\n blog.save()\n col = Collect.objects.filter(isDelete=False).get(bid=data['bid'])\n col.isDelete = True\n col.save()\n sendMsg['state'] = \"success\"\n sendMsg['reason'] = \"博客删除成功!!!\"\n return JsonResponse(sendMsg)\n elif data['itype'] == \"delcblog\":\n col = Collect.objects.filter(isDelete=False).get(bid=data['bid'])\n col.isDelete = True\n col.save()\n sendMsg['state'] = \"success\"\n sendMsg['reason'] = \"此条收藏已删除!!!\"\n return render(request, 'blog/person.html', {'bloglist': bloglist, 'user': user, 'bnum': bnum, 'cnum': cnum, 'cblogs': cblogs})\n\n\ndef comment(request):\n comments = Comment.objects.filter(isDelete=False).order_by('-cid')#倒序\n talk = \"人生苦短,我学Python !\"\n uid = request.session.get('id', None)\n if request.method == \"POST\":\n if uid == None:\n sendMsg = {'state':\"failed\", 'reason':\"发表评论前,请先登录!!!\"}\n return JsonResponse(sendMsg)\n recvMsg = request.body.decode()\n data = json.loads(recvMsg)\n user = User.objects.get(account=uid)\n com = Comment(fUser=user, content=data['comment'], isDelete=False)\n com.save()\n sendMsg = {'state': \"success\", 'reason': \"评论已发表!!!\"}\n return JsonResponse(sendMsg)\n return render(request, 'blog/comment.html', {'comments': comments, \"talk\": talk})\n\ndef about(request):\n if request.method == \"POST\":\n recvMsg = request.body.decode()\n data = json.loads(recvMsg)\n info = RecvMsg(name=data['name'], email=data['email'], msg=data['msg'])\n info.save()\n sendMsg = {'state': \"success\", 'reason': \"你的发送信息已被接收!!!\"}\n return JsonResponse(sendMsg)\n return render(request, 'blog/about.html')\n\n\n\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"135744594","text":"my_data=[1,1,1,4,2,44,6,8,6,8]\nprint(my_data)\nunique_data = set(my_data)\nprint(unique_data)\nfor element in unique_data:\n print(element)\n\nt_data=(1,4,5,3,77)\nfor element in t_data:\n print(element)\n\nstr_data=\"Hello World\"\nfor element in str_data:\n print(element)\n\ndic_data = {\"name\": \"bambi\",\n \"age\":7,\n \"hobby\":\"sleep\"}\nfor element in dic_data:\n print(element)\n\nfor key in dic_data:\n print(key+' '+str(dic_data[key]))\n\n","sub_path":"01_Jump_to_Python/Chap03/131_2.py","file_name":"131_2.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"175035986","text":"import tensorflow as tf\nimport argparse\nfrom srgan.models.generator import Generator\nfrom srgan.models.srresnet import Generator_MSE_Model\nfrom srgan.data.data_generator import train_data_generator\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('-epoch',\n '--srresnet_epochs',\n type=int,\n metavar='',\n default = 20000)\n\n parser.add_argument('-b',\n '--batch_size',\n type=int,\n metavar='',\n default = 16)\n\n parser.add_argument('-img_dir',\n '--train_path',\n type=str,\n metavar='',\n default = '/content/DIV2K_train_HR/*.png')\n\n parser.add_argument('-w',\n '--weights_path',\n type=str,\n metavar='',\n default = '/content/srresnet_weights/')\n\n parser.add_argument('-lr',\n '--generator_learning_rate',\n type=int,\n metavar='',\n default = 0.0001)\n\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = parse_args()\n train_dataset = train_data_generator(args.train_path,\n args.batch_size)\n generator_mse_model = Generator_MSE_Model(generator_model=Generator())\n generator_mse_model.generator_model.build((1, None, None, 3))\n callbacks = [tf.keras.callbacks.ModelCheckpoint(args.weights_path,\n monitor='mse_loss',\n save_best_only=False,\n save_weights_only=True,\n mode='auto')]\n\n generator_mse_model = Generator_MSE_Model(generator_model=Generator())\n generator_mse_model.generator_model.build((1, None, None, 3))\n generator_mse_model.compile(generator_optimizer=tf.keras.optimizers.Adam(args.generator_learning_rate),\n generator_loss=tf.keras.losses.MeanSquaredError())\n generator_mse_model.fit(train_dataset,\n epochs=args.srresnet_epochs,\n callbacks=callbacks)\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"model_srresnet.py","file_name":"model_srresnet.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"198441813","text":"from tensorflow.keras import layers\nfrom tensorflow.keras import initializers\n\nfrom .activations import gelu\n\nfrom .util import LayerStore\n\n\nclass FeedForward(layers.Layer, LayerStore):\n\n def __init__(\n self,\n hidden_size=1024,\n intermediate_hidden_size=4096,\n dropout=0.0,\n init_stddev=0.02,\n shared_intermediate=False,\n shared_output=False,\n **kwargs\n ):\n super(FeedForward, self).__init__(**kwargs)\n self.hidden_size = hidden_size\n self.intermediate_hidden_size = intermediate_hidden_size\n self.dropout = dropout\n self.init_stddev = init_stddev\n self.shared_intermediate = shared_intermediate\n\n self.intermediate_dense = self.get_layer(\n shared_intermediate,\n 'ff_intermediate_dense',\n layers.Dense,\n intermediate_hidden_size,\n kernel_initializer=initializers.TruncatedNormal(stddev=init_stddev),\n activation=gelu,\n )\n self.output_dense = self.get_layer(\n shared_output,\n 'ff_output_dense',\n layers.Dense,\n hidden_size,\n kernel_initializer=initializers.TruncatedNormal(stddev=init_stddev),\n )\n\n def call(self, inputs):\n x = self.intermediate_dense(inputs)\n x = self.output_dense(x)\n x = layers.Dropout(self.dropout)(x)\n return x\n","sub_path":"model/feed_forward.py","file_name":"feed_forward.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"553896331","text":"# --------------------------------------------------------------------------\n# Mbed Cloud Python SDK\n# (C) COPYRIGHT 2017 Arm Limited\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# --------------------------------------------------------------------------\n\"\"\"A Channels API module\"\"\"\nimport logging\n\nfrom mbed_cloud.subscribe.channels.channel import _API_CHANNELS\nfrom mbed_cloud.subscribe.channels.channel import ChannelSubscription\nfrom mbed_cloud.subscribe.subscribe import expand_dict_as_keys\n\nfrom mbed_cloud import utils\n\n\nclass ResourceValueCurrent(ChannelSubscription):\n \"\"\"Triggers on response to a request for a current resource value\"\"\"\n\n def __init__(self, device_id, resource_path, **extra_filters):\n \"\"\"Channel\"\"\"\n self.device_id = device_id\n self.resource_path = resource_path\n\n # each request is unique\n self.async_id = utils.new_async_id()\n logging.debug('new async id: %s', self.async_id)\n\n self._route_keys = expand_dict_as_keys(dict(\n id=self.async_id,\n channel=_API_CHANNELS.async_responses,\n ))\n self._optional_filters = {}\n self._optional_filters.update(extra_filters)\n self._optional_filter_keys = expand_dict_as_keys(self._optional_filters)\n\n def start(self):\n \"\"\"Start the channel\"\"\"\n # observers for this channel only need to wait for one value\n self._observer_params.update(dict(once=True))\n super(ResourceValueCurrent, self).start()\n self._api.ensure_notifications_thread()\n self._api._mds_rpc_post(\n device_id=self.device_id,\n method='GET',\n uri=self.resource_path,\n async_id=self.async_id,\n _wrap_with_consumer=False,\n )\n\n def notify(self, data):\n \"\"\"Notify this channel of inbound data\"\"\"\n super(ResourceValueCurrent, self).notify(data)\n # after one response, close the channel\n self.ensure_stopped()\n","sub_path":"src/mbed_cloud/subscribe/channels/resource_value_current.py","file_name":"resource_value_current.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"373706810","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCode by: Palash Patole\nMoMpy Project: Modules\nDate of creation: Fri Nov 8 20:50:04 2019\n\nversion: Base\n\nCulmination of:\n 1. Ver2 of Basics-I_ver1.py - \n functions for Converting from/to Cartesian coordinates to /from Kepler elements\n Added on: Nov 8\n\"\"\"\n\nimport math # to use value of Pi\nimport numpy as np #NumPy library\n\ndef convertCartesianToKepler(S_bar,mu,isOutputInDegree = False,isPrint=False):\n \"\"\"Converts cartesian coordinates into equivalent Kepler elements.\"\"\"\n\n r2d = 180/math.pi #bconversion factor for radians to degrees\n ####################################################\n ######### Cartesian to Kepler Conversion ###########\n ####################################################\n ## 1. Computation of required Vectors and their norms\n r_bar = S_bar[:3] # position vector [m]\n V_bar = S_bar[3:6] # velocity vector [m/s]\n \n h_bar = np.cross(r_bar,V_bar) # angular momentum vector\n h = np.linalg.norm(h_bar) # magnitude of angular momentum vector\n r = np.linalg.norm(r_bar) # magnitude of position vector [m]\n V = np.linalg.norm(V_bar) # magnitude of velocity vector [m/s]\n\n N_bar = np.cross(np.array([0,0,1]),h_bar) # N vector\n Nxy = np.linalg.norm(N_bar) # squareroot of N_bar(1,1)^2 + N_bar(2,1)^2;\n e_bar = np.cross(V_bar,h_bar)/mu - r_bar/r # eccentricity vector\n\n\n ## 2. Computation of orbital elements\n a = 1/(2/r - V**2/mu) # Semi-major axis [m]\n e = np.linalg.norm(e_bar) # Eccentricity\n i = math.acos(h_bar[2]/h) # Inclination [radian]\n RAAN = math.atan2(N_bar[1]/Nxy,N_bar[0]/Nxy) # RAAN [radian]\n\n ## 3. Settting up the sign for argument of peri-center\n if np.dot(np.cross(N_bar,e_bar),h_bar) > 0:\n sign1 = 1\n else:\n sign1 = -1\n \n ## 4. Setting up the sign for true anomaly \n if np.dot(np.cross(e_bar,r_bar),h_bar) > 0:\n sign2 = 1\n else:\n sign2 = -1\n \n ## 5. Computation of orbital elements - continued\n omega = sign1 * math.acos(np.dot((e_bar/e),(N_bar/Nxy))) # Argument of periapsis [radian] \n theta = sign2 * math.acos(np.dot((r_bar/r),(e_bar/e))) # True anomaly [radian]\n\n\n ## 6. Computation of mean and eccentric anomalies\n E = 0\n M = 0\n if e > 0 and e < 1:\n E = 2 * math.atan(math.tan(theta/2)*math.sqrt( (1-e) / (1+e) )) # Eccentric anomaly [radian]\n M = E - e * math.sin(E) # Mean anomaly [radian]\n \n ## 7. Correcting for negative values of angles if any \n if RAAN < 0:\n RAAN = RAAN + 2 * math.pi\n if omega < 0:\n omega = omega + 2 * math.pi\n if theta < 0: \n theta = theta+ 2 * math.pi\n if E < 0:\n E = E + 2 * math.pi\n if M < 0:\n M = M + 2 * math.pi\n \n ############### Conversion Complete ################# \n \n ## 8. Saving the results in one array and displaying results, if required \n if isOutputInDegree == True:\n Kepler = np.array([a, e, i*r2d, RAAN*r2d, omega*r2d, theta*r2d, E*r2d, M*r2d])\n if isPrint == True:\n print(\"\\nConversion from cartesian coordinates to Kepler elements is successful.\")\n print (\"Converted Kepler elements are:\") \n print (\"Semi-major axis [m]: a = \",a)\n print (\"Eccentricity: e = \",e)\n print (\"Inclination [deg]: i = \",i*r2d)\n print (\"RAAN [deg]: \\u03A9 = \",RAAN*r2d)\n print (\"Argument of periapsis [deg]: \\u03C9 = \",omega*r2d)\n print (\"True anomaly [deg]: \\u03B8 = \",theta*r2d)\n print (\"Eccentric anomaly [deg]: E = \",E*r2d)\n print (\"Mean anomaly [deg]: M = \",M*r2d)\n else:\n Kepler = np.array([a, e, i, RAAN, omega, theta, E, M])\n if isPrint == True:\n print(\"\\nConversion from cartesian coordinates to Kepler elements is successful.\")\n print (\"Converted Kepler elements are:\") \n print (\"Semi-major axis [m]: a = \\t\",a)\n print (\"Eccentricity: e = \\t\",e)\n print (\"Inclination [rad]: i = \\t\",i)\n print (\"RAAN [rad]: \\u03A9 = \\t\",RAAN)\n print (\"Argument of periapsis [rad]: \\u03C9 = \\t\",omega)\n print (\"True anomaly [rad]: \\u03B8 = \\t\",theta)\n print (\"Eccentric anomaly [rad]: E = \\t\",E)\n print (\"Mean anomaly [rad]: M = \\t\",M)\n \n return Kepler \n\ndef convertKeplerToCartesian(KeplerElements,mu,typeOfAnomaly =1,isInputInDegree = False,isPrint=False):\n \n \"\"\"Converts Kepler elements into equivalent Cartesian coordinates.\"\"\"\n \n r2d = 180/math.pi #bconversion factor for radians to degrees\n ####################################################\n ######### Kepler to Cartesian Conversion ###########\n ####################################################\n ## 1. Setting up Kepler elements\n a = KeplerElements[0] # Semi-major axis[m]\n e = KeplerElements[1] # Eccentricity\n i = KeplerElements[2] # Inclination [radian]\n RAAN = KeplerElements[3] # Right ascention of ascending node [radian]\n omega = KeplerElements[4] # Argument of pericenter [radian]\n \n ## 1. Converting angles from degree to radian, if required\n if isInputInDegree==True:\n i = i/r2d # inclination [radian]\n RAAN = RAAN/r2d # RAAN [radian]\n omega = omega/r2d # Argument of periapsis [radian]\n KeplerElements5_Radian = KeplerElements[5]/r2d # Anomaly[radian] \n else:\n KeplerElements5_Radian = KeplerElements[5] # Anomaly[radian] \n \n ## 2. Deciding the anomaly type passed \n if typeOfAnomaly == 1: # Mean anolmaly is passed\n M = KeplerElements5_Radian # Mean anomaly[radian] \n E = 0\n theta = 0\n elif typeOfAnomaly == 2: # Eccentric anolmaly is passed \n E =KeplerElements5_Radian # Eccentric anomaly[radian] \n theta = 0\n elif typeOfAnomaly == 3: # True anolmaly is passed \n theta = KeplerElements5_Radian # True anomaly[radian] \n else:\n typeOfAnomaly = 1 # Assuming that Mean anomaly was passed\n M = KeplerElements5_Radian # Mean anomaly[radian] \n \n ## 3. Computation of Eccentric and True anomalies, if required \n if typeOfAnomaly == 1: \n E0 = math.pi\n E1 = 2 * math.pi\n while True: \n E1 = E0 + (M-E0+e*math.sin(E0))/(1-e*math.cos(E0))\n if abs(E1 - E0) > 1e-20:\n E0 = E1\n else:\n E = E1\n break\n theta = 2 * math.atan( math.tan(E/2) * math.sqrt((1+e)/(1-e)))\n elif typeOfAnomaly == 2: \n theta = 2 * math.atan( math.tan(E/2) * math.sqrt((1+e)/(1-e)))\n elif typeOfAnomaly == 3: \n E = 2 * math.atan( math.tan(theta/2) * math.sqrt((1-e)/(1+e)))\n \n ## 4. Computation of r\n r = a * (1 - e * math.cos(E))\n \n ## 5. Computation of required variables\n xi = r * math.cos(theta) \n eta = r * math.sin(theta)\n l1 = math.cos(RAAN)*math.cos(omega) - math.sin(RAAN)*math.sin(omega)*math.cos(i)\n l2 = -math.cos(RAAN)*math.sin(omega) - math.sin(RAAN)*math.cos(omega)*math.cos(i)\n m1 = math.sin(RAAN)*math.cos(omega) + math.cos(RAAN)*math.sin(omega)*math.cos(i)\n m2 = -math.sin(RAAN)*math.sin(omega) + math.cos(RAAN)*math.cos(omega)*math.cos(i)\n n1 = math.sin(omega)*math.sin(i)\n n2 = math.cos(omega)* math.sin(i)\n \n ## 6. Computation of position and velocity coordinates\n S = np.array([[l1,l2],[m1,m2],[n1,n2]])\n S2 = np.array([[xi],[eta]]) \n S = np.dot(S,S2)\n \n ## 7. Magnitutde of specific angular momentum vector\n h = math.sqrt(mu*a*(1-e**2))\n \n ## 8. Computation of velocity components\n x_dot = mu * (-l1*math.sin(theta)+l2*(e+math.cos(theta)))/h # x velocity [m/s]\n y_dot = mu * (-m1*math.sin(theta)+m2*(e+math.cos(theta)))/h # y velocity [m/s]\n z_dot = mu * (-n1*math.sin(theta)+n2*(e+math.cos(theta)))/h # z velocity [m/s]\n \n ############### Conversion Complete ################# \n \n ## 9. Saving the results in one array and displaying results, if required \n Cartesian = np.array([S[0][0], S[1][0], S[2][0], x_dot, y_dot, z_dot])\n if isPrint == True:\n print(\"\\nConversion from Kepler elements to Cartesian coordinates is successful.\")\n print (\"Converted Cartesian coordinates are:\") \n print (\"X-position [m]: x = \\t\",S[0][0])\n print (\"Y-position [m]: y = \\t\",S[1][0])\n print (\"Z-position [m]: z = \\t\",S[2][0]) \n print (\"X-velocity [m/s]: x_dot = \\t\", x_dot)\n print (\"Y-velocity [m/s]: y_dot = \\t\", y_dot)\n print (\"Z-velocity [m/s]: z_dot = \\t\", z_dot) \n \n return Cartesian","sub_path":"Modules/BasicAstrodynamics.py","file_name":"BasicAstrodynamics.py","file_ext":"py","file_size_in_byte":8636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"49791539","text":"from collab import models\nfrom collab.utils import handle_email\nimport datetime\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n help = \"\"\" Cette fonction permet d'envoyer un mail aux utilisateurs qui sont\n abonnés aux notifications sur un signalement \"\"\"\n\n def handle(self, *args, **options):\n for user in models.CustomUser.objects.all():\n res_events = {}\n # get users Subscription\n for subscription in user.subscription_set.all():\n date = datetime.datetime.now().date()\n # get features events\n events = models.Event.objects.filter(feature_id=subscription.feature_id,\n creation_date__contains=date)\n res_events[str(subscription.feature_id)] = { \"project\": subscription.project_slug,\n \"identifiant\": str(subscription.feature_id),\n \"url\": \"\"\"{domain}projet/{project_slug}/{feature_type}/{feature_id}\"\"\".format(\n domain=settings.BASE_URL,\n project_slug=subscription.project_slug,\n feature_type=subscription.feature_type_slug,\n feature_id=str(subscription.feature_id))}\n # create template\n list_event = []\n for event in events:\n list_event.append({\n \"object_type\": event.get_object_type_display(),\n \"event_type\": event.get_event_type_display(),\n \"creation_date\": event.creation_date.strftime('%d-%m-%Y %H:%M:%S')})\n res_events[str(subscription.feature_id)].update({'events':list_event})\n # send email to user\n if res_events:\n context = {'first_name': user.first_name,\n 'last_name': user.last_name,\n 'username': user.username,\n 'res': res_events}\n handle_email(user, context)\n self.stdout.write(self.style.SUCCESS('FIN DE L ENVOI DE MAIL.'))\n","sub_path":"collab/management/commands/notify.py","file_name":"notify.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"342338369","text":"#!/usr/bin/env python\nimport unittest\nimport os\n\nimport botocore\n\nfrom mock import patch, mock\n\n# Class under test\nimport batch_autoscaling # pylint: disable=import-error\n\nFAKE_LIST_JOBS_RESPONSE = {'jobSummaryList': [{'status': 'RUNNING', 'jobName': 'job-name-1', 'createdAt': 1561155711844, 'jobId': '11111111-abcd-ffff-1111-abcdabcd0001'},\n {'status': 'RUNNING', 'jobName': 'job-name-2', 'createdAt': 1561155811844, 'jobId': '11111111-abcd-ffff-1111-abcdabcd0002'}]}\n\nFAKE_LIST_JOBS_RESPONSE_EMPTY = {'jobSummaryList': []}\n\nFAKE_QUEUE_NAME = 'fake-job-queue'\nFAKE_COMPUTE_ENVIRONMENT_NAME = 'fake-compute-environment'\nFAKE_REGION = 'us-east-1'\nFAKE_ACCOUNT = '123456789012'\n\nFAKE_COMPUTE_ENVIRONMENT_ARN = \"arn:aws:batch:{region}:{account}:compute-environment/{compute_env}\".format(region=FAKE_REGION, account=FAKE_ACCOUNT, compute_env=FAKE_COMPUTE_ENVIRONMENT_NAME)\nFAKE_ECS_CLUSTER_ARN = \"arn:aws:batch:{region}:{account}:cluster/{compute_env}_Batch_fake-guid\".format(region=FAKE_REGION, account=FAKE_ACCOUNT, compute_env=FAKE_COMPUTE_ENVIRONMENT_NAME)\n\nFAKE_DESCRIBE_JOB_QUEUES_RESPONSE = {\"jobQueues\": [{\"status\": \"VALID\",\n \"jobQueueArn\": \"arn:aws:batch:{region}:{account}:job-queue/{queue}\".format(region=FAKE_REGION, account=FAKE_ACCOUNT, queue=FAKE_QUEUE_NAME),\n \"computeEnvironmentOrder\": [\n {\"computeEnvironment\": FAKE_COMPUTE_ENVIRONMENT_ARN}\n ],\n \"jobQueueName\": FAKE_QUEUE_NAME}]}\n\nFAKE_CANNOT_UPDATE_EXCEPTION = botocore.exceptions.ClientError({'Error': {'Code': 'ClientException', 'Message': 'Cannot update, compute environment ... is being modified.'}}, 'UpdateComputeEnvironment')\n\nFAKE_BATCH_CONFIGURATIONS = [{'queue_name': FAKE_QUEUE_NAME, 'vcpus': 12, 'region': FAKE_REGION}]\n\nFAKE_DESCRIBE_COMPUTE_ENVIRONMENTS = {\"computeEnvironments\": [{\"computeEnvironmentName\": FAKE_COMPUTE_ENVIRONMENT_NAME,\n \"computeEnvironmentArn\": FAKE_COMPUTE_ENVIRONMENT_ARN,\n \"ecsClusterArn\": FAKE_ECS_CLUSTER_ARN,\n \"computeResources\": {\"desiredvCpus\": 4, \"maxvCpus\": 40, \"minvCpus\": 0,\n \"tags\": {}}}]}\n\nFAKE_DESCRIBE_CLUSTERS_SCALING_TAG_SET = {\"clusters\": [{\"status\": \"ACTIVE\",\n \"tags\": [{\"value\": \"1\", \"key\": \"IDSeqEnvsThatCanScale\"}],\n \"clusterArn\": FAKE_ECS_CLUSTER_ARN}]}\n\nFAKE_DESCRIBE_CLUSTERS_NO_SCALING_TAG = {\"clusters\": [{\"status\": \"ACTIVE\",\n \"tags\": [],\n \"clusterArn\": FAKE_ECS_CLUSTER_ARN}]}\n\nclass TestAutoscaling(unittest.TestCase):\n '''Tests for /app/jobs/autoscaling.py'''\n\n def test_calc_auto_scaling_recommendation_1(self):\n '''WHEN new capacity is same as current capacity THEN do not recommend a change'''\n result = batch_autoscaling.calc_auto_scaling_recommendation(pending_jobs_counts={'RUNNABLE': 1, 'STARTING': 1, 'RUNNING': 1},\n current_vcpu_min=36,\n current_vcpu_max=40, job_vcpus=12, scaling_permission=True)\n\n self.assertEqual(result, {'change': False, 'new_vcpu_min': 36})\n\n\n def test_calc_auto_scaling_recommendation_2(self):\n '''WHEN new capacity is higher than current capacity THEN recommend a change to the higher capacity'''\n result = batch_autoscaling.calc_auto_scaling_recommendation(pending_jobs_counts={'RUNNABLE': 2},\n current_vcpu_min=10,\n current_vcpu_max=40, job_vcpus=12, scaling_permission=True)\n\n self.assertEqual(result, {'change': True, 'new_vcpu_min': 24})\n\n\n def test_calc_auto_scaling_recommendation_3(self):\n '''WHEN new capacity is lower than current capacity THEN recommend a change to the lower capacity'''\n result = batch_autoscaling.calc_auto_scaling_recommendation(pending_jobs_counts={'RUNNABLE': 1},\n current_vcpu_min=30,\n current_vcpu_max=40, job_vcpus=12, scaling_permission=True)\n\n self.assertEqual(result, {'change': True, 'new_vcpu_min': 12})\n\n\n def test_calc_auto_scaling_recommendation_4(self):\n '''WHEN total pending jobs exceed max capacity AND capacity is lower THEN recommend a change to capped to the maximum capacity'''\n result = batch_autoscaling.calc_auto_scaling_recommendation(pending_jobs_counts={'RUNNABLE': 3, 'STARTING': 4, 'RUNNING': 12},\n current_vcpu_min=12,\n current_vcpu_max=40, job_vcpus=12, scaling_permission=True)\n\n self.assertEqual(result, {'change': True, 'new_vcpu_min': 40})\n\n\n def test_calc_auto_scaling_recommendation_5(self):\n '''WHEN scaling permission is not set THEN do not recommend a change'''\n result = batch_autoscaling.calc_auto_scaling_recommendation(pending_jobs_counts={'RUNNABLE': 3, 'STARTING': 4, 'RUNNING': 12},\n current_vcpu_min=12,\n current_vcpu_max=40, job_vcpus=12, scaling_permission=False)\n\n self.assertEqual(result, {'change': False, 'new_vcpu_min': 40})\n\n\n def _parameterized_test_process_batch_configuration(self, batch_describe_compute_environments_return_value,\n ecs_describe_clusters_return_value, should_have_scaling_permission, should_change):\n with patch('batch_autoscaling.boto3.client') as _mock_boto3:\n _mock_boto3.return_value.list_jobs.side_effect = [FAKE_LIST_JOBS_RESPONSE, FAKE_LIST_JOBS_RESPONSE_EMPTY, FAKE_LIST_JOBS_RESPONSE_EMPTY]\n _mock_boto3.return_value.describe_job_queues.return_value = FAKE_DESCRIBE_JOB_QUEUES_RESPONSE\n _mock_boto3.return_value.describe_compute_environments.return_value = batch_describe_compute_environments_return_value\n _mock_boto3.return_value.describe_clusters.return_value = ecs_describe_clusters_return_value\n\n result = batch_autoscaling.process_batch_configuration(FAKE_BATCH_CONFIGURATIONS[0])\n\n if should_have_scaling_permission:\n _mock_boto3.return_value.update_compute_environment.assert_called_once_with(computeEnvironment=FAKE_COMPUTE_ENVIRONMENT_NAME, computeResources={'minvCpus': 24})\n else:\n _mock_boto3.return_value.update_compute_environment.assert_not_called()\n self.assertEqual(result, {'autoscaling_recommendation': {'change': should_change, 'new_vcpu_min': 24},\n 'current_configuration': {'maxvCpus': 40, 'minvCpus': 0, 'desiredvCpus': 4, 'scaling_permission': should_have_scaling_permission},\n 'compute_environment_name': FAKE_COMPUTE_ENVIRONMENT_NAME,\n 'pending_jobs_counts': {'RUNNING': 2, 'STARTING': 0, 'RUNNABLE': 0}})\n\n\n def test_process_batch_configuration_1(self):\n '''WHEN processing batch configuration with scaling tag set THEN invoke dependencies and change the environment'''\n self._parameterized_test_process_batch_configuration(batch_describe_compute_environments_return_value=FAKE_DESCRIBE_COMPUTE_ENVIRONMENTS,\n ecs_describe_clusters_return_value=FAKE_DESCRIBE_CLUSTERS_SCALING_TAG_SET,\n should_have_scaling_permission=True, should_change=True)\n\n def test_process_batch_configuration_3(self):\n '''WHEN processing batch configuration with scaling tag not set THEN do not change the environment'''\n self._parameterized_test_process_batch_configuration(batch_describe_compute_environments_return_value=FAKE_DESCRIBE_COMPUTE_ENVIRONMENTS,\n ecs_describe_clusters_return_value=FAKE_DESCRIBE_CLUSTERS_NO_SCALING_TAG,\n should_have_scaling_permission=False, should_change=False)\n\n @patch('batch_autoscaling.boto3.client', side_effect=FAKE_CANNOT_UPDATE_EXCEPTION)\n def test_autoscale_compute_environments(self, _):\n '''WHEN any error happens during autoscale for an specific environment THEN return the error message and don't break'''\n result = batch_autoscaling.autoscale_compute_environments(FAKE_BATCH_CONFIGURATIONS)\n\n self.assertEqual(result[0]['error_type'], \"\")\n self.assertRegexpMatches(result[0]['error_args'][0], 'Cannot update')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/jobs/test_batch_autoscaling.py","file_name":"test_batch_autoscaling.py","file_ext":"py","file_size_in_byte":9516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"4823323","text":"def anagramSolution5(s1, s2):\n # check if they are equal in length\n if len(s1) != len(s2):\n return False\n c1 = {}\n c2 = {}\n for w1 in s1:\n if not c1.get(w1):\n c1[w1] = 0\n else:\n c1[w1] = c1[w1] +1\n for w2 in s2:\n if not c2.get(w2):\n c2[w2] = 0\n else:\n c2[w2] = c2[w2] +1\n for k,v in c1.items():\n if c1.get(k) != c2.get(k):\n return False\n \n return True\n\nprint(anagramSolution5('earth', 'heart'))\n\n","sub_path":"anagramSolution5.py","file_name":"anagramSolution5.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"271741605","text":"\"\"\"\nTest the data module.\n\"\"\"\n\nimport pytest\nimport numpy as np\nfrom sklearn.datasets import make_regression\nfrom sklearn.linear_model import LinearRegression\nfrom imblearn.pipeline import Pipeline\n\nfrom ...preprocessing import FeatureSelector, RowSelector\n\nX, y = make_regression(n_features=10)\n\n\n@pytest.mark.parametrize('indices', [\n ([0,1,2]),\n ([5]),\n (np.arange(0, 10))\n])\ndef test_feature_selector(indices):\n \"\"\"Test the feature selector.\"\"\"\n selector = FeatureSelector(indices=indices)\n X_t = selector.fit_transform(X, y)\n assert X_t.shape[0] == X.shape[0]\n assert X_t.shape[1] == len(indices)\n assert np.array_equal(X_t, X[:, indices])\n\n\ndef test_default_feature_selector():\n \"\"\"Test the default feature selector.\"\"\"\n selector = FeatureSelector()\n X_t = selector.fit_transform(X, y)\n assert np.array_equal(X_t, X)\n\n\ndef test_feature_selector_pipeline_integration():\n \"\"\"Test the integration of feature selector\n and pipelines.\"\"\"\n pipeline = Pipeline([('selector', FeatureSelector(indices=[0, 2])), ('lr', LinearRegression())])\n pipeline.fit(X, y)\n\n\ndef test_feature_selector_set_parameters():\n \"\"\"Test the feature selector set of\n parameters method.\"\"\"\n indices, updated_indices = [0, 3, 4], None\n\n selector = FeatureSelector(indices)\n X_t = selector.fit_transform(X, y)\n assert X_t.shape[1] == len(indices)\n\n selector.set_params(indices=updated_indices)\n X_t = selector.fit_transform(X, y)\n assert np.array_equal(X_t, X)\n\n\n@pytest.mark.parametrize('sampling_strategy,selection_strategy', [\n (0.9, None),\n (0.4, 5),\n (0.1, np.random.RandomState(2))\n])\ndef test_row_selector_strategy(sampling_strategy, selection_strategy):\n \"\"\"Test the selection strategy of row selector.\"\"\"\n selector = RowSelector(sampling_strategy, selection_strategy)\n X_t, y_t = selector.fit_resample(X, y)\n n_samples = int(sampling_strategy * len(X))\n assert X_t.shape == (n_samples, X.shape[1])\n assert y_t.shape == (n_samples,)\n\n\n@pytest.mark.parametrize('sampling_strategy', [\n 0.9, 0.4, 0.1, 1.0\n])\ndef test_row_selector_head(sampling_strategy):\n \"\"\"Test the head strategy of row selector.\"\"\"\n selector = RowSelector(sampling_strategy, selection_strategy='head')\n X_t, y_t = selector.fit_resample(X, y)\n n_samples = int(sampling_strategy * len(X))\n assert np.array_equal(X_t, X[:n_samples])\n assert np.array_equal(y_t, y[:n_samples])\n\n\n@pytest.mark.parametrize('sampling_strategy', [\n 0.2, 0.7, 0.5, 1.0\n])\ndef test_row_selector_tail(sampling_strategy):\n \"\"\"Test the tail strategy of row selector.\"\"\"\n selector = RowSelector(sampling_strategy, selection_strategy='tail')\n X_t, y_t = selector.fit_resample(X, y)\n n_samples = int(sampling_strategy * len(X))\n assert np.array_equal(X_t, X[-n_samples:])\n assert np.array_equal(y_t, y[-n_samples:])\n\n\ndef test_default_row_selector():\n \"\"\"Test the default row selector.\"\"\"\n selector = RowSelector()\n X_t, y_t = selector.fit_resample(X, y)\n assert np.array_equal(X_t, X)\n assert np.array_equal(y_t, y)\n\n\ndef test_row_selector_pipeline_integration():\n \"\"\"Test the integration of row selector\n and pipelines.\"\"\"\n pipeline = Pipeline(\n [\n ('selector', RowSelector(sampling_strategy=0.8, selection_strategy=0)),\n ('lr', LinearRegression())\n ]\n )\n pipeline.fit(X, y)\n","sub_path":"sklearnext/preprocessing/tests/test_data.py","file_name":"test_data.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"563523324","text":"import time\nfrom gpiozero import DistanceSensor\n\npinTrig = 23\npinEcho = 24\n\nsensor=DistanceSensor(echo=pinEcho, trigger=pinTrig, max_distance=5, threshold_distance=0.2)\n\nprint(\"Ultrasonic Measurement\")\n\ntry:\n while True:\n distance=sensor.distance*100\n print(\"Distance: %.1f cm\" % distance, '')\n time.sleep(0.5)\n\n# If you press CTRL+C, cleanup and stop\nexcept KeyboardInterrupt:\n print(\"Exiting\")\n","sub_path":"test/sonar-GPIOZero-test1.py","file_name":"sonar-GPIOZero-test1.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"517698225","text":"import unittest\nimport numpy as np\n\nfrom bokeh.properties import (\n HasProps, Int, Array, String, Enum, Float, DataSpec, ColorSpec, DashPattern\n)\n\nclass Basictest(unittest.TestCase):\n\n def test_simple_class(self):\n class Foo(HasProps):\n x = Int(12)\n y = String(\"hello\")\n z = Array([1,2,3])\n s = String(None)\n\n f = Foo()\n self.assertEqual(f.x, 12)\n self.assertEqual(f.y, \"hello\")\n self.assert_(np.array_equal(np.array([1,2,3]), f.z))\n self.assertEqual(f.s, None)\n\n f.x = 18\n self.assertEqual(f.x, 18)\n\n f.y = \"bar\"\n self.assertEqual(f.y, \"bar\")\n\n def test_enum(self):\n class Foo(HasProps):\n x = Enum(\"blue\", \"red\", \"green\")\n y = Enum(\"small\", \"medium\", \"large\", default=\"tiny\")\n\n f = Foo()\n self.assertEqual(f.x, \"blue\")\n self.assertEqual(f.y, \"tiny\")\n f.x = \"red\"\n with self.assertRaises(ValueError):\n f.x = \"yellow\"\n f.y = \"small\"\n with self.assertRaises(ValueError):\n # Even though this is the default, it is not a valid value\n # for the Enum.\n f.y = \"tiny\"\n\n def test_inheritance(self):\n class Base(HasProps):\n x = Int(12)\n y = String(\"hello\")\n\n class Child(Base):\n z = Float(3.14)\n\n c = Child()\n self.assertEqual(frozenset(['x', 'y', 'z']), frozenset(c.properties()))\n self.assertEqual(c.y, \"hello\")\n\n def test_set(self):\n class Foo(HasProps):\n x = Int(12)\n y = Enum(\"red\", \"blue\", \"green\")\n z = String(\"blah\")\n\n f = Foo()\n self.assertEqual(f.x, 12)\n self.assertEqual(f.y, \"red\")\n self.assertEqual(f.z, \"blah\")\n f.set(**dict(x=20, y=\"green\", z=\"hello\"))\n self.assertEqual(f.x, 20)\n self.assertEqual(f.y, \"green\")\n self.assertEqual(f.z, \"hello\")\n with self.assertRaises(ValueError):\n f.set(y=\"orange\")\n\n def test_no_parens(self):\n class Foo(HasProps):\n x = Int\n y = Int()\n f = Foo()\n self.assertEqual(f.x, f.y)\n f.x = 13\n self.assertEqual(f.x, 13)\n\n # def test_kwargs_init(self):\n # class Foo(HasProps):\n # x = String\n # y = Int\n # z = Float\n # f = Foo(x = \"hello\", y = 14)\n # self.assertEqual(f.x, \"hello\")\n # self.assertEqual(f.y, 14)\n\n # with self.assertRaises(TypeError):\n # # This should raise a TypeError: object.__init__() takes no parameters\n # g = Foo(z = 3.14, q = \"blah\")\n\nclass TestDataSpec(unittest.TestCase):\n\n def test_field(self):\n class Foo(HasProps):\n x = DataSpec(\"xfield\")\n f = Foo()\n self.assertEqual(f.x, \"xfield\")\n self.assertDictEqual(Foo.__dict__[\"x\"].to_dict(f), {\"field\": \"xfield\", \"units\": \"data\"})\n f.x = \"my_x\"\n self.assertEqual(f.x, \"my_x\")\n self.assertDictEqual(Foo.__dict__[\"x\"].to_dict(f), {\"field\": \"my_x\", \"units\": \"data\"})\n\n def test_value(self):\n class Foo(HasProps):\n x = DataSpec(\"xfield\")\n f = Foo()\n self.assertEqual(f.x, \"xfield\")\n f.x = 12\n self.assertEqual(f.x, 12)\n self.assertDictEqual(Foo.__dict__[\"x\"].to_dict(f), {\"value\": 12, \"units\": \"data\"})\n f.x = 15\n self.assertEqual(f.x, 15)\n self.assertDictEqual(Foo.__dict__[\"x\"].to_dict(f), {\"value\": 15, \"units\": \"data\"})\n f.x = dict(value=23, units=\"screen\")\n self.assertDictEqual(Foo.__dict__[\"x\"].to_dict(f), {\"value\": 23, \"units\": \"screen\"})\n # Setting defaults when there is a fixed value should do nothing, so verify this.\n # Also, setting a dict clobbers all fields that are not explicitly set, so \"units\"\n # gets reset back to the default value on the DataSpec, which is \"data\".\n f.x = dict(value=32, default=18)\n self.assertDictEqual(Foo.__dict__[\"x\"].to_dict(f), {\"value\": 32, \"units\": \"data\"})\n\n def test_default(self):\n class Foo(HasProps):\n y = DataSpec(\"yfield\", default=12)\n f = Foo()\n self.assertEqual(f.y, {\"field\": \"yfield\", \"default\": 12})\n self.assertDictEqual(Foo.__dict__[\"y\"].to_dict(f), {\"field\": \"yfield\", \"default\": 12, \"units\": \"data\"})\n f.y = \"y1\"\n self.assertEqual(f.y, \"y1\")\n f.y = (\"y2\", 27)\n self.assertDictEqual(f.y, {\"field\": \"y2\", \"default\": 27, \"units\": \"data\"})\n self.assertDictEqual(Foo.__dict__[\"y\"].to_dict(f), {\"field\": \"y2\", \"default\": 27, \"units\": \"data\"})\n # Once we set a concrete value, the default is ignored, because it is unused\n f.y = 32\n self.assertEqual(f.y, 32)\n self.assertDictEqual(Foo.__dict__[\"y\"].to_dict(f), {\"value\": 32, \"units\": \"data\"})\n\n def test_multiple_instances(self):\n class Foo(HasProps):\n x = DataSpec(\"xfield\", default=12)\n\n a = Foo()\n b = Foo()\n a.x = 13\n b.x = 14\n self.assertEqual(a.x, 13)\n self.assertEqual(b.x, 14)\n self.assertDictEqual(Foo.__dict__[\"x\"].to_dict(a), {\"value\": 13, \"units\": \"data\"})\n self.assertDictEqual(Foo.__dict__[\"x\"].to_dict(b), {\"value\": 14, \"units\": \"data\"})\n a.x = (\"x2\", 21)\n self.assertDictEqual(Foo.__dict__[\"x\"].to_dict(a), {\"field\": \"x2\", \"default\": 21, \"units\": \"data\"})\n self.assertDictEqual(Foo.__dict__[\"x\"].to_dict(b), {\"value\": 14, \"units\": \"data\"})\n b.x = {\"field\": \"x3\", \"units\": \"screen\", \"default\": 25}\n self.assertDictEqual(Foo.__dict__[\"x\"].to_dict(a), {\"field\": \"x2\", \"default\": 21, \"units\": \"data\"})\n self.assertDictEqual(Foo.__dict__[\"x\"].to_dict(b), {\"field\": \"x3\", \"units\": \"screen\", \"default\": 25})\n\n\nclass TestColorSpec(unittest.TestCase):\n\n def test_field(self):\n class Foo(HasProps):\n col = ColorSpec(\"colorfield\")\n desc = Foo.__dict__[\"col\"]\n f = Foo()\n self.assertEqual(f.col, \"colorfield\")\n self.assertDictEqual(desc.to_dict(f), {\"field\": \"colorfield\"})\n f.col = \"myfield\"\n self.assertEqual(f.col, \"myfield\")\n self.assertDictEqual(desc.to_dict(f), {\"field\": \"myfield\"})\n\n def test_field_default(self):\n class Foo(HasProps):\n col = ColorSpec(\"colorfield\", default=\"red\")\n desc = Foo.__dict__[\"col\"]\n f = Foo()\n self.assertDictEqual(f.col, {\"field\": \"colorfield\", \"default\": \"red\"})\n self.assertDictEqual(desc.to_dict(f), {\"field\": \"colorfield\", \"default\": \"red\"})\n f.col = \"myfield\"\n self.assertDictEqual(f.col, {\"field\": \"myfield\", \"default\": \"red\"})\n self.assertDictEqual(desc.to_dict(f), {\"field\": \"myfield\", \"default\": \"red\"})\n\n def test_default_tuple(self):\n class Foo(HasProps):\n col = ColorSpec(\"colorfield\", default=(128,255,124))\n desc = Foo.__dict__[\"col\"]\n f = Foo()\n self.assertDictEqual(f.col, {\"field\": \"colorfield\", \"default\": (128, 255, 124)})\n self.assertDictEqual(desc.to_dict(f), {\"field\": \"colorfield\", \"default\": \"rgb(128, 255, 124)\"})\n\n def test_fixed_value(self):\n class Foo(HasProps):\n col = ColorSpec(\"gray\")\n desc = Foo.__dict__[\"col\"]\n f = Foo()\n self.assertEqual(f.col, \"gray\")\n self.assertDictEqual(desc.to_dict(f), {\"value\": \"gray\"})\n\n def test_named_value(self):\n class Foo(HasProps):\n col = ColorSpec(\"colorfield\")\n desc = Foo.__dict__[\"col\"]\n f = Foo()\n\n f.col = \"red\"\n self.assertEqual(f.col, \"red\")\n self.assertDictEqual(desc.to_dict(f), {\"value\": \"red\"})\n f.col = \"forestgreen\"\n self.assertEqual(f.col, \"forestgreen\")\n self.assertDictEqual(desc.to_dict(f), {\"value\": \"forestgreen\"})\n\n def test_named_value_set_none(self):\n class Foo(HasProps):\n col = ColorSpec(\"colorfield\")\n desc = Foo.__dict__[\"col\"]\n f = Foo()\n f.col = None\n self.assertDictEqual(desc.to_dict(f), {\"value\": None})\n\n def test_named_color_overriding_default(self):\n class Foo(HasProps):\n col = ColorSpec(\"colorfield\", default=\"blue\")\n desc = Foo.__dict__[\"col\"]\n f = Foo()\n f.col = \"forestgreen\"\n self.assertEqual(f.col, \"forestgreen\")\n self.assertDictEqual(desc.to_dict(f), {\"value\": \"forestgreen\"})\n f.col = \"myfield\"\n self.assertDictEqual(f.col, {\"field\": \"myfield\", \"default\": \"blue\"})\n self.assertDictEqual(desc.to_dict(f), {\"field\": \"myfield\", \"default\": \"blue\"})\n\n def test_hex_value(self):\n class Foo(HasProps):\n col = ColorSpec(\"colorfield\")\n desc = Foo.__dict__[\"col\"]\n f = Foo()\n f.col = \"#FF004A\"\n self.assertEqual(f.col, \"#FF004A\")\n self.assertDictEqual(desc.to_dict(f), {\"value\": \"#FF004A\"})\n f.col = \"myfield\"\n self.assertEqual(f.col, \"myfield\")\n self.assertDictEqual(desc.to_dict(f), {\"field\": \"myfield\"})\n\n def test_tuple_value(self):\n class Foo(HasProps):\n col = ColorSpec(\"colorfield\")\n desc = Foo.__dict__[\"col\"]\n f = Foo()\n f.col = (128, 200, 255)\n self.assertEqual(f.col, (128, 200, 255))\n self.assertDictEqual(desc.to_dict(f), {\"value\": \"rgb(128, 200, 255)\"})\n f.col = \"myfield\"\n self.assertEqual(f.col, \"myfield\")\n self.assertDictEqual(desc.to_dict(f), {\"field\": \"myfield\"})\n f.col = (100, 150, 200, 0.5)\n self.assertEqual(f.col, (100, 150, 200, 0.5))\n self.assertDictEqual(desc.to_dict(f), {\"value\": \"rgba(100, 150, 200, 0.5)\"})\n\n def test_set_dict(self):\n class Foo(HasProps):\n col = ColorSpec(\"colorfield\")\n desc = Foo.__dict__[\"col\"]\n f = Foo()\n f.col = {\"field\": \"myfield\", \"default\": \"#88FF00\"}\n self.assertDictEqual(f.col, {\"field\": \"myfield\", \"default\": \"#88FF00\"})\n\n f.col = \"field2\"\n self.assertEqual(f.col, \"field2\")\n self.assertDictEqual(desc.to_dict(f), {\"field\": \"field2\"})\n\nclass TestDashPattern(unittest.TestCase):\n\n def test_named(self):\n class Foo(HasProps):\n pat = DashPattern\n f = Foo()\n self.assertEqual(f.pat, [])\n f.pat = \"solid\"\n self.assertEqual(f.pat, [])\n f.pat = \"dashed\"\n self.assertEqual(f.pat, [6])\n f.pat = \"dotted\"\n self.assertEqual(f.pat, [2,4])\n f.pat = \"dotdash\"\n self.assertEqual(f.pat, [2,4,6,4])\n f.pat = \"dashdot\"\n self.assertEqual(f.pat, [6,4,2,4])\n\n def test_string(self):\n class Foo(HasProps):\n pat = DashPattern\n f = Foo()\n f.pat = \"\"\n self.assertEqual(f.pat, [])\n f.pat = \"2\"\n self.assertEqual(f.pat, [2])\n f.pat = \"2 4\"\n self.assertEqual(f.pat, [2, 4])\n f.pat = \"2 4 6\"\n self.assertEqual(f.pat, [2, 4, 6])\n def assign(x, val):\n x.pat = val\n self.assertRaises(ValueError, assign, f , \"abc 6\")\n\n def test_tuple(self):\n class Foo(HasProps):\n pat = DashPattern\n f = Foo()\n f.pat = ()\n self.assertEqual(f.pat, ())\n f.pat = (2,)\n self.assertEqual(f.pat, (2,))\n f.pat = (2,4)\n self.assertEqual(f.pat, (2, 4))\n f.pat = (2,4,6)\n self.assertEqual(f.pat, (2, 4, 6))\n def assign(x, val):\n x.pat = val\n self.assertRaises(ValueError, assign, f , (2, 4.2))\n self.assertRaises(ValueError, assign, f , (2, \"a\"))\n\n def test_list(self):\n class Foo(HasProps):\n pat = DashPattern\n f = Foo()\n f.pat = []\n self.assertEqual(f.pat, [])\n f.pat = [2]\n self.assertEqual(f.pat, [2])\n f.pat = [2,4]\n self.assertEqual(f.pat, [2, 4])\n f.pat = [2,4,6]\n self.assertEqual(f.pat, [2, 4, 6])\n def assign(x, val):\n x.pat = val\n self.assertRaises(ValueError, assign, f , [2, 4.2])\n self.assertRaises(ValueError, assign, f , [2, \"a\"])\n\n def test_invalid(self):\n class Foo(HasProps):\n pat = DashPattern\n f = Foo()\n def assign(x, val):\n x.pat = val\n self.assertRaises(ValueError, assign, f , 10)\n self.assertRaises(ValueError, assign, f , 10.1)\n self.assertRaises(ValueError, assign, f , {})\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"bokeh/tests/test_properties.py","file_name":"test_properties.py","file_ext":"py","file_size_in_byte":12497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"13742914","text":"# Итератор для удаления дубликатов\nclass Unique(object):\n def __init__(self, items, **kwargs):\n self.lst=list(items) # Получаем в список\n self.index = 0 # Счётчик чтобы бегать по списку и в конце завершить цикл\n self.case_ignore = kwargs.get('ignore_case')\n self.buf=[] # Список для контроля уникальных значений\n\n # В качестве ключевого аргумента, конструктор должен принимать bool-параметр ignore_case,\n # в зависимости от значения которого будут считаться одинаковые строки в разном регистре\n # Например: ignore_case = True, Aбв и АБВ разные строки\n # ignore_case = False, Aбв и АБВ одинаковые строки, одна из них удалится\n # По-умолчанию ignore_case = False\n\n def __next__(self):\n while self.index < len(self.lst):\n if self.case_ignore: # Определяемся, будет ли разным регистр\n i = self.lst[self.index].lower()\n else:\n i = self.lst[self.index] # В одну строку никак не работало\n if i not in self.buf: # Проверка на уникальость...\n self.buf.append(i) # ...и добавление в случае успеха\n return i # ...и возврат в случае успеха\n self.index += 1\n raise StopIteration\n\n def __iter__(self):\n return self\n","sub_path":"librip/iterators.py","file_name":"iterators.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"66614784","text":"# Copyright 2011 Thierry Carrez \n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render\nfrom django.conf import settings\nfrom django.contrib.auth import logout\nfrom django.core.mail import EmailMessage\nfrom django.http import HttpResponseRedirect, HttpResponseForbidden\nfrom django.utils.encoding import smart_str\n\nfrom odsreg.cfp.models import Proposal, Topic, Comment\nfrom odsreg.cfp.forms import ProposalForm, ProposalEditForm, CommentForm\nfrom odsreg.cfp.forms import ProposalReviewForm, ProposalSwitchForm\nfrom odsreg.cfp.utils import linkify, is_editable, topiclead\n\n\n@login_required\ndef list(request):\n proposals = Proposal.objects.all()\n reviewable_topics = Topic.objects.filter(\n lead_username=request.user.username)\n request.session['lastlist'] = \"\"\n return render(request, \"cfplist.html\",\n {'proposals': proposals,\n 'reviewable_topics': reviewable_topics})\n\n\n@login_required\ndef topiclist(request, topicid):\n topic = Topic.objects.get(id=topicid)\n if not topiclead(request.user, topic):\n return HttpResponseForbidden(\"Forbidden\")\n proposals = Proposal.objects.filter(topic=topicid)\n request.session['lastlist'] = \"cfp/topic/%s\" % topicid\n return render(request, \"topiclist.html\",\n {'proposals': proposals,\n 'topic': topic})\n\n\n@login_required\ndef topicstatus(request):\n topics = Topic.objects.all()\n return render(request, \"topicstatus.html\", {'topics': topics})\n\n\n@login_required\ndef create(request):\n if request.method == 'POST':\n form = ProposalForm(request.POST)\n if form.is_valid():\n proposal = form.save(commit=False)\n proposal.proposer = request.user\n proposal.status = 'U'\n proposal.save()\n return list(request)\n else:\n form = ProposalForm()\n\n topics = Topic.objects.all()\n return render(request, 'cfpcreate.html', {'topics': topics, 'form': form})\n\n\n@login_required\ndef details(request, proposalid):\n proposal = Proposal.objects.get(id=proposalid)\n if request.method == 'POST':\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.proposal = proposal\n comment.author = request.user\n comment.save()\n else:\n form = CommentForm()\n comments = Comment.objects.filter(proposal=proposal)\n return render(request, \"cfpdetails.html\",\n {'proposal': proposal,\n 'form': form,\n 'comments': comments,\n 'editable': is_editable(proposal, request.user),\n 'blueprints': linkify(proposal.blueprints)})\n\n\n@login_required\ndef edit(request, proposalid):\n proposal = Proposal.objects.get(id=proposalid)\n if not is_editable(proposal, request.user):\n return HttpResponseForbidden(\"Forbidden\")\n if request.method == 'POST':\n form = ProposalEditForm(request.POST, instance=proposal)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/%s' % request.session['lastlist'])\n else:\n form = ProposalEditForm(instance=proposal)\n return render(request, 'cfpedit.html', {'form': form,\n 'proposal': proposal})\n\n\n@login_required\ndef delete(request, proposalid):\n proposal = Proposal.objects.get(id=proposalid)\n if ((proposal.proposer != request.user) or proposal.status in ['A', 'S']):\n return HttpResponseForbidden(\"Forbidden\")\n if request.method == 'POST':\n proposal.delete()\n return HttpResponseRedirect('/%s' % request.session['lastlist'])\n return render(request, 'cfpdelete.html', {'proposal': proposal})\n\n\n@login_required\ndef switch(request, proposalid):\n proposal = Proposal.objects.get(id=proposalid)\n if ((proposal.proposer != request.user)\n and not topiclead(request.user, proposal.topic)) or proposal.scheduled:\n return HttpResponseForbidden(\"Forbidden\")\n if request.method == 'POST':\n form = ProposalSwitchForm(request.POST, instance=proposal)\n if form.is_valid():\n form.save()\n proposal = Proposal.objects.get(id=proposalid)\n proposal.status = 'U'\n proposal.save()\n return HttpResponseRedirect('/%s' % request.session['lastlist'])\n else:\n form = ProposalSwitchForm(instance=proposal)\n return render(request, 'cfpswitch.html', {'form': form,\n 'proposal': proposal})\n\n\n@login_required\ndef review(request, proposalid):\n proposal = Proposal.objects.get(id=proposalid)\n if not topiclead(request.user, proposal.topic):\n return HttpResponseForbidden(\"Forbidden\")\n current_status = proposal.status\n status_long = proposal.get_status_display()\n if request.method == 'POST':\n form = ProposalReviewForm(request.POST, instance=proposal)\n if form.is_valid():\n form.save()\n reviewer_notes = ''\n if form.cleaned_data['comment']:\n reviewer_notes = form.cleaned_data['comment']\n c = Comment()\n c.proposal = proposal\n c.author = request.user\n c.content = reviewer_notes\n c.save()\n if (settings.SEND_MAIL and current_status != proposal.status):\n lead = User.objects.get(username=proposal.topic.lead_username)\n if (lead.email and proposal.proposer.email):\n message = \"\"\"\nThis is an automated email.\nIf needed, you should reply directly to the topic lead (%s).\n\nOn your session proposal: %s\nThe topic lead (%s) changed status from %s to %s.\n\nReviewer's notes:\n%s\n\nYou can edit your proposal at: %s/cfp/edit/%s\"\"\" \\\n % (proposal.topic.lead_username,\n smart_str(proposal.title),\n proposal.topic.lead_username,\n status_long, proposal.get_status_display(),\n smart_str(reviewer_notes),\n settings.SITE_ROOT, proposalid)\n email = EmailMessage(settings.EMAIL_PREFIX +\n \"Status change on your session proposal\",\n message, settings.EMAIL_FROM,\n [proposal.proposer.email, ], [],\n headers={'Reply-To': lead.email})\n email.send()\n return HttpResponseRedirect('/cfp/topic/%d' % proposal.topic.id)\n else:\n form = ProposalReviewForm(instance=proposal)\n comments = Comment.objects.filter(proposal=proposal)\n return render(request, 'cfpreview.html',\n {'form': form,\n 'proposal': proposal,\n 'comments': comments,\n 'blueprints': linkify(proposal.blueprints)})\n\n\ndef dologout(request):\n logout(request)\n return HttpResponseRedirect('/')\n","sub_path":"cfp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"48517668","text":"from poker.Table import *\nfrom itertools import tee\n\nclass ActionEffect(enum.Enum):\n OK = 0\n Not_enought_money = 1\n All_in_requred = 2\n Pot_already_open = 3\n Check_required = 4\n Arg_out_of_range = 5\n Too_little_ammount = 6\n Pot_is_close = 7\n Input_error = 8\n\n\ndef fold(table): \n table.turn.fold = True\n return ActionEffect.OK\n\ndef bet(table, ammount):\n if ammount <= 0:\n return ActionEffect.Arg_out_of_range\n else:\n if ammount < 2*table.smallBlind:\n return ActionEffect.Too_little_ammount\n else:\n if table.turn.money < ammount:\n return ActionEffect.Not_enought_money\n else:\n if table.table_ammount == 0:\n table.table_ammount = ammount\n table.pot += ammount\n table.turn.money -= ammount\n table.turn.table_money += ammount\n\n table.new_ender()\n \n return ActionEffect.OK\n else:\n return ActionEffect.Pot_already_open\n\ndef call(table): \n to_call = table.table_ammount - table.turn.table_money\n if to_call == 0:\n return ActionEffect.Check_required\n elif table.turn.money <= to_call:\n return ActionEffect.All_in_requred\n elif to_call > 0:\n table.turn.money -= to_call\n table.turn.table_money += to_call\n table.pot += to_call\n return ActionEffect.OK\n\n\ndef all_in(table):\n table.turn.all_in = True\n to_call = table.table_ammount - table.turn.table_money\n if table.turn.money > to_call:\n table.table_ammount = table.turn.table_money + table.turn.money\n table.pot += table.turn.money\n table.turn.table_money += table.turn.money\n table.turn.money = 0\n return ActionEffect.OK\n\ndef check(table):\n if table.table_ammount == 0:\n table.turn.check = True\n return ActionEffect.OK\n else:\n if table.turn.blind.name == 'big' and table.table_ammount == 2 * table.smallBlind:\n table.turn.check = True\n return ActionEffect.OK\n return ActionEffect.Pot_already_open\n\ndef Raise(table, ammount):\n to_call = table.table_ammount - table.turn.table_money\n raise_amm = ammount - to_call\n if table.table_ammount == 0:\n return ActionEffect.Pot_is_close\n elif ammount < 0:\n return ActionEffect.Arg_out_of_range\n else:\n if table.turn.money < ammount:\n return ActionEffect.Not_enought_money\n else:\n if raise_amm < table.table_ammount:\n return ActionEffect.Too_little_ammount\n else:\n table.table_ammount += raise_amm\n table.turn.money -= ammount\n table.pot += ammount\n table.turn.table_money += ammount\n return ActionEffect.OK","sub_path":"poker/player_actions.py","file_name":"player_actions.py","file_ext":"py","file_size_in_byte":2880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"377765512","text":"from random import *\n\nclass InvalidEntryException(Exception):\n \"\"\"This exception is raised when an entry that is passed in is not\n in the heap\"\"\"\n pass\n\nclass InvalidPositionException(Exception):\n \"\"\"This exception is raised when no entry exists at the position\n that is passed in\"\"\"\n pass\n\nclass HeapException(Exception):\n \"\"\"This exception is raised when some operation on the heap would be\n invalid, such as trying to pop from an empty heap.\"\"\"\n pass\n\nclass HeapPriorityQueue(object):\n \"\"\"An (adapted) priority queue implemented as a heap.\"\"\"\n class Entry(object):\n \"\"\"An \\\"entry\\\" in the heap contains a key and value, as expected,\n but it also contains the position of the entry in the heap. The\n information about the position allows us to make this an adapted\n priority queue, because given an entry we can locate it in O(1)\n time.\"\"\"\n\n __nextId = 0\n\n def __init__(self, key, value, pos):\n \"\"\"Creates an entry based on a key, value, and position in the heap.\"\"\"\n self.__key = key\n self.__value = value\n self.__pos = pos\n self.__id = self.__class__.__nextId\n self.__class__.__nextId += 1\n\n def __str__(self):\n \"\"\"Returns a string representation of the entry, giving key,\n value, and position information.\"\"\"\n return \"(\" + str(self.__key) + \", \" + str(self.__value) \\\n + \", \" + str(self.__pos) + \")\"\n\n def __eq__(self, other):\n \"\"\"Equality between two entries is found by comparing their\n ID's. This means, in a sense, that every entry is unique.\"\"\"\n return self.__id == other.__id\n\n def __ne__(self, other):\n \"\"\"Tests non-equality between two entries.\"\"\"\n return not self == other\n\n def key(self):\n \"\"\"Gets the key held by this entry.\"\"\"\n return self.__key\n\n def _setKey(self, key):\n \"\"\"Changes the key held by this entry. Shouldn't be called\n by external functions.\"\"\"\n self.__key = key\n\n def value(self):\n \"\"\"Gets the value held by this entry.\"\"\"\n return self.__value\n\n def _setValue(self, value):\n \"\"\"Changes the value held by this entry. Shouldn't be called\n by external functions.\"\"\"\n self.__value = value\n\n def pos(self):\n \"\"\"Gets the position held by this entry.\"\"\"\n return self.__pos\n\n def _setPos(self, pos):\n \"\"\"Changes the position held by this entry. Shouldn't be called\n by external functions.\"\"\"\n self.__pos = pos\n\n def id(self):\n \"\"\"Gets a unique identifier for this entry.\"\"\"\n return self.__id\n\n def __init__(self, l=None, cmp=None, reverse=False):\n \"\"\"Creates a new priority queue. By default, it is just an\n empty priority queue. But you can also pass in a list L of\n key-value pairs that will be added on startup. You can also\n pass in a custom comparator function CMP which is used to\n determine the ordering of the keys (CMP should behave like\n a normal Python comparator). (Otherwise, a default comparator\n which just compares keys directly using < and > is used.) Finally,\n if REVERSE is false this is a min-heap, but a max-heap otherwise.\"\"\"\n self.__heap = []\n self.__next = 0\n\n if cmp is not None:\n self.__cmp = cmp\n else:\n self.__cmp = self.__defaultCmp\n self.__reverse = reverse\n\n if l is not None:\n self.heapify(l)\n\n def __str__(self):\n \"\"\"Returns a string representation of this priority queue. Prints\n out the array representation of the internal heap, and the entry\n in each cell. (This could be better, but anything superior would\n probably require ASCII art.)\"\"\"\n sList = [\"[\"]\n for e in self.__heap[0:self.__next]:\n sList.append(str(e) + \" \")\n s = ''.join(sList)\n s = s[0:(len(s) - 1)] + \"]\"\n return s\n\n def __len__(self):\n \"\"\"Gets the number of entries currently in the heap.\"\"\"\n return self.__next\n\n def __defaultCmp(self, k1, k2):\n \"\"\"The default comparator for comparing two keys. It does exactly\n what you would expect.\"\"\"\n if k1 == k2:\n return 0\n elif k1 > k2:\n return 1\n else:\n return -1\n\n def __fCmp(self, e1, e2):\n \"\"\"A helper function for convenience. Given two entries E1 and E2,\n it compares the keys contained in the entries as necessitated by the parameters\n passed into __init__() (including REVERSE)\"\"\"\n result = self.__cmp(e1.key(), e2.key())\n if self.__reverse:\n return -result\n else:\n return result\n\n def __leftChild(self, e):\n \"\"\"Gets the left child of an entry E. (helper)\"\"\"\n return self.__heap[e.pos() * 2 + 1]\n\n def __rightChild(self, e):\n \"\"\"Gets the right child of an entry E. (helper)\"\"\"\n return self.__heap[e.pos() * 2 + 2]\n\n def __parent(self, e):\n \"\"\"Gets the parent of an entry E. (helper)\"\"\"\n return self.__heap[(e.pos() - 1) // 2]\n\n def __swap(self, e1, e2):\n \"\"\"Helper that swaps two entries in the heap, making sure to maintain\n the position markers in the entries, etc. This is at the core\n of upheap and downheap.\"\"\"\n tmp = e1.pos()\n e1._setPos(e2.pos())\n e2._setPos(tmp)\n\n tmp = self.__heap[e1.pos()]\n self.__heap[e1.pos()] = self.__heap[e2.pos()]\n self.__heap[e2.pos()] = tmp\n\n def __upHeap(self, e):\n \"\"\"Helper that does upheap on an entry E in the heap.\"\"\"\n while e.pos() > 0 and self.__fCmp(e, self.__parent(e)) < 0:\n self.__swap(e, self.__parent(e))\n\n return e\n\n def __downHeap(self, e, end = None):\n if end is None: end = self.__next\n\n \"\"\"Helper that does downheap on an entry E in the heap. Restricts\"\"\"\n while (e.pos() * 2 + 1 < end \\\n and self.__fCmp(e, self.__leftChild(e)) > 0) \\\n or (e.pos() * 2 + 2 < end \\\n and self.__fCmp(e, self.__rightChild(e)) > 0):\n if e.pos() * 2 + 2 >= end \\\n or self.__fCmp(self.__leftChild(e), self.__rightChild(e)) < 0:\n c = self.__leftChild(e)\n self.__swap(e, c)\n else:\n c = self.__rightChild(e)\n self.__swap(e, c)\n\n return e\n\n def __fixPosition(self, e):\n \"\"\"Helper that \\\"fixes\\\" the position of an entry E somewhere in\n the heap. That is, assuming the entry has correct position information,\n and all other entries are in the correct position, it upheaps or downheaps\n the entry as necessary so that the heap remains in heap order.\"\"\"\n if e.pos() > 0 and self.__fCmp(e, self.__parent(e)) < 0:\n return self.__upHeap(e)\n else:\n return self.__downHeap(e)\n\n def __getitem__(self, pos):\n \"\"\"Gets an entry at a certain position in the heap.\n\n Throws InvalidPositionException if no such position is in the heap.\n\n Runs in O(1).\"\"\"\n if pos < 0 or pos >= self.__next:\n raise InvalidPositionException(\"position does not exist in heap\")\n\n return self.__heap[pos]\n\n def isEmpty(self):\n \"\"\"Returns whether this priority queue is empty.\"\"\"\n return len(self) == 0\n\n def top(self):\n \"\"\"Gets the entry at the top of the heap (the entry with lowest key)\n\n Throws HeapException if the heap is empty.\n\n Runs in O(1).\"\"\"\n if self.__next == 0:\n raise HeapException(\"no value in empty heap\")\n\n return self.__heap[0]\n\n def push(self, key, value):\n \"\"\"Adds a key-value pair to the heap.\n\n Runs in O(log n).\"\"\"\n if self.__next >= len(self.__heap):\n self.__heap.append(None)\n e = HeapPriorityQueue.Entry(key, value, self.__next)\n self.__heap[self.__next] = e\n self.__next += 1\n\n return self.__upHeap(e)\n\n def pop(self):\n \"\"\"Removes the entry at the top of the heap (the entry with lowest key),\n and returns it.\n\n Throws HeapException if the heap is empty.\n\n Runs in O(log n).\"\"\"\n if self.__next == 0:\n raise HeapException(\"cannot pop from empty heap\")\n\n e = self.__heap[0]\n self.__next -= 1\n\n if self.__next == 0: # heap is empty\n return e\n\n self.__heap[0] = self.__heap[self.__next]\n self.__heap[0]._setPos(0)\n self.__downHeap(self.__heap[0])\n\n return e\n\n def remove(self, entry):\n \"\"\"Removes an entry ENTRY from the heap, returning ENTRY.\n\n Throws InvalidEntryException if the entry is not in the heap.\n\n Runs in O(log n)\"\"\"\n self.__testEntry(entry)\n\n pos = entry.pos()\n\n self.__next -= 1\n rEntry = self.__heap[self.__next]\n\n # We got lucky and removed the last node\n if pos == self.__next:\n return entry\n\n self.__heap[pos] = rEntry\n rEntry._setPos(pos)\n self.__fixPosition(rEntry)\n\n return entry\n\n def replaceKey(self, entry, key):\n \"\"\"Replaces the key of an entry ENTRY in the priority queue, with KEY\n (of course the heap will be adjusted.), returning ENTRY (with the new\n KEY)\n\n Throws InvalidEntryException if the entry is not in the heap.\n\n Runs in O(log n)\"\"\"\n self.__testEntry(entry)\n\n self.__heap[entry.pos()]._setKey(key)\n return self.__fixPosition(entry)\n\n def replaceValue(self, entry, value):\n \"\"\"Replaces the value of an entry ENTRY in the priority queue, with\n VALUE\n\n Throws InvalidEntryException if the entry is not in the heap.\n\n Runs in O(1).\"\"\"\n self.__testEntry(entry)\n\n pos = entry.pos()\n self.__heap[pos]._setValue(value)\n\n return self.__heap[pos]\n\n def merge(self, q):\n \"\"\"Merges this HeapPriorityQueue with another one, Q.\n\n Throws HeapException if the two queues do not use the same comparator\n or ordering (min/max) (after all, it makes no sense to combine a\n min-heap with a max-heap!)\n\n Runs in O(n) time.\n\n #if self.__cmp != q.__cmp or self.__reverse != q.__reverse:\n # raise HeapException, \"heaps do not use same parameters\"\n posa = 0\n posb = 0\n npos = 0\n newQ = HeapPriorityQueue(cmp = self.__cmp, reverse = self.__reverse)\n\n while posa < self.__next and posb < q.__next:\n if self.__fCmp(self[posa], q[posb]) < 0:\n newQ.__heap.append(self.Entry( \\\n self[posa].key(), self[posa].value(), npos))\n posa += 1\n npos += 1\n else:\n newQ.__heap.append(self.Entry( \\\n q[posb].key(), q[posb].value(), npos))\n posb += 1\n npos += 1\n\n while posa < self.__next:\n newQ.__heap.append(self.Entry( \\\n self[posa].key(), self[posa].value(), npos))\n posa += 1\n npos += 1\n\n while posb < q.__next:\n newQ.__heap.append(q.Entry( \\\n q[posb].key(), q[posb].value(), npos))\n posb += 1\n npos += 1\n\n newQ.__next = self.__next + q.__next\n self.__heap = newQ.__heap\n self.__next = newQ.__next\"\"\"\n pass\n\n def heapify(self, l):\n \"\"\"Recreates the heap out of a list L, by heapifying it.\n\n This method runs in O(n) time.\"\"\"\n\n self.__heap = []\n # \"convert\" the array into our internal array, using Entry format\n for i in range(0, len(l)):\n self.__heap.append(self.Entry(l[i][0], l[i][1], i))\n self.__next = len(l)\n\n for i in range((len(l) - 1) // 2, -1, -1):\n self.__downHeap(self.__heap[i])\n\n def __testEntry(self, entry):\n \"\"\"Helper that checks whether an entry is in the heap.\n\n More precisely, it first sees if the entry has a valid position value,\n and if so, retrieves the entry allegedly at that position, ensuring\n that it's the same as ENTRY.\"\"\"\n\n if entry is None:\n raise InvalidEntryException(\"Entry is None\")\n\n pos = entry.pos()\n if pos < 0 or pos >= len(self) or self.__heap[pos] != entry:\n raise InvalidEntryException(\"Entry is not in this heap\")\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"cs16/hw9/heappriorityqueue.py","file_name":"heappriorityqueue.py","file_ext":"py","file_size_in_byte":12700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"91191364","text":"n, m = map(int, input().split())\na_list, b_list = input().split(), input().split()\n\nres = 0\naction_list = []\nwhile True:\n res += 1\n if b_list[0] == a_list[0]:\n a_list = a_list[1:]\n if not a_list:\n action_list.append('1')\n break\n if b_list[0] == a_list[0]:\n action_list.append('1')\n else:\n try:\n k = a_list.index(b_list[0])\n k_list = set(a_list[:k])\n ind = 0\n for u in k_list:\n ind = max(ind, b_list.index(u))\n b_list.insert(ind + 1, b_list[0])\n b_list = b_list[1:]\n action_list.append(str(ind+1))\n except ValueError:\n b_list.append(b_list[0])\n b_list = b_list[1:]\n action_list.append(str(n))\nprint(res)\nprint(' '.join(action_list))\n","sub_path":"task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"418292225","text":"# -*- coding: utf-8 -*-\n\"\"\"\nProfile: http://hl7.org/fhir/StructureDefinition/CodeSystem\nRelease: STU3\nVersion: 3.0.2\nRevision: 11917\nLast updated: 2019-10-24T11:53:00+11:00\n\"\"\"\nimport typing\n\nfrom pydantic import Field, root_validator\nfrom pydantic.error_wrappers import ErrorWrapper, ValidationError\nfrom pydantic.errors import MissingError, NoneIsNotAllowedError\n\nfrom . import backboneelement, domainresource, fhirtypes\n\n\nclass CodeSystem(domainresource.DomainResource):\n \"\"\"Disclaimer: Any field name ends with ``__ext`` doesn't part of\n Resource StructureDefinition, instead used to enable Extensibility feature\n for FHIR Primitive Data Types.\n\n A set of codes drawn from one or more code systems.\n A code system resource specifies a set of codes drawn from one or more code\n systems.\n \"\"\"\n\n resource_type = Field(\"CodeSystem\", const=True)\n\n caseSensitive: bool = Field(\n None,\n alias=\"caseSensitive\",\n title=\"If code comparison is case sensitive\",\n description=(\n \"If code comparison is case sensitive when codes within this system are\"\n \" compared to each other.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n caseSensitive__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_caseSensitive\", title=\"Extension field for ``caseSensitive``.\"\n )\n\n compositional: bool = Field(\n None,\n alias=\"compositional\",\n title=\"If code system defines a post-composition grammar\",\n description=\"True If code system defines a post-composition grammar.\",\n # if property is element of this resource.\n element_property=True,\n )\n compositional__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_compositional\", title=\"Extension field for ``compositional``.\"\n )\n\n concept: typing.List[fhirtypes.CodeSystemConceptType] = Field(\n None,\n alias=\"concept\",\n title=\"Concepts in the code system\",\n description=(\n \"Concepts that are in the code system. The concept definitions are \"\n \"inherently hierarchical, but the definitions must be consulted to \"\n \"determine what the meaning of the hierarchical relationships are.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n\n contact: typing.List[fhirtypes.ContactDetailType] = Field(\n None,\n alias=\"contact\",\n title=\"Contact details for the publisher\",\n description=(\n \"Contact details to assist a user in finding and communicating with the\"\n \" publisher.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n\n content: fhirtypes.Code = Field(\n None,\n alias=\"content\",\n title=\"not-present | example | fragment | complete\",\n description=(\n \"How much of the content of the code system - the concepts and codes it\"\n \" defines - are represented in this resource.\"\n ),\n # if property is element of this resource.\n element_property=True,\n element_required=True,\n # note: Enum values can be used in validation,\n # but use in your own responsibilities, read official FHIR documentation.\n enum_values=[\"not-present\", \"example\", \"fragment\", \"complete\"],\n )\n content__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_content\", title=\"Extension field for ``content``.\"\n )\n\n copyright: fhirtypes.Markdown = Field(\n None,\n alias=\"copyright\",\n title=\"Use and/or publishing restrictions\",\n description=(\n \"A copyright statement relating to the code system and/or its contents.\"\n \" Copyright statements are generally legal restrictions on the use and \"\n \"publishing of the code system.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n copyright__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_copyright\", title=\"Extension field for ``copyright``.\"\n )\n\n count: fhirtypes.UnsignedInt = Field(\n None,\n alias=\"count\",\n title=\"Total concepts in the code system\",\n description=(\n \"The total number of concepts defined by the code system. Where the \"\n \"code system has a compositional grammar, the count refers to the \"\n \"number of base (primitive) concepts.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n count__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_count\", title=\"Extension field for ``count``.\"\n )\n\n date: fhirtypes.DateTime = Field(\n None,\n alias=\"date\",\n title=\"Date this was last changed\",\n description=(\n \"The date (and optionally time) when the code system was published. \"\n \"The date must change if and when the business version changes and it \"\n \"must change if the status code changes. In addition, it should change \"\n \"when the substantive content of the code system changes.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n date__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_date\", title=\"Extension field for ``date``.\"\n )\n\n description: fhirtypes.Markdown = Field(\n None,\n alias=\"description\",\n title=\"Natural language description of the code system\",\n description=(\n \"A free text natural language description of the code system from a \"\n \"consumer's perspective.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n description__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_description\", title=\"Extension field for ``description``.\"\n )\n\n experimental: bool = Field(\n None,\n alias=\"experimental\",\n title=\"For testing purposes, not real usage\",\n description=(\n \"A boolean value to indicate that this code system is authored for \"\n \"testing purposes (or education/evaluation/marketing), and is not \"\n \"intended to be used for genuine usage.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n experimental__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_experimental\", title=\"Extension field for ``experimental``.\"\n )\n\n filter: typing.List[fhirtypes.CodeSystemFilterType] = Field(\n None,\n alias=\"filter\",\n title=\"Filter that can be used in a value set\",\n description=(\n \"A filter that can be used in a value set compose statement when \"\n \"selecting concepts using a filter.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n\n hierarchyMeaning: fhirtypes.Code = Field(\n None,\n alias=\"hierarchyMeaning\",\n title=\"grouped-by | is-a | part-of | classified-with\",\n description=\"The meaning of the hierarchy of concepts.\",\n # if property is element of this resource.\n element_property=True,\n # note: Enum values can be used in validation,\n # but use in your own responsibilities, read official FHIR documentation.\n enum_values=[\"grouped-by\", \"is-a\", \"part-of\", \"classified-with\"],\n )\n hierarchyMeaning__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None,\n alias=\"_hierarchyMeaning\",\n title=\"Extension field for ``hierarchyMeaning``.\",\n )\n\n identifier: fhirtypes.IdentifierType = Field(\n None,\n alias=\"identifier\",\n title=\"Additional identifier for the code system\",\n description=(\n \"A formal identifier that is used to identify this code system when it \"\n \"is represented in other formats, or referenced in a specification, \"\n \"model, design or an instance.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n\n jurisdiction: typing.List[fhirtypes.CodeableConceptType] = Field(\n None,\n alias=\"jurisdiction\",\n title=\"Intended jurisdiction for code system (if applicable)\",\n description=(\n \"A legal or geographic region in which the code system is intended to \"\n \"be used.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n\n name: fhirtypes.String = Field(\n None,\n alias=\"name\",\n title=\"Name for this code system (computer friendly)\",\n description=(\n \"A natural language name identifying the code system. This name should \"\n \"be usable as an identifier for the module by machine processing \"\n \"applications such as code generation.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n name__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_name\", title=\"Extension field for ``name``.\"\n )\n\n property: typing.List[fhirtypes.CodeSystemPropertyType] = Field(\n None,\n alias=\"property\",\n title=\"Additional information supplied about each concept\",\n description=(\n \"A property defines an additional slot through which additional \"\n \"information can be provided about a concept.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n\n publisher: fhirtypes.String = Field(\n None,\n alias=\"publisher\",\n title=\"Name of the publisher (organization or individual)\",\n description=(\n \"The name of the individual or organization that published the code \"\n \"system.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n publisher__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_publisher\", title=\"Extension field for ``publisher``.\"\n )\n\n purpose: fhirtypes.Markdown = Field(\n None,\n alias=\"purpose\",\n title=\"Why this code system is defined\",\n description=(\n \"Explaination of why this code system is needed and why it has been \"\n \"designed as it has.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n purpose__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_purpose\", title=\"Extension field for ``purpose``.\"\n )\n\n status: fhirtypes.Code = Field(\n None,\n alias=\"status\",\n title=\"draft | active | retired | unknown\",\n description=(\n \"The status of this code system. Enables tracking the life-cycle of the\"\n \" content.\"\n ),\n # if property is element of this resource.\n element_property=True,\n element_required=True,\n # note: Enum values can be used in validation,\n # but use in your own responsibilities, read official FHIR documentation.\n enum_values=[\"draft\", \"active\", \"retired\", \"unknown\"],\n )\n status__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_status\", title=\"Extension field for ``status``.\"\n )\n\n title: fhirtypes.String = Field(\n None,\n alias=\"title\",\n title=\"Name for this code system (human friendly)\",\n description=\"A short, descriptive, user-friendly title for the code system.\",\n # if property is element of this resource.\n element_property=True,\n )\n title__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_title\", title=\"Extension field for ``title``.\"\n )\n\n url: fhirtypes.Uri = Field(\n None,\n alias=\"url\",\n title=(\n \"Logical URI to reference this code system (globally unique) \"\n \"(Coding.system)\"\n ),\n description=(\n \"An absolute URI that is used to identify this code system when it is \"\n \"referenced in a specification, model, design or an instance. This \"\n \"SHALL be a URL, SHOULD be globally unique, and SHOULD be an address at\"\n \" which this code system is (or will be) published. The URL SHOULD \"\n \"include the major version of the code system. For more information see\"\n \" [Technical and Business Versions](resource.html#versions). This is \"\n \"used in [Coding]{datatypes.html#Coding}.system.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n url__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_url\", title=\"Extension field for ``url``.\"\n )\n\n useContext: typing.List[fhirtypes.UsageContextType] = Field(\n None,\n alias=\"useContext\",\n title=\"Context the content is intended to support\",\n description=(\n \"The content was developed with a focus and intent of supporting the \"\n \"contexts that are listed. These terms may be used to assist with \"\n \"indexing and searching for appropriate code system instances.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n\n valueSet: fhirtypes.Uri = Field(\n None,\n alias=\"valueSet\",\n title=\"Canonical URL for value set with entire code system\",\n description=\"Canonical URL of value set that contains the entire code system.\",\n # if property is element of this resource.\n element_property=True,\n )\n valueSet__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueSet\", title=\"Extension field for ``valueSet``.\"\n )\n\n version: fhirtypes.String = Field(\n None,\n alias=\"version\",\n title=\"Business version of the code system (Coding.version)\",\n description=(\n \"The identifier that is used to identify this version of the code \"\n \"system when it is referenced in a specification, model, design or \"\n \"instance. This is an arbitrary value managed by the code system author\"\n \" and is not expected to be globally unique. For example, it might be a\"\n \" timestamp (e.g. yyyymmdd) if a managed version is not available. \"\n \"There is also no expectation that versions can be placed in a \"\n \"lexicographical sequence. This is used in \"\n \"[Coding]{datatypes.html#Coding}.version.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n version__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_version\", title=\"Extension field for ``version``.\"\n )\n\n versionNeeded: bool = Field(\n None,\n alias=\"versionNeeded\",\n title=\"If definitions are not stable\",\n description=(\n \"This flag is used to signify that the code system has not (or does \"\n \"not) maintain the definitions, and a version must be specified when \"\n \"referencing this code system.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n versionNeeded__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_versionNeeded\", title=\"Extension field for ``versionNeeded``.\"\n )\n\n @classmethod\n def elements_sequence(cls):\n \"\"\"returning all elements names from\n ``CodeSystem`` according specification,\n with preserving original sequence order.\n \"\"\"\n return [\n \"id\",\n \"meta\",\n \"implicitRules\",\n \"language\",\n \"text\",\n \"contained\",\n \"extension\",\n \"modifierExtension\",\n \"url\",\n \"identifier\",\n \"version\",\n \"name\",\n \"title\",\n \"status\",\n \"experimental\",\n \"date\",\n \"publisher\",\n \"contact\",\n \"description\",\n \"useContext\",\n \"jurisdiction\",\n \"purpose\",\n \"copyright\",\n \"caseSensitive\",\n \"valueSet\",\n \"hierarchyMeaning\",\n \"compositional\",\n \"versionNeeded\",\n \"content\",\n \"count\",\n \"filter\",\n \"property\",\n \"concept\",\n ]\n\n @root_validator(pre=True, allow_reuse=True)\n def validate_required_primitive_elements_1200(\n cls, values: typing.Dict[str, typing.Any]\n ) -> typing.Dict[str, typing.Any]:\n \"\"\"https://www.hl7.org/fhir/extensibility.html#Special-Case\n In some cases, implementers might find that they do not have appropriate data for\n an element with minimum cardinality = 1. In this case, the element must be present,\n but unless the resource or a profile on it has made the actual value of the primitive\n data type mandatory, it is possible to provide an extension that explains why\n the primitive value is not present.\n \"\"\"\n required_fields = [(\"content\", \"content__ext\"), (\"status\", \"status__ext\")]\n _missing = object()\n\n def _fallback():\n return \"\"\n\n errors: typing.List[\"ErrorWrapper\"] = []\n for name, ext in required_fields:\n field = cls.__fields__[name]\n ext_field = cls.__fields__[ext]\n value = values.get(field.alias, _missing)\n if value not in (_missing, None):\n continue\n ext_value = values.get(ext_field.alias, _missing)\n missing_ext = True\n if ext_value not in (_missing, None):\n if isinstance(ext_value, dict):\n missing_ext = len(ext_value.get(\"extension\", [])) == 0\n elif (\n getattr(ext_value.__class__, \"get_resource_type\", _fallback)()\n == \"FHIRPrimitiveExtension\"\n ):\n if ext_value.extension and len(ext_value.extension) > 0:\n missing_ext = False\n else:\n validate_pass = True\n for validator in ext_field.type_.__get_validators__():\n try:\n ext_value = validator(v=ext_value)\n except ValidationError as exc:\n errors.append(ErrorWrapper(exc, loc=ext_field.alias))\n validate_pass = False\n if not validate_pass:\n continue\n if ext_value.extension and len(ext_value.extension) > 0:\n missing_ext = False\n if missing_ext:\n if value is _missing:\n errors.append(ErrorWrapper(MissingError(), loc=field.alias))\n else:\n errors.append(\n ErrorWrapper(NoneIsNotAllowedError(), loc=field.alias)\n )\n if len(errors) > 0:\n raise ValidationError(errors, cls) # type: ignore\n\n return values\n\n\nclass CodeSystemConcept(backboneelement.BackboneElement):\n \"\"\"Disclaimer: Any field name ends with ``__ext`` doesn't part of\n Resource StructureDefinition, instead used to enable Extensibility feature\n for FHIR Primitive Data Types.\n\n Concepts in the code system.\n Concepts that are in the code system. The concept definitions are\n inherently hierarchical, but the definitions must be consulted to determine\n what the meaning of the hierarchical relationships are.\n \"\"\"\n\n resource_type = Field(\"CodeSystemConcept\", const=True)\n\n code: fhirtypes.Code = Field(\n None,\n alias=\"code\",\n title=\"Code that identifies concept\",\n description=(\n \"A code - a text symbol - that uniquely identifies the concept within \"\n \"the code system.\"\n ),\n # if property is element of this resource.\n element_property=True,\n element_required=True,\n )\n code__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_code\", title=\"Extension field for ``code``.\"\n )\n\n concept: typing.List[fhirtypes.CodeSystemConceptType] = Field(\n None,\n alias=\"concept\",\n title=\"Child Concepts (is-a/contains/categorizes)\",\n description=(\n \"Defines children of a concept to produce a hierarchy of concepts. The \"\n \"nature of the relationships is variable (is-a/contains/categorizes) - \"\n \"see hierarchyMeaning.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n\n definition: fhirtypes.String = Field(\n None,\n alias=\"definition\",\n title=\"Formal definition\",\n description=(\n \"The formal definition of the concept. The code system resource does \"\n \"not make formal definitions required, because of the prevalence of \"\n \"legacy systems. However, they are highly recommended, as without them \"\n \"there is no formal meaning associated with the concept.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n definition__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_definition\", title=\"Extension field for ``definition``.\"\n )\n\n designation: typing.List[fhirtypes.CodeSystemConceptDesignationType] = Field(\n None,\n alias=\"designation\",\n title=\"Additional representations for the concept\",\n description=(\n \"Additional representations for the concept - other languages, aliases,\"\n \" specialized purposes, used for particular purposes, etc.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n\n display: fhirtypes.String = Field(\n None,\n alias=\"display\",\n title=\"Text to display to the user\",\n description=(\n \"A human readable string that is the recommended default way to present\"\n \" this concept to a user.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n display__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_display\", title=\"Extension field for ``display``.\"\n )\n\n property: typing.List[fhirtypes.CodeSystemConceptPropertyType] = Field(\n None,\n alias=\"property\",\n title=\"Property value for the concept\",\n description=\"A property value for this concept.\",\n # if property is element of this resource.\n element_property=True,\n )\n\n @classmethod\n def elements_sequence(cls):\n \"\"\"returning all elements names from\n ``CodeSystemConcept`` according specification,\n with preserving original sequence order.\n \"\"\"\n return [\n \"id\",\n \"extension\",\n \"modifierExtension\",\n \"code\",\n \"display\",\n \"definition\",\n \"designation\",\n \"property\",\n \"concept\",\n ]\n\n @root_validator(pre=True, allow_reuse=True)\n def validate_required_primitive_elements_1923(\n cls, values: typing.Dict[str, typing.Any]\n ) -> typing.Dict[str, typing.Any]:\n \"\"\"https://www.hl7.org/fhir/extensibility.html#Special-Case\n In some cases, implementers might find that they do not have appropriate data for\n an element with minimum cardinality = 1. In this case, the element must be present,\n but unless the resource or a profile on it has made the actual value of the primitive\n data type mandatory, it is possible to provide an extension that explains why\n the primitive value is not present.\n \"\"\"\n required_fields = [(\"code\", \"code__ext\")]\n _missing = object()\n\n def _fallback():\n return \"\"\n\n errors: typing.List[\"ErrorWrapper\"] = []\n for name, ext in required_fields:\n field = cls.__fields__[name]\n ext_field = cls.__fields__[ext]\n value = values.get(field.alias, _missing)\n if value not in (_missing, None):\n continue\n ext_value = values.get(ext_field.alias, _missing)\n missing_ext = True\n if ext_value not in (_missing, None):\n if isinstance(ext_value, dict):\n missing_ext = len(ext_value.get(\"extension\", [])) == 0\n elif (\n getattr(ext_value.__class__, \"get_resource_type\", _fallback)()\n == \"FHIRPrimitiveExtension\"\n ):\n if ext_value.extension and len(ext_value.extension) > 0:\n missing_ext = False\n else:\n validate_pass = True\n for validator in ext_field.type_.__get_validators__():\n try:\n ext_value = validator(v=ext_value)\n except ValidationError as exc:\n errors.append(ErrorWrapper(exc, loc=ext_field.alias))\n validate_pass = False\n if not validate_pass:\n continue\n if ext_value.extension and len(ext_value.extension) > 0:\n missing_ext = False\n if missing_ext:\n if value is _missing:\n errors.append(ErrorWrapper(MissingError(), loc=field.alias))\n else:\n errors.append(\n ErrorWrapper(NoneIsNotAllowedError(), loc=field.alias)\n )\n if len(errors) > 0:\n raise ValidationError(errors, cls) # type: ignore\n\n return values\n\n\nclass CodeSystemConceptDesignation(backboneelement.BackboneElement):\n \"\"\"Disclaimer: Any field name ends with ``__ext`` doesn't part of\n Resource StructureDefinition, instead used to enable Extensibility feature\n for FHIR Primitive Data Types.\n\n Additional representations for the concept.\n Additional representations for the concept - other languages, aliases,\n specialized purposes, used for particular purposes, etc.\n \"\"\"\n\n resource_type = Field(\"CodeSystemConceptDesignation\", const=True)\n\n language: fhirtypes.Code = Field(\n None,\n alias=\"language\",\n title=\"Human language of the designation\",\n description=\"The language this designation is defined for.\",\n # if property is element of this resource.\n element_property=True,\n )\n language__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_language\", title=\"Extension field for ``language``.\"\n )\n\n use: fhirtypes.CodingType = Field(\n None,\n alias=\"use\",\n title=\"Details how this designation would be used\",\n description=\"A code that details how this designation would be used.\",\n # if property is element of this resource.\n element_property=True,\n )\n\n value: fhirtypes.String = Field(\n None,\n alias=\"value\",\n title=\"The text value for this designation\",\n description=None,\n # if property is element of this resource.\n element_property=True,\n element_required=True,\n )\n value__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_value\", title=\"Extension field for ``value``.\"\n )\n\n @classmethod\n def elements_sequence(cls):\n \"\"\"returning all elements names from\n ``CodeSystemConceptDesignation`` according specification,\n with preserving original sequence order.\n \"\"\"\n return [\"id\", \"extension\", \"modifierExtension\", \"language\", \"use\", \"value\"]\n\n @root_validator(pre=True, allow_reuse=True)\n def validate_required_primitive_elements_3058(\n cls, values: typing.Dict[str, typing.Any]\n ) -> typing.Dict[str, typing.Any]:\n \"\"\"https://www.hl7.org/fhir/extensibility.html#Special-Case\n In some cases, implementers might find that they do not have appropriate data for\n an element with minimum cardinality = 1. In this case, the element must be present,\n but unless the resource or a profile on it has made the actual value of the primitive\n data type mandatory, it is possible to provide an extension that explains why\n the primitive value is not present.\n \"\"\"\n required_fields = [(\"value\", \"value__ext\")]\n _missing = object()\n\n def _fallback():\n return \"\"\n\n errors: typing.List[\"ErrorWrapper\"] = []\n for name, ext in required_fields:\n field = cls.__fields__[name]\n ext_field = cls.__fields__[ext]\n value = values.get(field.alias, _missing)\n if value not in (_missing, None):\n continue\n ext_value = values.get(ext_field.alias, _missing)\n missing_ext = True\n if ext_value not in (_missing, None):\n if isinstance(ext_value, dict):\n missing_ext = len(ext_value.get(\"extension\", [])) == 0\n elif (\n getattr(ext_value.__class__, \"get_resource_type\", _fallback)()\n == \"FHIRPrimitiveExtension\"\n ):\n if ext_value.extension and len(ext_value.extension) > 0:\n missing_ext = False\n else:\n validate_pass = True\n for validator in ext_field.type_.__get_validators__():\n try:\n ext_value = validator(v=ext_value)\n except ValidationError as exc:\n errors.append(ErrorWrapper(exc, loc=ext_field.alias))\n validate_pass = False\n if not validate_pass:\n continue\n if ext_value.extension and len(ext_value.extension) > 0:\n missing_ext = False\n if missing_ext:\n if value is _missing:\n errors.append(ErrorWrapper(MissingError(), loc=field.alias))\n else:\n errors.append(\n ErrorWrapper(NoneIsNotAllowedError(), loc=field.alias)\n )\n if len(errors) > 0:\n raise ValidationError(errors, cls) # type: ignore\n\n return values\n\n\nclass CodeSystemConceptProperty(backboneelement.BackboneElement):\n \"\"\"Disclaimer: Any field name ends with ``__ext`` doesn't part of\n Resource StructureDefinition, instead used to enable Extensibility feature\n for FHIR Primitive Data Types.\n\n Property value for the concept.\n A property value for this concept.\n \"\"\"\n\n resource_type = Field(\"CodeSystemConceptProperty\", const=True)\n\n code: fhirtypes.Code = Field(\n None,\n alias=\"code\",\n title=\"Reference to CodeSystem.property.code\",\n description=\"A code that is a reference to CodeSystem.property.code.\",\n # if property is element of this resource.\n element_property=True,\n element_required=True,\n )\n code__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_code\", title=\"Extension field for ``code``.\"\n )\n\n valueBoolean: bool = Field(\n None,\n alias=\"valueBoolean\",\n title=\"Value of the property for this concept\",\n description=\"The value of this property.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=True,\n )\n valueBoolean__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueBoolean\", title=\"Extension field for ``valueBoolean``.\"\n )\n\n valueCode: fhirtypes.Code = Field(\n None,\n alias=\"valueCode\",\n title=\"Value of the property for this concept\",\n description=\"The value of this property.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=True,\n )\n valueCode__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueCode\", title=\"Extension field for ``valueCode``.\"\n )\n\n valueCoding: fhirtypes.CodingType = Field(\n None,\n alias=\"valueCoding\",\n title=\"Value of the property for this concept\",\n description=\"The value of this property.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=True,\n )\n\n valueDateTime: fhirtypes.DateTime = Field(\n None,\n alias=\"valueDateTime\",\n title=\"Value of the property for this concept\",\n description=\"The value of this property.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=True,\n )\n valueDateTime__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueDateTime\", title=\"Extension field for ``valueDateTime``.\"\n )\n\n valueInteger: fhirtypes.Integer = Field(\n None,\n alias=\"valueInteger\",\n title=\"Value of the property for this concept\",\n description=\"The value of this property.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=True,\n )\n valueInteger__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueInteger\", title=\"Extension field for ``valueInteger``.\"\n )\n\n valueString: fhirtypes.String = Field(\n None,\n alias=\"valueString\",\n title=\"Value of the property for this concept\",\n description=\"The value of this property.\",\n # if property is element of this resource.\n element_property=True,\n # Choice of Data Types. i.e value[x]\n one_of_many=\"value\",\n one_of_many_required=True,\n )\n valueString__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_valueString\", title=\"Extension field for ``valueString``.\"\n )\n\n @classmethod\n def elements_sequence(cls):\n \"\"\"returning all elements names from\n ``CodeSystemConceptProperty`` according specification,\n with preserving original sequence order.\n \"\"\"\n return [\n \"id\",\n \"extension\",\n \"modifierExtension\",\n \"code\",\n \"valueCode\",\n \"valueCoding\",\n \"valueString\",\n \"valueInteger\",\n \"valueBoolean\",\n \"valueDateTime\",\n ]\n\n @root_validator(pre=True, allow_reuse=True)\n def validate_required_primitive_elements_2797(\n cls, values: typing.Dict[str, typing.Any]\n ) -> typing.Dict[str, typing.Any]:\n \"\"\"https://www.hl7.org/fhir/extensibility.html#Special-Case\n In some cases, implementers might find that they do not have appropriate data for\n an element with minimum cardinality = 1. In this case, the element must be present,\n but unless the resource or a profile on it has made the actual value of the primitive\n data type mandatory, it is possible to provide an extension that explains why\n the primitive value is not present.\n \"\"\"\n required_fields = [(\"code\", \"code__ext\")]\n _missing = object()\n\n def _fallback():\n return \"\"\n\n errors: typing.List[\"ErrorWrapper\"] = []\n for name, ext in required_fields:\n field = cls.__fields__[name]\n ext_field = cls.__fields__[ext]\n value = values.get(field.alias, _missing)\n if value not in (_missing, None):\n continue\n ext_value = values.get(ext_field.alias, _missing)\n missing_ext = True\n if ext_value not in (_missing, None):\n if isinstance(ext_value, dict):\n missing_ext = len(ext_value.get(\"extension\", [])) == 0\n elif (\n getattr(ext_value.__class__, \"get_resource_type\", _fallback)()\n == \"FHIRPrimitiveExtension\"\n ):\n if ext_value.extension and len(ext_value.extension) > 0:\n missing_ext = False\n else:\n validate_pass = True\n for validator in ext_field.type_.__get_validators__():\n try:\n ext_value = validator(v=ext_value)\n except ValidationError as exc:\n errors.append(ErrorWrapper(exc, loc=ext_field.alias))\n validate_pass = False\n if not validate_pass:\n continue\n if ext_value.extension and len(ext_value.extension) > 0:\n missing_ext = False\n if missing_ext:\n if value is _missing:\n errors.append(ErrorWrapper(MissingError(), loc=field.alias))\n else:\n errors.append(\n ErrorWrapper(NoneIsNotAllowedError(), loc=field.alias)\n )\n if len(errors) > 0:\n raise ValidationError(errors, cls) # type: ignore\n\n return values\n\n @root_validator(pre=True, allow_reuse=True)\n def validate_one_of_many_2797(\n cls, values: typing.Dict[str, typing.Any]\n ) -> typing.Dict[str, typing.Any]:\n \"\"\"https://www.hl7.org/fhir/formats.html#choice\n A few elements have a choice of more than one data type for their content.\n All such elements have a name that takes the form nnn[x].\n The \"nnn\" part of the name is constant, and the \"[x]\" is replaced with\n the title-cased name of the type that is actually used.\n The table view shows each of these names explicitly.\n\n Elements that have a choice of data type cannot repeat - they must have a\n maximum cardinality of 1. When constructing an instance of an element with a\n choice of types, the authoring system must create a single element with a\n data type chosen from among the list of permitted data types.\n \"\"\"\n one_of_many_fields = {\n \"value\": [\n \"valueBoolean\",\n \"valueCode\",\n \"valueCoding\",\n \"valueDateTime\",\n \"valueInteger\",\n \"valueString\",\n ]\n }\n for prefix, fields in one_of_many_fields.items():\n assert cls.__fields__[fields[0]].field_info.extra[\"one_of_many\"] == prefix\n required = (\n cls.__fields__[fields[0]].field_info.extra[\"one_of_many_required\"]\n is True\n )\n found = False\n for field in fields:\n if field in values and values[field] is not None:\n if found is True:\n raise ValueError(\n \"Any of one field value is expected from \"\n f\"this list {fields}, but got multiple!\"\n )\n else:\n found = True\n if required is True and found is False:\n raise ValueError(f\"Expect any of field value from this list {fields}.\")\n\n return values\n\n\nclass CodeSystemFilter(backboneelement.BackboneElement):\n \"\"\"Disclaimer: Any field name ends with ``__ext`` doesn't part of\n Resource StructureDefinition, instead used to enable Extensibility feature\n for FHIR Primitive Data Types.\n\n Filter that can be used in a value set.\n A filter that can be used in a value set compose statement when selecting\n concepts using a filter.\n \"\"\"\n\n resource_type = Field(\"CodeSystemFilter\", const=True)\n\n code: fhirtypes.Code = Field(\n None,\n alias=\"code\",\n title=\"Code that identifies the filter\",\n description=\"The code that identifies this filter when it is used in the instance.\",\n # if property is element of this resource.\n element_property=True,\n element_required=True,\n )\n code__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_code\", title=\"Extension field for ``code``.\"\n )\n\n description: fhirtypes.String = Field(\n None,\n alias=\"description\",\n title=\"How or why the filter is used\",\n description=\"A description of how or why the filter is used.\",\n # if property is element of this resource.\n element_property=True,\n )\n description__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_description\", title=\"Extension field for ``description``.\"\n )\n\n operator: typing.List[fhirtypes.Code] = Field(\n None,\n alias=\"operator\",\n title=\"Operators that can be used with filter\",\n description=\"A list of operators that can be used with the filter.\",\n # if property is element of this resource.\n element_property=True,\n element_required=True,\n )\n operator__ext: typing.List[\n typing.Union[fhirtypes.FHIRPrimitiveExtensionType, None]\n ] = Field(None, alias=\"_operator\", title=\"Extension field for ``operator``.\")\n\n value: fhirtypes.String = Field(\n None,\n alias=\"value\",\n title=\"What to use for the value\",\n description=\"A description of what the value for the filter should be.\",\n # if property is element of this resource.\n element_property=True,\n element_required=True,\n )\n value__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_value\", title=\"Extension field for ``value``.\"\n )\n\n @classmethod\n def elements_sequence(cls):\n \"\"\"returning all elements names from\n ``CodeSystemFilter`` according specification,\n with preserving original sequence order.\n \"\"\"\n return [\n \"id\",\n \"extension\",\n \"modifierExtension\",\n \"code\",\n \"description\",\n \"operator\",\n \"value\",\n ]\n\n @root_validator(pre=True, allow_reuse=True)\n def validate_required_primitive_elements_1819(\n cls, values: typing.Dict[str, typing.Any]\n ) -> typing.Dict[str, typing.Any]:\n \"\"\"https://www.hl7.org/fhir/extensibility.html#Special-Case\n In some cases, implementers might find that they do not have appropriate data for\n an element with minimum cardinality = 1. In this case, the element must be present,\n but unless the resource or a profile on it has made the actual value of the primitive\n data type mandatory, it is possible to provide an extension that explains why\n the primitive value is not present.\n \"\"\"\n required_fields = [\n (\"code\", \"code__ext\"),\n (\"operator\", \"operator__ext\"),\n (\"value\", \"value__ext\"),\n ]\n _missing = object()\n\n def _fallback():\n return \"\"\n\n errors: typing.List[\"ErrorWrapper\"] = []\n for name, ext in required_fields:\n field = cls.__fields__[name]\n ext_field = cls.__fields__[ext]\n value = values.get(field.alias, _missing)\n if value not in (_missing, None):\n continue\n ext_value = values.get(ext_field.alias, _missing)\n missing_ext = True\n if ext_value not in (_missing, None):\n if isinstance(ext_value, dict):\n missing_ext = len(ext_value.get(\"extension\", [])) == 0\n elif (\n getattr(ext_value.__class__, \"get_resource_type\", _fallback)()\n == \"FHIRPrimitiveExtension\"\n ):\n if ext_value.extension and len(ext_value.extension) > 0:\n missing_ext = False\n else:\n validate_pass = True\n for validator in ext_field.type_.__get_validators__():\n try:\n ext_value = validator(v=ext_value)\n except ValidationError as exc:\n errors.append(ErrorWrapper(exc, loc=ext_field.alias))\n validate_pass = False\n if not validate_pass:\n continue\n if ext_value.extension and len(ext_value.extension) > 0:\n missing_ext = False\n if missing_ext:\n if value is _missing:\n errors.append(ErrorWrapper(MissingError(), loc=field.alias))\n else:\n errors.append(\n ErrorWrapper(NoneIsNotAllowedError(), loc=field.alias)\n )\n if len(errors) > 0:\n raise ValidationError(errors, cls) # type: ignore\n\n return values\n\n\nclass CodeSystemProperty(backboneelement.BackboneElement):\n \"\"\"Disclaimer: Any field name ends with ``__ext`` doesn't part of\n Resource StructureDefinition, instead used to enable Extensibility feature\n for FHIR Primitive Data Types.\n\n Additional information supplied about each concept.\n A property defines an additional slot through which additional information\n can be provided about a concept.\n \"\"\"\n\n resource_type = Field(\"CodeSystemProperty\", const=True)\n\n code: fhirtypes.Code = Field(\n None,\n alias=\"code\",\n title=(\n \"Identifies the property on the concepts, and when referred to in \"\n \"operations\"\n ),\n description=(\n \"A code that is used to identify the property. The code is used \"\n \"internally (in CodeSystem.concept.property.code) and also externally, \"\n \"such as in property filters.\"\n ),\n # if property is element of this resource.\n element_property=True,\n element_required=True,\n )\n code__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_code\", title=\"Extension field for ``code``.\"\n )\n\n description: fhirtypes.String = Field(\n None,\n alias=\"description\",\n title=\"Why the property is defined, and/or what it conveys\",\n description=(\n \"A description of the property- why it is defined, and how its value \"\n \"might be used.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n description__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_description\", title=\"Extension field for ``description``.\"\n )\n\n type: fhirtypes.Code = Field(\n None,\n alias=\"type\",\n title=\"code | Coding | string | integer | boolean | dateTime\",\n description=(\n 'The type of the property value. Properties of type \"code\" contain a '\n \"code defined by the code system (e.g. a reference to anotherr defined \"\n \"concept).\"\n ),\n # if property is element of this resource.\n element_property=True,\n element_required=True,\n # note: Enum values can be used in validation,\n # but use in your own responsibilities, read official FHIR documentation.\n enum_values=[\"code\", \"Coding\", \"string\", \"integer\", \"boolean\", \"dateTime\"],\n )\n type__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_type\", title=\"Extension field for ``type``.\"\n )\n\n uri: fhirtypes.Uri = Field(\n None,\n alias=\"uri\",\n title=\"Formal identifier for the property\",\n description=(\n \"Reference to the formal meaning of the property. One possible source \"\n \"of meaning is the [Concept Properties](codesystem-concept-\"\n \"properties.html) code system.\"\n ),\n # if property is element of this resource.\n element_property=True,\n )\n uri__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(\n None, alias=\"_uri\", title=\"Extension field for ``uri``.\"\n )\n\n @classmethod\n def elements_sequence(cls):\n \"\"\"returning all elements names from\n ``CodeSystemProperty`` according specification,\n with preserving original sequence order.\n \"\"\"\n return [\n \"id\",\n \"extension\",\n \"modifierExtension\",\n \"code\",\n \"uri\",\n \"description\",\n \"type\",\n ]\n\n @root_validator(pre=True, allow_reuse=True)\n def validate_required_primitive_elements_2081(\n cls, values: typing.Dict[str, typing.Any]\n ) -> typing.Dict[str, typing.Any]:\n \"\"\"https://www.hl7.org/fhir/extensibility.html#Special-Case\n In some cases, implementers might find that they do not have appropriate data for\n an element with minimum cardinality = 1. In this case, the element must be present,\n but unless the resource or a profile on it has made the actual value of the primitive\n data type mandatory, it is possible to provide an extension that explains why\n the primitive value is not present.\n \"\"\"\n required_fields = [(\"code\", \"code__ext\"), (\"type\", \"type__ext\")]\n _missing = object()\n\n def _fallback():\n return \"\"\n\n errors: typing.List[\"ErrorWrapper\"] = []\n for name, ext in required_fields:\n field = cls.__fields__[name]\n ext_field = cls.__fields__[ext]\n value = values.get(field.alias, _missing)\n if value not in (_missing, None):\n continue\n ext_value = values.get(ext_field.alias, _missing)\n missing_ext = True\n if ext_value not in (_missing, None):\n if isinstance(ext_value, dict):\n missing_ext = len(ext_value.get(\"extension\", [])) == 0\n elif (\n getattr(ext_value.__class__, \"get_resource_type\", _fallback)()\n == \"FHIRPrimitiveExtension\"\n ):\n if ext_value.extension and len(ext_value.extension) > 0:\n missing_ext = False\n else:\n validate_pass = True\n for validator in ext_field.type_.__get_validators__():\n try:\n ext_value = validator(v=ext_value)\n except ValidationError as exc:\n errors.append(ErrorWrapper(exc, loc=ext_field.alias))\n validate_pass = False\n if not validate_pass:\n continue\n if ext_value.extension and len(ext_value.extension) > 0:\n missing_ext = False\n if missing_ext:\n if value is _missing:\n errors.append(ErrorWrapper(MissingError(), loc=field.alias))\n else:\n errors.append(\n ErrorWrapper(NoneIsNotAllowedError(), loc=field.alias)\n )\n if len(errors) > 0:\n raise ValidationError(errors, cls) # type: ignore\n\n return values\n","sub_path":"fhir/resources/STU3/codesystem.py","file_name":"codesystem.py","file_ext":"py","file_size_in_byte":51796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"140316845","text":"# coding: utf-8\n\"\"\"\nBase para desarrollo de modulos externos.\nPara obtener el modulo/Funcion que se esta llamando:\n GetParams(\"module\")\n\nPara obtener las variables enviadas desde formulario/comando Rocketbot:\n var = GetParams(variable)\n Las \"variable\" se define en forms del archivo package.json\n\nPara modificar la variable de Rocketbot:\n SetVar(Variable_Rocketbot, \"dato\")\n\nPara obtener una variable de Rocketbot:\n var = GetVar(Variable_Rocketbot)\n\nPara obtener la Opcion seleccionada:\n opcion = GetParams(\"option\")\n\n\nPara instalar librerias se debe ingresar por terminal a la carpeta \"libs\"\n\n pip install -t .\n\n\"\"\"\nimport os\nimport sys\nbase_path = tmp_global_obj[\"basepath\"]\ncur_path = base_path + 'modules' + os.sep + 'voximplant_' + os.sep + 'libs' + os.sep\nsys.path.append(cur_path)\nfrom voximplant.apiclient import VoximplantAPI, VoximplantException\n\n\n\"\"\"\n Obtengo el modulo que fueron invocados\n\"\"\"\nmodule = GetParams(\"module\")\n\nif module == \"voximplant\":\n credentials = GetParams(\"credentials\")\n source = GetParams(\"source\")\n destination = GetParams(\"destination\")\n message = GetParams(\"message\")\n\n if \"+\" in source:\n source = source.split('+')[1]\n\n if \"+\" in destination:\n destination = destination.split('+')[1]\n\n try:\n api = VoximplantAPI(credentials)\n\n # Send the SMS with the \"Test message\" text from the phone number 447443332211 to the phone number 447443332212\n\n SOURCE = source\n DESTINATION = destination\n SMS_BODY = message\n\n try:\n res = api.send_sms_message(SOURCE, DESTINATION, SMS_BODY)\n print(res)\n except VoximplantException as e:\n print(\"Error: {}\".format(e.message))\n\n except Exception as e:\n PrintException()\n raise e\n\n\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"557428896","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/9/8 上午12:11\n# @Author : ShaHeTop-Almighty-ares\n# @Email : yang6333yyx@126.com\n# @File : service.py\n# @Software: PyCharm\n\nfrom app.cms.article.models import Article\nfrom validators.publicValidator import is_valid\n\n\nclass ArticleService(object):\n\n @staticmethod\n def add_article(data):\n if is_valid(data):\n return Article.get_json(data)\n","sub_path":"Flask_Projects/HuntingBall/app/cms/article/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"650413275","text":"class CQueue:\n MAXSIZE = 10 # class member\n\n def __init__(self): # 생성자\n self.container = [None for _ in range(CQueue.MAXSIZE)] # class member 쓰는법\n self.__head = 0\n self.__tail = 0\n\n def is_empty(self):\n if self.__head == self.__tail:\n return True\n else:\n return False\n\n def is_full(self):\n next = self.__step_forward(self.__tail)\n if next == self.__head:\n return True\n return False\n\n def enqueue(self, data):\n if self.is_full():\n raise Exception(\"The queue is full\")\n self.container[self.__tail] = data\n # tail은 마지막 데이터의 다음을 가리킨다.\n self.__tail = self.__step_forward(self.__tail)\n\n def dequeue(self):\n if self.is_empty():\n raise Exception(\"The queue is empty\")\n ret = self.container[self.__head]\n self.__head = self.__step_forward(self.__head)\n return ret\n\n def peek(self):\n if self.is_empty():\n raise Exception(\"The queue is empty\")\n return self.container[self.__head]\n\n # 편의 함수\n def __step_forward(self, x):\n x += 1\n if x >= CQueue.MAXSIZE:\n x = 0\n return x\n\n\nif __name__ == \"__main__\":\n cq = CQueue()\n\n # cq.enqueue(1)\n # cq.enqueue(2)\n # cq.enqueue(3)\n #\n # for i in range(3):\n # print(cq.dequeue())\n\n for i in range(8):\n cq.enqueue(i)\n\n for i in range(5):\n print(cq.dequeue(), end=\" \")\n\n for i in range(8, 14):\n cq.enqueue(i)\n\n while not cq.is_empty():\n print(cq.dequeue(), end=\" \")\n\n print()\n for i in range(10):\n print(cq.container[i], end=\" \")\n","sub_path":"Data_structure/circular_queue.py","file_name":"circular_queue.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"216251363","text":"# -*- coding: utf-8 -*-\n\nimport os\nfrom celery import Celery\nfrom enferno.settings import ProdConfig, DevConfig\n\ncelery = Celery(__name__)\n\nif os.environ.get(\"FLASK_DEBUG\") == '0':\n cfg = ProdConfig\nelse:\n cfg = DevConfig\n\ncelery = Celery('tasks', broker=cfg.CELERY_BROKER_URL)\n#remove deprecated warning\ncelery.conf.update({'CELERY_ACCEPT_CONTENT':['pickle', 'json', 'msgpack', 'yaml']})\ncelery.conf.update({'CELERY_RESULT_BACKEND':cfg.CELERY_RESULT_BACKEND})\ncelery.conf.add_defaults(cfg)\n\nclass ContextTask(celery.Task):\n abstract = True\n\n def __call__(self, *args, **kwargs):\n from enferno.app import create_app\n with create_app(cfg).app_context():\n return super(ContextTask, self).__call__(*args, **kwargs)\n\ncelery.Task = ContextTask\n\n\n@celery.task\ndef task():\n pass\n\n","sub_path":"enferno/tasks/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"636483756","text":"import unittest\nimport sys\n\nfrom src.grammar_tester.psparse import strip_token, parse_tokens, parse_links, parse_postscript, get_link_set, \\\n prepare_tokens, skip_command_response, skip_linkage_header, PS_TIMEOUT_EXPIRED, PS_PANIC_DETECTED\nfrom src.grammar_tester.optconst import *\nfrom src.grammar_tester.parsestat import parse_metrics\n\n\ngutenberg_children_bug = \\\n\"\"\"\n[(LEFT-WALL)(\")(project.v)(gutenberg[?].n)('s.p)(alice[?].n)('s.p)(adventures.n)([in])(wonderland.n)\n(,)(by)(lewis[!])(carroll[?].n)(\")(()(edited.v-d)())]\n[[0 2 1 (Wi)][0 1 0 (ZZZ)][2 9 2 (Os)][6 9 1 (Ds**x)][5 6 0 (YS)][4 5 0 (D*u)][3 4 0 (YS)]\n[7 9 0 (AN)][9 11 1 (MXsx)][10 11 0 (Xd)][11 17 2 (Xc)][11 13 1 (Jp)][12 13 0 (AN)][13 16 1 (MXsp)]\n[16 17 0 (Xca)][13 14 0 (ZZZ)][15 16 0 (Xd)]]\n[0]\n\"\"\"\ngutenberg_children_bug2 = \"[ebook # @number@ ][(LEFT-WALL)(release.n)(date.n)(:.j)(@date@[?].n)([)(ebook[?].a)([#])\" \\\n \"(@number@[?].n)(])][[0 3 2 (Xx)][0 2 1 (Wa)][1 2 0 (AN)][3 4 0 (Jp)][4 8 2 (MXs)]\" \\\n \"[5 8 1 (Xd)][6 8 0 (A)][8 9 0 (Xc)]][0]\"\n\n\n# cleaned_Gutenberg_Children bug list\ncgch_bug_001 = \\\n\"\"\"\n[ illustration : \" i tell you what , you stay right here ! \"[(LEFT-WALL)([[])(illustration.n-u)(:.v)(\")([i])(tell.v)(you)(what)(,)(you)(stay.v)(right.a)(here)(!)(\")][[0 14 4 (Xp)][0 9 3 (Xx)][0 6 2 (WV)][0 2 0 (Wd)][2 3 0 (Ss)][3 6 1 (I*v)][3 4 0 (ZZZ)][6 8 1 (QI)][6 7 0 (Ox)][9 11 1 (WV)][9 10 0 (Wd)][10 11 0 (Sp)][11 12 0 (Pa)][12 13 0 (MVp)][14 15 0 (ZZZ)]][0]\n\"\"\"\n# most people start at our web site which has the main pg search facility:\nalice_bug_001 = \\\n\"\"\"\n[(most)(people)(start)(at)([our])(web)(site)([which])([has])([the])\n([main])([pg])([search])([facility:])]\n[[0 1 0 (C26C33)][1 2 0 (C33C54)][2 3 0 (C54C22)][3 6 1 (C22C17)][5 6 0 (C23C17)]]\n[0]\n\"\"\"\n\n# its business office is located at @number@ north @number@ west, salt lake city, ut @number@ , ( @number@ ) @number@ - @number@ , email business@pglaf.org.\nalice_bug_002 = \\\n\"\"\"\n[(LEFT-WALL)(its)(business.n-u)(office.n)(is.v)(located.v-d)(at)(@number@[?].n)(north.a)(@number@[?].a)\n(west.a)(,)(salt.n-u)(lake.n)(city.n)(,)(ut[?].v)(@number@[?].a)(,)([(])\n(@number@[?].a)())(@number@[?].a)(-.r)(@number@[?].a)(,)(email.s)(business@pglaf.org[?].n)(.)]\n[[0 28 6 (Xp)][0 16 5 (WV)][0 11 4 (Xx)][0 5 3 (WV)][0 3 2 (Wd)][1 3 1 (Ds**x)][2 3 0 (AN)]\n[3 4 0 (Ss*s)][4 5 0 (Pv)][5 9 1 (Pa)][5 6 0 (MVp)][6 7 0 (Jp)][7 8 0 (Mp)][9 10 0 (MVp)]\n[11 15 3 (Xx)][15 16 0 (Wa)][11 14 2 (Wa)][12 14 1 (AN)][13 14 0 (AN)][16 27 5 (Os)][26 27 0 (AN)]\n[17 26 4 (A)][17 18 0 (Xc)][20 26 3 (A)][20 21 0 (Xc)][22 26 2 (A)][22 23 0 (Xc)][24 26 1 (A)]\n[24 25 0 (Xc)]]\n[0]\n\"\"\"\n\nalice_bug_003 = \\\n\"\"\"\n[(LEFT-WALL)([(])(alice[?].n)(had.v-d)(no.misc-d)(idea.n)(what)(latitude.n-u)(was.v-d)(,)\n(or.ij)(longitude.n-u)(either.r)(,)([but])(thought.q-d)(they)(were.v-d)(nice.a)(grand.a)\n(words.n)(to.r)(say.v)(.)([)])]\n[[0 23 5 (Xp)][0 10 3 (Xx)][0 3 1 (WV)][0 2 0 (Wd)][2 3 0 (Ss)][3 5 1 (Os)][4 5 0 (Ds**x)]\n[5 6 0 (MXs)][6 9 2 (Xca)][9 10 0 (Xd)][6 8 1 (Bsdt)][6 7 0 (Rn)][7 8 0 (Ss)][10 17 4 (WV)]\n[10 11 0 (Wdc)][11 17 3 (Ss)][12 17 2 (E)][15 17 1 (Eq)][13 15 0 (Xd)][15 16 0 (SIpj)][17 20 2 (Opt)]\n[18 20 1 (A)][19 20 0 (A)][20 22 1 (Bpw)][20 21 0 (R)][21 22 0 (I)]]\n[0]\n\"\"\"\n\nalice_bug_004 = \\\n\"\"\"\n[(LEFT-WALL)(posting.g)(date.n)(:.j)(@date@[?].a)([)(ebook[?].a)([#])(@number@[?].n)(])\n(release.n)(date.n)(:.j)([@date@])(last.ord)(updated.v-d)(:.v)(@date@[?].n)]\n[[0 3 2 (Xx)][0 2 1 (Wa)][1 2 0 (AN)][3 12 5 (Xx)][3 11 4 (Wa)][10 11 0 (AN)][4 10 3 (A)]\n[4 8 2 (MX*ta)][5 8 1 (Xd)][6 8 0 (A)][8 9 0 (Xc)][12 16 2 (WV)][12 14 0 (Wd)][14 16 1 (Ss*o)]\n[14 15 0 (Mv)][16 17 0 (Ost)]]\n[0]\n\"\"\"\n\ngutenberg_children_bug_002 = \\\n\"\"\"\n[(LEFT-WALL)([a])(millennium.n-u)(fulcrum.n)(edition.n)([(])([c])([)])(1991[!])([by])\n(duncan[?].n)(research.n-u)]\n[[0 11 5 (Wa)][2 11 4 (AN)][3 11 3 (AN)][4 11 2 (AN)][8 11 1 (AN)][10 11 0 (AN)]]\n[0]\n\"\"\"\n\ngutenberg_children_bug_002t = \"[(LEFT-WALL)([a])(millennium.n-u)(fulcrum.n)(edition.n)([(])([c])([)])(1991[!])([by])\" \\\n \"(duncan[?].n)(research.n-u)]\"\n\ngutenberg_children_bug_002tr = [r\"###LEFT-WALL###\", \"[a]\", \"millennium\", \"fulcrum\", \"edition\", \"[(]\", \"[c]\", \"[)]\",\n \"1991\", \"[by]\", \"duncan\", \"research\"]\n\ngutenberg_children_bug_002l = \"[[0 11 5 (Wa)][2 11 4 (AN)][3 11 3 (AN)][4 11 2 (AN)][8 11 1 (AN)][10 11 0 (AN)]][0]\"\n\ngutenberg_children_bug_002lr = [(0, 11), (2, 11), (3, 11), (4, 11), (8, 11), (10, 11)]\n\nexplosion_bug = \\\n\"\"\"\nconclusions : icp-sf-ms is a reliable method of blood analysis for cd , mn and pb even for the evaluation on an individual basis.\nby comparing eyebrow shape and position in both young and mature women , this study provides objective data with which to plan forehead rejuvenating procedures.\nthe odds of being overweight in adulthood was @number@ times greater ( @percent@ ci : @date@ @number@ ) in overweight compared with healthy weight youth.\nholocaust survivors did not differ in the level of resilience from comparisons ( mean : @number@ ± @number@ vs. @number@ ± @number@ respectively ) .\n[(LEFT-WALL)(holocaust.n)(survivors.n)(did.v-d)(not.e)(differ.v)(in.r)(the)(level.n)(of)\n(resilience.n-u)(from)(comparisons.n)(()(mean.a)([:])(@number@[?].n)(±[?].n)(@number@[?].n)(vs.)\n(@number@[?].n)(±[?].n)(@number@[?].n)([respectively])())(.)]\n[[0 25 4 (Xp)][0 5 2 (WV)][0 2 1 (Wd)][1 2 0 (AN)][2 3 0 (Sp)][3 5 1 (I*d)][3 4 0 (N)]\n[4 5 0 (En)][5 11 2 (MVp)][5 6 0 (MVp)][6 8 1 (Js)][7 8 0 (Ds**c)][8 9 0 (Mf)][9 10 0 (Jp)]\n[10 11 0 (Mp)][11 12 0 (Jp)][12 18 3 (MXp)][13 18 2 (Xd)][14 18 1 (A)][17 18 0 (AN)][16 17 0 (AN)]\n[18 24 3 (Xc)][18 19 0 (Mp)][19 22 2 (Jp)][20 22 1 (AN)][21 22 0 (AN)]]\n[0]\n\"\"\"\n\ntimeout_linkage = \\\n\"\"\"\nNo complete linkages found.\nTimer is expired!\nEntering \"panic\" mode...\nFound 576744359 linkages (100 of 100 random linkages had no P.P. violations) at null count 4\n\tLinkage 1, cost vector = (UNUSED=4 DIS= 0.00 LEN=19)\n[(but)([I])(have)(passed)(my)(royal)(word)([,])(and)([I])\n(cannot)(break)(it)([,])(so)(there)(is)(no)(help)(for)\n(you)(..y)(')]\n[[0 5 1 (FK)][0 2 0 (FF)][2 3 0 (FC)][3 4 0 (CJ)][5 10 1 (KG)][5 6 0 (KH)][8 10 0 (BG)]\n[10 12 1 (GE)][11 12 0 (CE)][12 14 0 (EF)][14 20 2 (FF)][18 20 1 (CF)][17 18 0 (JC)][16 17 0 (LJ)]\n[15 16 0 (EL)][18 19 0 (CB)][20 22 1 (FC)][21 22 0 (CC)]]\n[0]\n\"\"\"\n\n\nclass TestPSParse(unittest.TestCase):\n\n post_all_walls = \"[(LEFT-WALL)(Dad[!])(was.v-d)(not.e)(a)(parent.n)(before)(.)(RIGHT-WALL)]\" \\\n \"[[0 7 2 (Xp)][0 1 0 (Wd)][1 2 0 (Ss*s)][2 5 1 (Osm)][2 3 0 (EBm)]\" \\\n \"[4 5 0 (Ds**c)][5 6 0 (Mp)][7 8 0 (RW)]][0]\"\n post_no_walls = \"[(eagle)(has)(wing)(.)][[0 2 1 (C04C01)][1 2 0 (C01C01)][2 3 0 (C01C05)]][0]\"\n post_no_links = \"[([herring])([isa])([fish])([.])][][0]\"\n\n link_str = \"[0 7 2 (Xp)][0 1 0 (Wd)][1 2 0 (Ss*s)][2 5 1 (Osm)][2 3 0 (EBm)][4 5 0 (Ds**c)][5 6 0 (Mp)][7 8 0 (RW)]\"\n\n tokens_all_walls = \"(LEFT-WALL)(Dad[!])(was.v-d)(not.e)(a)(parent.n)(before)(.)(RIGHT-WALL)\"\n tokens_no_walls = \"(eagle)(has)(wing)(.)\"\n tokens_no_walls_no_period = \"(eagle)(has)(wing)\"\n\n def test_new_tokenizer(self):\n\n def find_end_of_token(text, pos: int) -> int:\n\n # Assume the open brace is already skipped\n braces = 1\n brackets = 0\n\n text_len = len(text)\n\n while pos < text_len:\n\n current = text[pos]\n\n if current == r\"(\":\n # If not \"[(]\"\n if not brackets:\n braces += 1\n\n elif current == r\")\":\n # if not \"[)]\"\n if not brackets:\n braces -= 1\n\n if not braces:\n return pos\n\n elif current == r\"[\":\n brackets += 1\n\n elif current == r\"]\":\n brackets -= 1\n\n pos += 1\n\n return pos\n\n def tokenizer(text: str) -> list:\n tokens = []\n pos = 0\n old = -1\n\n while pos < len(text):\n if pos == old:\n print(\"Infinite loop detected...\")\n break\n\n # To avoid infinite loop in case of errors in postscript string\n old = pos\n\n if text[pos] == r\"(\":\n pos += 1\n\n end = find_end_of_token(text, pos)\n\n if end > pos:\n tokens.append(text[pos:end])\n\n pos = end + 1\n\n return tokens\n\n self.assertEqual([\"eagle\", \"has\", \"wing\", \".\"], tokenizer(\"(eagle)(has)(wing)(.)\"))\n\n self.assertEqual([\"LEFT-WALL\", \"Dad[!]\", \"was.v-d\", \"not.e\", \"a\", \"parent.n\", \"before\", \".\", \"RIGHT-WALL\"],\n tokenizer(\"(LEFT-WALL)(Dad[!])(was.v-d)(not.e)(a)(parent.n)(before)(.)(RIGHT-WALL)\"))\n\n post = \"(LEFT-WALL)([(])(alice[?].n)(had.v-d)(no.misc-d)(idea.n)(what)(latitude.n-u)(was.v-d)(,)(or.ij)\" \\\n \"(longitude.n-u)(either.r)(,)([but])(thought.q-d)(they)(were.v-d)(nice.a)(grand.a)(words.n)(to.r)(say.v)\" \\\n \"(.)([)])\"\n ref = [\"LEFT-WALL\", \"[(]\", \"alice[?].n\", \"had.v-d\", \"no.misc-d\", \"idea.n\", \"what\", \"latitude.n-u\", \"was.v-d\",\n \",\", \"or.ij\", \"longitude.n-u\", \"either.r\", \",\", \"[but]\", \"thought.q-d\", \"they\", \"were.v-d\", \"nice.a\",\n \"grand.a\", \"words.n\", \"to.r\", \"say.v\", \".\", \"[)]\"]\n\n # print(tokenizer(post))\n\n self.assertEqual(ref, tokenizer(post))\n\n @staticmethod\n def cmp_lists(list1: [], list2: []) -> bool:\n if list1 is None or list2 is None or len(list1) != len(list2):\n return False\n\n for i in range(0, len(list1)):\n if list1[i] != list2[i]:\n return False\n\n return True\n\n def test_strip_token(self):\n \"\"\" Test for stripping Link Grammar suffixes off tokens \"\"\"\n self.assertEqual(strip_token(\"strange[!]\"), \"strange\")\n self.assertEqual(strip_token(\"strange.a\"), \"strange\")\n self.assertEqual(strip_token(\"[strange]\"), \"[strange]\")\n\n # @unittest.skip\n def test_parse_tokens_alice_003(self):\n \"\"\" Test for proper parsing of '[(]' revealed by Alice in Wonderland corpus \"\"\"\n options = BIT_STRIP | BIT_NO_LWALL | BIT_NO_PERIOD\n\n # sent = \"(alice had no idea what latitude was, or longitude either, but thought they were nice grand words to say.)\"\n post = \"(LEFT-WALL)([(])(alice[?].n)(had.v-d)(no.misc-d)(idea.n)(what)(latitude.n-u)(was.v-d)(,)(or.ij)\" \\\n \"(longitude.n-u)(either.r)(,)([but])(thought.q-d)(they)(were.v-d)(nice.a)(grand.a)(words.n)(to.r)(say.v)\" \\\n \"(.)([)])\"\n ref = \\\n [\"###LEFT-WALL###\", \"[(]\", \"alice\", \"had\", \"no\", \"idea\", \"what\", \"latitude\", \"was\", \",\", \"or\", \"longitude\",\n \"either\", \",\", \"[but]\", \"thought\", \"they\", \"were\", \"nice\", \"grand\", \"words\", \"to\", \"say\", \".\", \"[)]\"]\n\n tokens = parse_tokens(post, options)[0]\n self.assertEqual(ref, tokens)\n\n # @unittest.skip\n def test_parse_tokens_alice_004(self):\n \"\"\" Test for proper parsing of square brackets revealed by Alice in Wonderland corpus \"\"\"\n options = BIT_STRIP | BIT_NO_LWALL | BIT_NO_PERIOD\n\n post = \"(LEFT-WALL)(posting.g)(date.n)(:.j)(@date@[?].a)([)(ebook[?].a)([#])(@number@[?].n)(])(release.n)\" \\\n \"(date.n)(:.j)([@date@])(last.ord)(updated.v-d)(:.v)(@date@[?].n)\"\n\n ref = [\"###LEFT-WALL###\", \"posting\", \"date\", \":\", \"@date@\", \"[\", \"ebook\", \"[#]\", \"@number@\", \"]\", \"release\",\n \"date\", \":\", \"[@date@]\", \"last\", \"updated\", \":\", \"@date@\"]\n\n tokens = parse_tokens(post, options)[0]\n self.assertEqual(ref, tokens)\n\n # @unittest.skip\n def test_parse_tokens(self):\n \"\"\" test_parse_tokens \"\"\"\n\n options = 0\n\n # No RIGHT-WALL, no CAPS\n options |= BIT_STRIP\n # tokens = parse_tokens(self.tokens_all_walls, options)\n # self.assertTrue(self.cmp_lists(tokens, ['###LEFT-WALL###', 'dad', 'was', 'not', 'a',\n # 'parent', 'before', '.']))\n\n # Tokens without walls\n tokens = parse_tokens(self.tokens_no_walls, options)[0]\n self.assertTrue(self.cmp_lists(tokens, ['###LEFT-WALL###', 'eagle', 'has', 'wing', '.']))\n\n # RIGHT-WALL and CAPS, no STRIP\n options |= (BIT_RWALL | BIT_CAPS)\n options &= ~BIT_STRIP\n tokens = parse_tokens(self.tokens_all_walls, options)[0]\n self.assertTrue(self.cmp_lists(tokens, ['###LEFT-WALL###', 'Dad[!]', 'was.v-d', 'not.e', 'a',\n 'parent.n', 'before', '.', '###RIGHT-WALL###']))\n\n # Tokens without walls\n tokens = parse_tokens(self.tokens_no_walls, options)[0]\n # print(tokens, file=sys.stdout)\n self.assertTrue(self.cmp_lists(tokens, ['###LEFT-WALL###', 'eagle', 'has', 'wing', '.']))\n\n @unittest.skip\n def test_parse_tokens_no_left_wall(self):\n # NO_LWALL and CAPS, no STRIP\n options = 0\n options |= BIT_CAPS | BIT_NO_LWALL\n # options |= (BIT_NO_LWALL | BIT_CAPS)\n # options &= (~(BIT_STRIP | BIT_RWALL))\n tokens = parse_tokens(self.tokens_all_walls, options)[0]\n\n # print(tokens)\n\n self.assertTrue(self.cmp_lists(tokens, ['Dad[!]', 'was.v-d', 'not.e', 'a',\n 'parent.n', 'before', '.']))\n\n @unittest.skip\n def test_parse_tokens_no_walls_no_period(self):\n options = 0\n options |= BIT_STRIP | BIT_NO_PERIOD | BIT_NO_LWALL\n tokens = parse_tokens(self.tokens_all_walls, options)[0]\n\n # print(tokens)\n\n self.assertTrue(self.cmp_lists(tokens, ['dad', 'was', 'not', 'a', 'parent', 'before']))\n\n @unittest.skip\n def test_parse_tokens_rwall_no_period(self):\n options = 0\n options |= BIT_STRIP | BIT_NO_PERIOD | BIT_RWALL\n tokens = parse_tokens(self.tokens_all_walls, options)[0]\n\n # print(tokens)\n\n self.assertTrue(self.cmp_lists(tokens, ['###LEFT-WALL###', 'dad', 'was', 'not', 'a', 'parent', 'before',\n '###RIGHT-WALL###']))\n\n @unittest.skip\n def test_parse_tokens_no_period(self):\n options = 0\n options |= BIT_STRIP | BIT_NO_PERIOD | BIT_RWALL\n tokens = parse_tokens(self.tokens_no_walls, options)[0]\n\n # print(tokens)\n\n self.assertTrue(self.cmp_lists(tokens, ['###LEFT-WALL###', 'eagle', 'has', 'wing']))\n\n # @unittest.skip\n def test_parse_no_period_if_no_period(self):\n \"\"\" Test for parsing sentence with no walls and period \"\"\"\n options = 0\n options |= BIT_STRIP | BIT_NO_PERIOD | BIT_RWALL\n tokens = parse_tokens(self.tokens_no_walls_no_period, options)[0]\n\n self.assertTrue(self.cmp_lists(tokens, ['###LEFT-WALL###', 'eagle', 'has', 'wing']))\n\n # @unittest.skip\n def test_parse_links(self):\n \"\"\" Test for parsing links out when LW and period are presented \"\"\"\n links = parse_links(self.link_str, ['###LEFT-WALL###', 'dad', 'was', 'not', 'a', 'parent', 'before', '.'], 0)\n\n # [0 7 2 (Xp)][0 1 0 (Wd)][1 2 0 (Ss*s)][2 5 1 (Osm)][2 3 0 (EBm)][4 5 0 (Ds**c)][5 6 0 (Mp)][7 8 0 (RW)]\n self.assertTrue(self.cmp_lists(links, [ (0, 7),\n (0, 1),\n (1, 2),\n (2, 5),\n (2, 3),\n (4, 5),\n (5, 6) ]))\n\n # @unittest.skip\n def test_parse_postscript_all_walls(self):\n \"\"\" Test for parsing postscript with both walls in \"\"\"\n options = 0\n options |= (BIT_RWALL | BIT_CAPS)\n options &= ~BIT_STRIP\n tokens, links = parse_postscript(self.post_all_walls, options)\n pm = parse_metrics(tokens)\n self.assertEqual(1.0, pm.completely_parsed_ratio)\n self.assertEqual(0.0, pm.completely_unparsed_ratio)\n self.assertEqual(1.0, pm.average_parsed_ratio)\n\n # @unittest.skip\n def test_parse_postscript_no_walls(self):\n \"\"\" Test for parsing_postscript with no walls in \"\"\"\n options = 0\n options |= (BIT_RWALL | BIT_CAPS)\n options &= ~BIT_STRIP\n\n tokens, links = parse_postscript(self.post_no_walls, options)\n pm = parse_metrics(tokens)\n self.assertEqual(1.0, pm.completely_parsed_ratio)\n self.assertEqual(0.0, pm.completely_unparsed_ratio)\n self.assertEqual(1.0, pm.average_parsed_ratio)\n\n # @unittest.skip\n def test_parse_postscript_no_links(self):\n \"\"\" Test for parsing postscript with no links \"\"\"\n options = 0\n options |= (BIT_RWALL | BIT_CAPS)\n options &= ~BIT_STRIP\n\n tokens, links = parse_postscript(self.post_no_links, options)\n self.assertEqual(0, len(links))\n\n # @unittest.skip\n def test_parse_postscript_gutenchildren_bug(self):\n \"\"\" Test for number of tokens (bug from Gutenberg Children corpus) \"\"\"\n options = 0\n # options |= (BIT_RWALL | BIT_CAPS)\n # options &= ~BIT_STRIP\n\n tokens, links = parse_postscript(gutenberg_children_bug, options)\n\n self.assertEqual(18, len(tokens))\n\n @unittest.skip\n def test_parse_gutenchildren_bug_002(self):\n \"\"\" Test for number of tokens (bug from Gutenberg Children corpus) \"\"\"\n options = BIT_NO_LWALL | BIT_NO_PERIOD | BIT_STRIP\n\n tokens = parse_tokens(gutenberg_children_bug_002t, options)[0]\n\n self.assertEqual(tokens, gutenberg_children_bug_002tr)\n\n @unittest.skip\n def test_parse_postscript_gutenchildren_bug_002(self):\n\n options = BIT_NO_LWALL | BIT_NO_PERIOD | BIT_STRIP\n\n tokens, links = parse_postscript(gutenberg_children_bug_002, options)\n\n print(tokens)\n\n self.assertEqual(12, len(tokens))\n self.assertEqual(6, len(links))\n\n # pm = parse_metrics(tokens)\n #\n # self.assertEqual(0.0, pm.completely_parsed_ratio)\n # self.assertEqual(0.0, pm.completely_unparsed_ratio)\n # self.assertEqual(0.94117647, float(pm.average_parsed_ratio))\n\n # self.assertEqual(16.0/17.0, pm.average_parsed_ratio)\n\n # @unittest.skip\n def test_parse_postscript_alice_bug_001(self):\n \"\"\" test_parse_postscript \"\"\"\n # print(__doc__, sys.stderr)\n\n options = 0\n # options |= (BIT_RWALL | BIT_CAPS)\n options &= ~BIT_STRIP\n\n tokens, links = parse_postscript(alice_bug_001, options)\n\n self.assertEqual(15, len(tokens))\n\n for link in links:\n self.assertTrue(link[0]<15 and link[1]<15, str(link))\n\n # self.assertEqual([\"most\", \"people\", \"start\", \"at\", \"our\", \"web\", \"site\", \"which\", \"has\", \"the\", \"main\", \"pg\",\n # \"search\", \"facility:\"], tokens)\n\n def test_parse_postscript_alice_bug_002(self):\n \"\"\" Gutenberg Children bug test \"\"\"\n options = 0\n # options |= (BIT_RWALL | BIT_CAPS)\n options &= ~BIT_STRIP\n\n tokens, links = parse_postscript(alice_bug_002, options)\n\n self.assertEqual(29, len(tokens), tokens)\n\n\n def test_get_link_set(self):\n \"\"\" Test for link extraction according to set options \"\"\"\n # post_all_walls = \"[(LEFT-WALL)(Dad[!])(was.v-d)(not.e)(a)(parent.n)(before)(.)(RIGHT-WALL)]\" \\\n # \"[[0 7 2 (Xp)][0 1 0 (Wd)][1 2 0 (Ss*s)][2 5 1 (Osm)][2 3 0 (EBm)]\" \\\n # \"[4 5 0 (Ds**c)][5 6 0 (Mp)][7 8 0 (RW)]][0]\"\n expected_set = {(1, 2), (2, 5), (2, 3), (4, 5), (5, 6)}\n options = BIT_NO_LWALL | BIT_NO_PERIOD | BIT_STRIP | BIT_PARSE_QUALITY\n tokens, links = parse_postscript(self.post_all_walls, options)\n result_set = get_link_set(tokens, links, options)\n\n self.assertTrue(result_set == expected_set)\n\n def test_prepare_tokens_both_walls_period_no_options(self):\n \"\"\" Test for filtering token list according to set options \"\"\"\n token_list = ['###LEFT-WALL###', 'dad', 'was', 'not', 'a', 'parent', 'before', '.', '###RIGHT-WALL###']\n token_list_no_walls = ['dad', 'was', 'not', 'a', 'parent', 'before', '.']\n token_list_no_period = ['###LEFT-WALL###', 'dad', 'was', 'not', 'a', 'parent', 'before', '###RIGHT-WALL###']\n token_list_words_only = ['dad', 'was', 'not', 'a', 'parent', 'before']\n\n # Should take no action\n options = 0 | BIT_RWALL\n result_list = prepare_tokens(token_list, options)\n self.assertEqual(token_list, result_list, \"Lists are not the same!!!\")\n\n # Should return a list with no walls only word-tokens and period\n options = 0 | BIT_NO_LWALL\n result_list = prepare_tokens(token_list, options)\n self.assertEqual(token_list_no_walls, result_list, \"Lists are not the same!!!\")\n\n # Should return a list with walls, word-tokens and period\n options = 0 | BIT_RWALL | BIT_NO_PERIOD\n result_list = prepare_tokens(token_list, options)\n self.assertEqual(token_list_no_period, result_list, \"Lists are not the same!!!\")\n\n # Should return a list with no walls and no period\n options = 0 | BIT_NO_LWALL | BIT_NO_PERIOD\n result_list = prepare_tokens(token_list, options)\n self.assertEqual(token_list_words_only, result_list, \"Lists are not the same!!!\")\n\n tokens_period_in_brackets = [\"dad\", \"[has]\", \"[a]\", \"[telescope]\", \"[.]\"]\n options = 0 | BIT_NO_LWALL | BIT_NO_PERIOD\n result_list = prepare_tokens(tokens_period_in_brackets, options)\n self.assertEqual([\"dad\", \"[has]\", \"[a]\", \"[telescope]\"], result_list, \"Lists are not the same!!!\")\n\n tokens_only_period_unboxed = [\"[dad]\", \"has\", \"[binoculars]\", \".\"]\n options = 0 | BIT_NO_LWALL | BIT_NO_PERIOD\n result_list = prepare_tokens(tokens_only_period_unboxed, options)\n self.assertEqual([\"[dad]\", \"has\", \"[binoculars]\"], result_list, \"Lists are not the same!!!\")\n\n seven_dots = ['###LEFT-WALL###', '[.]', '[.]', '[.]', '[.]', '[.]', '[.]', '[.]', '###RIGHT-WALL###']\n options = 0\n result_list = prepare_tokens(seven_dots, options)\n self.assertEqual(['###LEFT-WALL###', '[.]', '[.]', '[.]', '[.]', '[.]', '[.]', '[.]'], result_list, \"Lists are not the same!!!\")\n\n options = 0 | BIT_NO_LWALL | BIT_NO_PERIOD\n result_list = prepare_tokens(seven_dots, options)\n self.assertEqual(['[.]', '[.]', '[.]', '[.]', '[.]', '[.]'], result_list, \"Lists are not the same!!!\")\n\n def test_skip_command_response(self):\n with open(\"tests/test-data/raw/debug-msg.txt\") as file:\n text = file.read()\n\n pos = skip_command_response(text)\n\n # print(text[pos:], sys.stderr)\n self.assertEqual(175, pos)\n\n def test_skip_linkage_header(self):\n pos, err = skip_linkage_header(timeout_linkage)\n print(timeout_linkage[pos:])\n self.assertEqual(219, pos)\n self.assertEqual(PS_PANIC_DETECTED|PS_TIMEOUT_EXPIRED, err)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_psparse.py","file_name":"test_psparse.py","file_ext":"py","file_size_in_byte":23241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"47587926","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nl=[]\nfor i in range(2000,3201):\n if(i%7==0 and i%5!=0):\n l.append(str(i))\nprint(','.join(l))\n \n \n\n\n# In[ ]:\n\n\n\n\n","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"411470719","text":"from acsploit.options import Options\n\n\noptions = Options()\noptions.add_option('n_inputs', 10, 'Number of nodes in tree (to insert)')\n# Worst case for node insertion in a R-B tree.\n\nDESCRIPTION = 'Produces a worst-case set of inputs for insertion in a Red-Black Tree' \\\n '\\n\\n ' \\\n 'Sorted insertions maximizes balancing operations in a Red-Black tree.'\n\n\ndef run(generator, output):\n ret = sorted_list(generator, options['n_inputs'])\n output.output(ret)\n\n\ndef sorted_list(generator, n_inputs):\n output = [generator.get_max_value()]\n for i in range(1, n_inputs):\n output.append(generator.get_less_than(output[i - 1]))\n return output\n","sub_path":"acsploit/exploits/tree/red_black_tree.py","file_name":"red_black_tree.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"344437644","text":"import pyodbc\nimport re\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport plotly.graph_objs as go\nimport plotly.plotly as py\nimport matplotlib.mlab as mlab\n\ncnxn = pyodbc.connect(\"Driver={SQL Server Native Client 11.0};\"\n \"Server=DESKTOP-PL894JS\\SQLEXPRESS;\"\n \"Database=Emails;\"\n \"Trusted_Connection=yes;\")\n\ncursor = cnxn.cursor()\nEmails = cursor.execute('SELECT [From] FROM TblSubjectAnalysisInvoices')\n\nFrom = []\nx = 0\nfor i in cursor.fetchall():\n From.append(i[0])\n\nUniqueEmails = set(From)\nSortedUniqueListX = list(UniqueEmails)\n\nSortedUniqueListX, yaxis = np.unique(From, return_counts=True)\n\nyaxis, SortedUniqueListX = (list(t) for t in zip(*sorted(zip(yaxis, SortedUniqueListX), reverse=False)))\nprint(SortedUniqueListX[:20])\nprint(yaxis[:20])\n\n#output chart\n# naming the x-axis\nplt.xlabel('Email address')\n# naming the y-axis\nplt.ylabel('Number of Emails')\n# plot title\nplt.title('Emails with word invoice in subject')\n#plt.plot(xaxis[:10], yaxis[:10], figsize=(20,4))\nplt.bar(SortedUniqueListX[10:20], yaxis[10:20], tick_label = SortedUniqueListX[10:20], width = 0.5, color = ['lightblue', 'lightgreen'])\nplt.xticks(rotation=80)\nplt.tight_layout()\n#plt.figure(figsize=(10, 5))\nplt.show()","sub_path":"Assigment1/venv/EmailSubjectAnalysisWithInvoices.py","file_name":"EmailSubjectAnalysisWithInvoices.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"62558002","text":"# -*- coding: utf-8 -*-\n#\n\"\"\"utils.py\"\"\"\nfrom datetime import datetime, date, timedelta\n\ndef do_load_dotenv():\n if do_load_dotenv.completed:\n return True\n from dotenv import load_dotenv\n load_dotenv()\n do_load_dotenv.completed = True\n return True\ndo_load_dotenv.completed = False\n\ndef isostring_to_datetime(iso_string):\n \"\"\"\n :param iso_string:\n :type iso_string: str\n :return: the python datetime obj\n :rtype: datetime\n \"\"\"\n if iso_string.endswith('Z'):\n iso_string = iso_string[:-1]+\"+0000\"\n else:\n last4 = iso_string[-4:]\n if \":\" in last4:\n # something like +04:30, change to 0430\n iso_string = iso_string[:-4] + last4.replace(\":\", \"\")\n try:\n return datetime.strptime(iso_string, \"%Y-%m-%dT%H:%M:%S%z\")\n except:\n return datetime.strptime(iso_string, \"%Y-%m-%dT%H:%M:%S.%f%z\")\n\ndelta_1h = timedelta(hours=1)\ndelta_1m = timedelta(minutes=1)\ndelta_1s = timedelta(seconds=1)\ndef datetime_to_isostring(py_datetime):\n \"\"\"\n :param py_datetime:\n :type py_datetime: datetime\n :return: the iso string representation\n :rtype: str\n \"\"\"\n tz = getattr(py_datetime, \"tzinfo\", None) # type: tzinfo\n if tz:\n off = tz.utcoffset(py_datetime)\n if off is not None:\n if off.days < 0:\n sign = \"-\"\n off = -off\n else:\n sign = \"+\"\n hh, mm = divmod(off, delta_1h)\n mm, ss = divmod(mm, delta_1m)\n if ss >= delta_1s:\n raise RuntimeError(\"ISO Datetime string cannot have UTC offset with seconds component\")\n if hh == 0 and mm == 0:\n suffix = \"Z\"\n else:\n suffix = \"%s%02d%02d\" % (sign, hh, mm)\n else:\n suffix = \"Z\"\n else:\n suffix = \"Z\"\n\n if isinstance(py_datetime, date) and not isinstance(py_datetime, datetime):\n datetime_string = py_datetime.strftime(\"%Y-%m-%dT00:00:00\")\n else:\n micros = getattr(py_datetime, 'microsecond', 0)\n if micros > 0:\n datetime_string = py_datetime.strftime(\"%Y-%m-%dT%H:%M:%S.%f\")\n else:\n datetime_string = py_datetime.strftime(\"%Y-%m-%dT%H:%M:%S\")\n return datetime_string + suffix\n\n\ndef sql_to_isostring(sql_datetime):\n \"\"\"\n Assumes sql date string is in UTC\n :param sql_datetime:\n :return:\n \"\"\"\n timestamp_parts = str(sql_datetime).split(' ')\n return \"{}T{}Z\".format(timestamp_parts[0], timestamp_parts[1])\n\n\ndef datetime_to_sql(py_datetime):\n \"\"\"\n Assumes datetime is in UTC.\n :param py_datetime:\n :type py_datetime: datetime\n :return: the sql string representation\n :rtype: str\n \"\"\"\n return py_datetime.strftime(\"%Y-%m-%d %H:%M:%S\")\n","sub_path":"nmdb/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"512384145","text":"#python3!\n#发送电子邮件给未充费的会员\nimport openpyxl,smtplib,os\nfrom openpyxl.utils import get_column_letter , column_index_from_string\nfrom email.mime.text import MIMEText\nfrom email.header import Header\n#通过excel读取未充会费的会员\nos.chdir('E://作业//auto')\nexcelfile=openpyxl.load_workbook('duesRecords.xlsx')\nSheet=excelfile.active\nnotpaid={}\nnum=Sheet.max_column\nfor i in range(1,Sheet.max_row+1):\n if Sheet.cell(row=i,column=num).value==None:\n notpaid.setdefault(Sheet.cell(row=i,column=1),Sheet.cell(row=i,column=2))\n else:\n pass\n #读取excel表格\n #将未充会费的会员加入dictS\n#登录邮箱自动发送邮件给没有充会费的成员\n #编辑信息内容\nprint(str(notpaid))\nFrom='1611229615@qq.com'\nmessage=MIMEText('没有充会费','plain','utf-8')\nmessage['Subject']=Header('交会费哦!','utf-8')\nmessage['From']=\"1611229615@qq.com\"\n #sign in\nsmtpobj=smtplib.SMTP(\"smtp.qq.com\",587)\nsmtpobj.ehlo()\nsmtpobj.starttls()\nsmtpobj.login(From,'xxxxxxxxxxxxx')\n #登录邮箱自动发送\nfor vip in notpaid.keys():\n print(vip)\n print(notpaid[vip].value)\n message['To']=notpaid[vip].value\n to=notpaid[vip].value\n smtpobj.sendmail(From,to,message.as_string())\n #退出邮箱\nsmtpobj.quit()\n","sub_path":"16101.py","file_name":"16101.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"499117837","text":"import numpy as np\nimport random\nimport os\nimport scipy.misc\n\ndef sample(size, channel, path, batch_size):\n choice_file_names = random.sample(os.listdir(path), batch_size)\n imgs = np.empty((0,size,size,channel), dtype=np.float32)\n encode = lambda x: x/127.5 -1\n\n for file_name in choice_file_names:\n img = encode(scipy.misc.imread(path+file_name).astype(np.float32))\n imgs = np.append(imgs, np.array([img]), axis=0)\n imgs = imgs.reshape((-1,size,size,channel))\n return imgs\n\ndef visualize(size, fakeX, batch_size, i):\n decode = lambda x: (x+1.)/2\n for n in range(batch_size):\n scipy.misc.imsave('./visualized/batch_{}itr{}.jpg'.format(n,i), decode(fakeX[n]))\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"134259500","text":"try:\n import time\n time.sleep(5)\n\n import socketio\n import webbrowser\n import sys\n\n sio = socketio.Client()\n\n @sio.on('connect')\n def connect():\n sio.emit('virus_connected')\n\n @sio.on('open_url')\n def open_url(data):\n url = data['url']\n print(f'url : {url}')\n webbrowser.open(url)\n #webbrowser.get(using='opera').open_new_tab(url) # DEVELOPMENT VERSION\n\n @sio.on('deactivate')\n def deactivate():\n print('DEACTIVATING')\n sio.emit('confirm_deactivate')\n\n @sio.on('finish_deactivating')\n def finish():\n time.sleep(0.5)\n sio.disconnect()\n time.sleep(0.5)\n sys.exit(0)\n\n @sio.on('ping')\n def ping():\n sio.emit('pong')\n time.sleep(0.1)\n\n try: \n sio.connect('https://debik.pp.ua')\n except ConnectionError:\n sio.connect('http://debik.pp.ua')\nexcept BaseException as e:\n print(e)\n time.sleep(7)\nelse:\n print('Connected to server')","sub_path":"pc_client/__pycache__/virus(build_for_compiling).py","file_name":"virus(build_for_compiling).py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"167650077","text":"import pymysql\nimport requests\nfrom bs4 import BeautifulSoup\nfrom tomorrow import threads\nfrom urllib3.exceptions import InsecureRequestWarning\n\nappKey = \"MldySkFwUXRnNGZzMURocjpyazFDNm94Nlh1OXppOWZF\"\nheader = {\n 'Host': 'www.tripadvisor.cn',\n 'Referer': 'https://www.tripadvisor.cn/Hotel_Review-g190356-d1767582-Reviews-or10-Novotel_Suites_'\n 'Luxembourg-Luxembourg_City.html',\n 'Connection': 'keep-alive',\n 'Content': 'keep-alive',\n 'X-Puid': 'W01f1H8AAAEAAJqYbXMAAAA6',\n 'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest',\n \"Proxy-Authorization\": 'Basic ' + appKey\n}\nip_port = \"transfer.mogumiao.com:9001\"\n\nproxy = {\"http\": \"http://\" + ip_port, \"https\": \"https://\" + ip_port}\n\nfailed_record = \"城市酒店失败url_20180727.txt\"\nsuccess_record = \"已抓取城市url.txt\"\n\n\ndef getpagenum(url):\n data_form = {'offset': 0, 'cat': \"1,2,3\"}\n try:\n r = requests.post(url, headers=header, data=data_form, verify=False, timeout=10, proxies=proxy)\n if r.status_code == 200:\n soup = BeautifulSoup(r.text, 'html.parser')\n try:\n num = soup.find(attrs={'class': 'unified ui_pagination standard_pagination ui_section listFooter'})[\n 'data-numpages']\n except Exception:\n num = 1\n return int(num)\n else:\n print(\"get pagenum failed!\")\n return 0\n except Exception:\n return 0\n\n\n@threads(10)\ndef get_hotel_url(city_url, city_location):\n print(city_url)\n pagenum = getpagenum(city_url) # req1\n print(pagenum)\n flag = 0\n\n if pagenum == 0:\n with open(\"得不到页码url_20180727.txt\", \"a+\") as ym:\n ym.write(city_url + \"\\n\")\n return\n else:\n connection = pymysql.connect(\n host='localhost',\n user='root',\n password='zxc1015zxc',\n db='trip_spider',\n cursorclass=pymysql.cursors.DictCursor\n )\n\n for x in range(pagenum):\n # data_form = {'offset': 0, 'cat': \"1,2,3\"}\n data_form = {'offset': str(x * 30), 'cat': \"1,2,3\"}\n try:\n # req2\n r2 = requests.post(city_url, headers=header, data=data_form, verify=False, timeout=10, proxies=proxy)\n s2 = BeautifulSoup(r2.content, 'html5lib')\n # html_30 = s2.find_all(\"div\", class_='listing collapsed')\n url_30 = [\"https://www.tripadvisor.cn\" + j.find(\"a\")['href'] for j in\n s2.find_all('div', attrs={'class': 'listing_title'})]\n name_30 = [j.find(\"a\").string for j in s2.find_all('div', attrs={'class': 'listing_title'})]\n for y in range(len(url_30)):\n sql = \"INSERT INTO `city_hotels_copy1` (`city`,`hotel_name`,`hotel_url`,`city_url`)\" \\\n \" VALUES (%s,%s,%s,%s) \"\n a = (city_location, name_30[y], url_30[y], city_url)\n try:\n with connection.cursor() as cursor:\n cursor.execute(sql, a)\n connection.commit()\n print(\"Done\")\n except Exception as e:\n print(repr(e))\n finally:\n # connection.close()\n pass\n except Exception as e:\n print(repr(e))\n with open(failed_record, \"a+\", encoding=\"utf-8\") as f2:\n f2.write(city_url + \",\" + data_form[\"offset\"] + \"\\n\")\n flag = 1\n continue\n if flag == 0:\n with open(success_record, \"a+\", encoding=\"utf-8\") as suc:\n suc.write(city_url + \"\\n\")\n\n\ndef get_location_name(city_url):\n index = city_init_urls.index(city_url)\n return city_init_locations[index]\n\n\nif __name__ == \"__main__\":\n print(\"hello\")\n f1 = open(\"country_cities_20180725.txt\", \"r\", encoding=\"utf-8\")\n city_init_lists = [item.strip(\"\\n\") for item in f1.readlines()]\n f1.close()\n city_init_urls = [\"https://www.tripadvisor.cn\" + i.split(\",\")[2] for i in city_init_lists]\n city_init_locations = [i.split(\",\")[0] for i in city_init_lists]\n\n f = open(\"城市酒店失败url.txt\", \"r\", encoding=\"utf-8\")\n city_lists = [item.strip(\"\\n\") for item in f.readlines()]\n f.close()\n requests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n city_urls = [i.split(\",\")[0] for i in city_lists]\n # city_locations = [i.split(\",\")[0] for i in city_lists]\n len_city = len(city_urls)\n for i in range(len_city):\n get_hotel_url(city_urls[i], get_location_name(city_urls[i]))\n print(\"hello\")\n\n # for i in city_urls:\n # print(get_location_name(i))\n","sub_path":"city_hotels_2.py","file_name":"city_hotels_2.py","file_ext":"py","file_size_in_byte":4921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"444963153","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'leon'\n\nimport sys\n\nsys.path.insert(0, '..')\n\nimport logging\nfrom contextlib import contextmanager\n\nfrom pyctrip import CtripClient\n\n\n# for testing\nlogging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'\n)\n\n# replace with right `alliance_id`, `sid` and `api_key`\nctrip = CtripClient('alliance_id', 'sid', 'api_key', raise_api_error=False)\n# ctrip = CtripClient('alliance_id', 'sid', 'api_key', raise_api_error=True)\n\n\n@contextmanager\ndef recover_from_exception():\n try:\n yield\n except Exception as e:\n import traceback\n\n traceback.print_exc()\n\n\n@contextmanager\ndef raise_api_error():\n ctrip.raise_api_error = True\n try:\n yield\n finally:\n ctrip.raise_api_error = False\n\n# with raise_api_error(), recover_from_exception():\n# ctrip.Hotel.OTA_Ping(echo_data='阿什顿')\n\n# with recover_from_exception():\n# ctrip.Hotel.OTA_Ping(echo_data='阿什顿')\n\n# with raise_api_error():\n# ctrip.Hotel.OTA_HotelSearch(city_code=2, area_id=112, hotel_name='上海')\n\nctrip.Hotel.OTA_HotelSearch(city_code=2, area_id=112, hotel_name='上海')\n# ctrip.Hotel.OTA_HotelSearch(city_code=2, rating=3)\n\nctrip.Hotel.OTA_HotelDescriptiveInfo(hotel_codes='625,626',\n position_type='502',\n hotel_info=True,\n room_info=True,\n area_info_att=True, area_info_rec=True,\n contact_info=True,\n multimedia=True)\n\nctrip.Hotel.OTA_HotelRatePlan(hotel_codes='625,626/123',\n date_start='2015-10-01',\n date_end='2015-10-02',\n display_ind=True\n )\n\nctrip.Hotel.OTA_HotelCacheChange(city_code=2,\n from_timestamp='2015-09-15T12:00:00.000000+08:00')\n\nctrip.Hotel.OTA_HotelAvail(hotel_code='625',\n date_start='2015-09-15T12:00:00.000000+08:00',\n date_end='2015-09-17T12:00:00.000000+08:00',\n rate_plan_code='123',\n quantity=2, guest_count=2, per_room=False,\n arrive_time='2015-09-15T18:00:00.000000+08:00',\n is_pre_pay=False)\n\nctrip.Hotel.OTA_Cancel(ctrip_order_id='168421264',\n ctrip_uid='c563a9ed-a090-4ded-b5dc-ddf1d3709e29',\n reason_codes='506,507,111')\n\nctrip.Hotel.OTA_HotelResNotif(last_modify='2015-09-15T18:00:00.000000+08:00')\n","sub_path":"tests/test_hotel.py","file_name":"test_hotel.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"58416294","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win32\\egg\\tests\\plugins\\poweradminbf3\\test_cmd_vipsave.py\n# Compiled at: 2016-03-08 18:42:10\nfrom mockito import when\nfrom b3.config import CfgConfigParser\nfrom b3.parsers.frostbite2.protocol import CommandFailedError\nfrom b3.plugins.poweradminbf3 import Poweradminbf3Plugin\nfrom tests.plugins.poweradminbf3 import Bf3TestCase\n\nclass Test_cmd_vipsave(Bf3TestCase):\n\n def setUp(self):\n Bf3TestCase.setUp(self)\n self.conf = CfgConfigParser()\n self.conf.loadFromString('[commands]\\nvipsave: 20\\n ')\n self.p = Poweradminbf3Plugin(self.console, self.conf)\n self.p.onLoadConfig()\n self.p.onStartup()\n self.moderator.connects('moderator')\n\n def test_nominal(self):\n when(self.console).write(('reservedSlotsList.list', 0)).thenReturn([])\n when(self.console).write(('reservedSlotsList.save', )).thenReturn([])\n self.moderator.connects('moderator')\n self.moderator.message_history = []\n self.moderator.says('!vipsave')\n self.assertEqual(1, len(self.moderator.message_history))\n self.assertEqual('VIP list saved to disk (0 name written)', self.moderator.message_history[0])\n\n def test_nominal_2(self):\n when(self.console).write(('reservedSlotsList.list', 0)).thenReturn(['foo', 'bar'])\n when(self.console).write(('reservedSlotsList.list', 2)).thenReturn([])\n when(self.console).write(('reservedSlotsList.save', )).thenReturn([])\n self.moderator.connects('moderator')\n self.moderator.message_history = []\n self.moderator.says('!vipsave')\n self.assertEqual(1, len(self.moderator.message_history))\n self.assertEqual('VIP list saved to disk (2 names written)', self.moderator.message_history[0])\n\n def test_frostbite_error(self):\n when(self.console).write(('reservedSlotsList.list', 0)).thenReturn([])\n when(self.console).write(('reservedSlotsList.save', )).thenRaise(CommandFailedError(['f00']))\n self.moderator.connects('moderator')\n self.moderator.message_history = []\n self.moderator.says('!vipsave')\n self.assertEqual(['Error: f00'], self.moderator.message_history)","sub_path":"pycfiles/b3-1.10.10-py2.7/test_cmd_vipsave.py","file_name":"test_cmd_vipsave.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"597551717","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 21 10:05:49 2019\n\n@author: tomoki\n\"\"\"\n\nimport re\nimport codecs\nimport csv, operator\nfrom Bio.Seq import Seq\nfrom Bio import SeqIO\nfrom Bio import SeqFeature\nfrom Bio.Alphabet import generic_dna\nfrom Bio.SeqFeature import SeqFeature, FeatureLocation\n\nwith open(\"/Users/tomoki/github/kops/analysis/kops_position_20201106.csv\", \"w\") as csv_file:\n fieldnames = [\"sequence\", \"start\", \"end\", \"direction\"]\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writeheader()\n\nfor record in SeqIO.parse(\"/Users/tomoki/github/kops/data/GCF_000010245.2_ASM1024v1_genomic.gbff\", \"genbank\"):\n seq = record.seq # Add sequence of E.coli genome\n\n nlist = [\"A\", \"T\", \"G\", \"C\"]\n ori = 3677235\n ter = 1561332\n head = 0\n tail = 4646332\n \n for n in nlist:\n dna = \"GGG\" + n + \"AGGG\"\n kops = Seq(dna, generic_dna)\n re_kops = kops[::-1]\n comp_kops = re_kops.complement()\n\n iterator = re.finditer(str(kops), str(seq))\n for match in iterator:\n target = match.group()\n start = match.start()\n end = match.end()\n if ori <= int(match.start()) < tail or head <= int(match.start()) < ter:\n output = str(target) + \",\" +str(match.start()+1) + \",\" + str(match.end()) + \",\" + str(\"leading\") + \",\" + seq[start-75:start+75]\n print (output)\n else:\n output = str(target) + \",\" +str(match.start()+1) + \",\" + str(match.end()) + \",\" + str(\"lagging\") + \",\" + seq[start-75:start+75]\n print (output)\n with open(\"/Users/tomoki/github/kops/analysis/kops_position_20201106.csv\", \"a\") as f:\n print (output, file=f)\n \n iterator = re.finditer(str(comp_kops), str(seq))\n for match in iterator:\n target = match.group()\n start = match.start()\n end = match.end()\n if ter <= int(match.start()) < ori:\n output = str(target) + \",\" +str(match.start()+1) + \",\" + str(match.end()) + \",\" + str(\"lagging\") + \",\" + seq[start-75:start+75]\n print (output)\n else:\n output = str(target) + \",\" +str(match.start()+1) + \",\" + str(match.end()) + \",\" + str(\"leading\") + \",\" + seq[start-75:start+75]\n print (output)\n with open(\"/Users/tomoki/github/kops/analysis/kops_position_20201106.csv\", \"a\") as f:\n print (output, file=f)\n \n else:\n pass\n \n\"\"\"\nReference:\n \n https://qiita.com/wanwanland/items/ce272419dde2f95cdabc\n https://python.keicode.com/lang/regular-expression-finditer.php\n \n # change\n\"\"\"","sub_path":"scripts/20201202_gcskew.py","file_name":"20201202_gcskew.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"485534701","text":"# 최고의 집합 - 기본수학 - 12938\n# 자연수 n 개로 이루어진 중복 집합(multi set, 편의상 이후에는 \"집합\"으로 통칭) 중에 다음 두 조건을 만족하는 집합을 최고의 집합이라고 합니다.\n# 각 원소의 합이 S가 되는 수의 집합\n# 위 조건을 만족하면서 각 원소의 곱 이 최대가 되는 집합\n# 예를 들어서 자연수 2개로 이루어진 집합 중 합이 9가 되는 집합은 다음과 같이 4개가 있습니다.\n# { 1, 8 }, { 2, 7 }, { 3, 6 }, { 4, 5 }\n# 그중 각 원소의 곱이 최대인 { 4, 5 }가 최고의 집합입니다.\n# 집합의 원소의 개수 n과 모든 원소들의 합 s가 매개변수로 주어질 때, 최고의 집합을 return 하는 solution 함수를 완성해주세요.\n\n# 최고의 집합은 오름차순으로 정렬된 1차원 배열(list, vector) 로 return 해주세요.\n# 만약 최고의 집합이 존재하지 않는 경우에 크기가 1인 1차원 배열(list, vector) 에 -1 을 채워서 return 해주세요.\n# 자연수의 개수 n은 1 이상 10,000 이하의 자연수입니다.\n# 모든 원소들의 합 s는 1 이상, 100,000,000 이하의 자연수입니다.\n\n# def solution(n, s):\n# answer = []\n# if n > s:\n# return [-1]\n\n# for i in range(n):\n# na = s % n\n# if i == n-1:\n# answer.append(mok + na)\n# else:\n# mok = s // n\n# answer.append(mok)\n\n# return answer\n\ndef solution(n, s):\n answer = []\n # 될 수 없는 경우\n if n > s:\n return [-1]\n\n mok = s // n\n na = s % n\n\n # n - 나머지 만큼 몫 추가\n for _ in range(n - na):\n answer.append(mok)\n # 나머지 만큼 몫 + 1 추가\n for _ in range(na):\n answer.append(mok+1)\n\n return answer\n\n\nprint(solution(4, 10))\n","sub_path":"python/programmers/기본수학/[12938_기본수학_최고의집합]홍종완.py","file_name":"[12938_기본수학_최고의집합]홍종완.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"98019157","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Time : 2020/7/8 16:20\n# @Author : lirixiang\n# @Email : 565539277@qq.com\n# @File : 32-PrintMinNumber.py\n\"\"\"\n输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。\n例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。\n\"\"\"\n# -*- coding:utf-8 -*-\nclass Solution:\n def PrintMinNumber(self, numbers) -> str:\n # write code here\n\n if len(numbers) == 0:\n return \"\"\n res = list(map(int, self.Permutation(numbers)))\n\n def bubble_sort(arr):\n n = len(arr)\n for i in range(n):\n for j in range(n - 1 - i):\n if arr[j] > arr[j + 1]:\n arr[j], arr[j + 1] = arr[j + 1], arr[j]\n return arr\n\n arr = bubble_sort(res)\n return arr[0]\n\n def Permutation(self, numbers):\n if len(numbers) == 1:\n return numbers\n\n str_numbers = list(map(str, numbers))\n sl = []\n for i in range(len(str_numbers)):\n for j in self.Permutation(str_numbers[:i] + str_numbers[i + 1:]):\n sl.append(str_numbers[i] + j)\n return sl\n\n\ns = Solution()\nres = s.PrintMinNumber([3,32,321])\nprint(res)","sub_path":"src/剑指offer/32-PrintMinNumber.py","file_name":"32-PrintMinNumber.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"326718737","text":"import insuranceqa_data as insuranceqa\nimport os\n\n# train_data = insuranceqa.load_pairs_train()\ntest_data = insuranceqa.load_pairs_test()\n# valid_data = insuranceqa.load_pairs_valid()\n\ntrain_data = insuranceqa.load_pool_train()\nprint(train_data)\n\nvocab_data = insuranceqa.load_pairs_vocab()\nprint(vocab_data['word2id']['UNKNOWN'])\nword = vocab_data['id2word']['10']\nprint(word)\nprint(vocab_data['tf'][word])\nprint(vocab_data['total'])\nprint(test_data[0])\nprint(test_data[1])\n\n\ndef ids_to_sentence(ids, id2word):\n words = [id2word[str(id)] for id in ids]\n sentence = ''.join(words)\n return sentence\n\n\nfor i in range(20):\n x = test_data[i]\n question_ids = x['question']\n utterance_ids = x['utterance']\n question = ids_to_sentence(question_ids, vocab_data['id2word'])\n utterance = ids_to_sentence(utterance_ids, vocab_data['id2word'])\n\n # print(x)\n print('question_ids: %s \\nquestion: %s \\nutterance: %s' % (question_ids, question, utterance))\n print('-------------------------------------------------')\n\n# valid_data, test_data and train_data share the same properties\n# for x in test_data:\n# print('index %s value: %s ++$++ %s ++$++ %s' % \\\n# (x['qid'], x['question'], x['utterance'], x['label']))\n\n# vocab_data = insuranceqa.load_pairs_vocab()\n# vocab_data['word2id']['UNKNOWN']\n# vocab_data['id2word'][0]\n# vocab_data['tf']\n# vocab_data['total']","sub_path":"arsenal/eipi10/chat/insuranceqa_test.py","file_name":"insuranceqa_test.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"609724957","text":"#-*- coding: utf-8\n\"\"\"\n Program to correct limb darkening in python based on ILD/swwidl\n Based on:\n https://hesperia.gsfc.nasa.gov/ssw/gen/idl/solar/darklimb_correct.pro\n\n Coefficients taken from \n Cox, A. N.: Allen's Astrophysical Quantities, Springer, 2000 taken from IDL\n\n Author: AngelMartinezC\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy.io import fits\nimport os\n\n\n\ndef writefits(image):\n\tos.system(\"rm -r limbcorrect.fits\")\n\thdu = fits.PrimaryHDU(image)\n\thdul = fits.HDUList([hdu])\n\thdul.writeto('limbcorrect.fits')\n\ndef figure(image,title=\"image\",save=False):\n\tplt.figure(figsize=(8,8))\n\tplt.title('Image')\n\tplt.imshow(image,cmap = 'Greys_r',origin='lower')\n\tif save == True:\n\t\tplt.savefig(title+\".png\")\n\telse:\n\t\tpass\n\tplt.show()\n\n\ndef darklimb(array):\n\t\n\t\"\"\"\n\t Darklimb function:\n\t \n\t It is requiered the files to be in a .FITS file in order to take\n\t advantage of the Header structure.\n\t \n\t Output:\n\t Dos arrays: The first image is the corrected array, the second\n\t one is the original. \n\t\"\"\"\n\t\n\t# -------------------------------------------------------------\n\t\n\tdef darklimb_u(ll):\n\t\tpll = np.array([1.0,ll,ll**2,ll**3,ll**4,ll**5])\n\t\tau = -8.9829751\n\t\tbu = 0.0069093916\n\t\tcu = -1.8144591e-6\n\t\tdu = 2.2540875e-10\n\t\teu = -1.3389747e-14\n\t\tfu = 3.0453572e-19\n\t\ta=np.array([au,bu,cu,du,eu,fu])\n\t\tul = sum(a*pll)\n\t\treturn ul\n\n\tdef darklimb_v(ll):\n\t\tpll = np.array([1.0,ll,ll**2,ll**3,ll**4,ll**5])\n\t\tav = 9.2891180\n\t\tbv = -0.0062212632\n\t\tcv = 1.5788029e-6\n\t\tdv = -1.9359644e-10\n\t\tev = 1.1444469e-14\n\t\tfv = -2.599494e-19\n\t\ta=np.array([av,bv,cv,dv,ev,fv])\n\t\tvl = sum(a*pll)\n\t\treturn vl\n\t\n\t# -------------------------------------------------------------\n\t\n\t# Read data files\n\tdata = fits.getdata(name,0)\n\thead = fits.getheader(name,0)\n\n\t# Parameters needed for the function\n\twavelength = head['WAVELNTH'] # Wavelenght\n\txcen = head['CRPIX1'] # X center\n\tycen = head['CRPIX2'] # Y center\n\tradius = head['RSUN_OBS']/head['CDELT1'] # Pixels result\n\tsize = head['NAXIS1'] # X array size\n\n\tll =1.0*wavelength\n\n\tarray = np.array(data) # Convert data into numpy arrays\n\tNaNs = np.isnan(array) # Look for NANs\n\tarray[NaNs] = 0.0 # Make zero all NANs\n\n\t# Apply correction\n\tul = darklimb_u(ll)\n\tvl = darklimb_v(ll)\n\n\txarr = np.arange(0,size,1.0) # Make X array\n\tyarr = np.arange(0,size,1.0) # Make Y array\n\txx, yy = np.meshgrid(xarr, yarr) # Make XY array\n\t# z: Make array so that the zero center is the center XY\n\t# Performed in order to make a circle\n\tz = np.sqrt((xx-xcen)**2 + (yy-ycen)**2) \n\t# grid: Normalize the circle so that inside radius is the unity\n\tgrid = z/radius \n\tout = np.where(grid>1.0) # Look for the values greater than unity\n\tgrid[out] = 0.0 # Make zero all those values (Domain of arcsin)\n\n\tlimbfilt = 1.0-ul-vl+ul*np.cos(np.arcsin(grid))+vl*np.cos(np.arcsin(grid))**2\n\n\t# Final image\n\timgout=np.array(array/limbfilt)\n\t\n\treturn imgout, array\n\n\nif __name__=='__name__':\n\t\n\tname = 'hmi.ic_45s.2014.02.04_03_44_15_TAI.continuum.fits'\n\tcorrected, original = darklimb(name)\n\n\t#writefits(corrected)\n\tfigure(corrected,title='corrected1',save=True)\n\tfigure(original,title='original1',save=True)\n\n\n\n","sub_path":"darklimb.py","file_name":"darklimb.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"195781998","text":"import sys\nimport os\nimport subprocess\nfrom splunk_logger import setup_logging\nfrom utils import load_pyden_config, write_pyden_config\nif sys.version < '3':\n pass\nelse:\n from importlib import reload\n\n\ndef activate():\n if sys.argv[-1] == \"reloaded\":\n reload(os)\n reload(sys)\n return\n\n sys.argv.append(\"reloaded\")\n bin_dir = os.path.dirname(py_exec)\n path = bin_dir + os.pathsep + os.environ[\"PATH\"]\n os.execve(py_exec, ['python'] + sys.argv, {\"PATH\": path, \"SPLUNK_HOME\": os.environ['SPLUNK_HOME']})\n\n\nif __name__ == \"__main__\":\n outputfile = sys.stdout\n sys.stdout.write(\"message\\n\")\n logger = setup_logging()\n args = dict()\n for arg in sys.argv[1:]:\n try:\n if \"reloaded\" in arg:\n continue\n k, v = arg.split('=')\n args[k] = v\n except ValueError:\n logger.error(\"Incorrect argument provided\")\n sys.exit(1)\n pm_config, config = load_pyden_config()\n logger.info(config.sections())\n pyden_location = pm_config.get('appsettings', 'location')\n if 'name' not in args:\n logger.error(\"No name for the new environment was provided.\")\n sys.stdout.write(\"No name for the new environment was provided.\")\n sys.exit(1)\n # get executable\n version = args.get('version')\n if not version:\n if config.has_option(\"default-pys\", \"distribution\"):\n version = config.get(\"default-pys\", \"distribution\")\n name = args['name']\n if name in config.sections():\n logger.error(\"Virtual environment name {} already exists\".format(name))\n sys.stdout.write(\"Virtual environment name {} already exists\".format(name))\n sys.exit(1)\n\n if version in config.sections():\n py_exec = os.path.join(os.environ['SPLUNK_HOME'], config.get(version, 'executable'))\n activate()\n else:\n logger.error(\"Python version not found in pyden.conf.\")\n sys.stdout.write(\"Python version not found in pyden.conf\")\n sys.exit(1)\n if not config.has_option(\"default-pys\", \"environment\"):\n write_pyden_config(pyden_location, config, 'default-pys', 'environment', name)\n\n venv_dir = os.path.join(pyden_location, 'local', 'lib', 'venv')\n if not os.path.isdir(venv_dir):\n os.makedirs(venv_dir)\n os.chdir(venv_dir)\n venv = subprocess.Popen([py_exec, '-m', \"virtualenv\", name], stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n universal_newlines=True)\n result, error = venv.communicate()\n for message in result.split('\\n'):\n if message:\n logger.info(message)\n for message in error.split('\\n'):\n if message:\n logger.error(message)\n if venv.returncode != 0:\n sys.exit(1)\n venv_exec = os.path.join(venv_dir, name, 'bin', 'python')\n write_pyden_config(pyden_location, config, name, \"executable\", venv_exec.lstrip(os.environ['SPLUNK_HOME']))\n write_pyden_config(pyden_location, config, name, 'version', version)\n sys.stdout.write(\"Successfully created virtual environment {} using Python {}\\n\".format(name, version))\n","sub_path":"src/pyden-manager/bin/create_venv.py","file_name":"create_venv.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"45010604","text":"from itertools import combinations, permutations\n\n\ndef solution(baseball):\n candidates = []\n for c in combinations(range(1, 10), 3):\n for p in permutations(c):\n candidates.append(100*p[0]+10*p[1]+p[2])\n\n for guess, strike, ball in baseball:\n new_candidates = []\n for c in candidates:\n guess = str(guess)\n c = str(c)\n s = int(guess[0] == c[0]) + int(guess[1] == c[1]) + int(guess[2] == c[2])\n b = c.count(guess[0]) + c.count(guess[1]) + c.count(guess[2]) - strike\n if (strike == s) and (ball == b):\n new_candidates.append(c)\n candidates = new_candidates\n\n answer = len(candidates)\n return answer\n\n\nif __name__ == '__main__':\n baseball = [[123, 1, 1], [356, 1, 0], [327, 2, 0], [489, 0, 1]]\n print(solution(baseball))\n\n","sub_path":"python/exhaustive_search/03_baseball.py","file_name":"03_baseball.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"164998429","text":"# -*- coding: utf-8 -*-\nimport copy\n\nimport numpy as np\nfrom matminer.featurizers.base import BaseFeaturizer\nfrom matminer.featurizers.site import (LocalStructOrderParams, cn_motif_op_params, cn_target_motif_op)\nfrom matminer.utils.caching import get_nearest_neighbors\nfrom matminer.utils.data import MagpieData\nfrom pymatgen.analysis.local_env import VoronoiNN\n\nfrom .crystalnn import CrystalNN\n\n\nclass LocalPropertyStatsNew(BaseFeaturizer):\n \"\"\"\n Differences, minima and maxima in elemental properties between site and its neighboring sites.\n Uses the Voronoi tessellation of the structure to determine the\n neighbors of the site, and assigns each neighbor (:math:`n`) a\n weight (:math:`A_n`) that corresponds to the area of the facet\n on the tessellation corresponding to that neighbor.\n The local property difference is then computed by\n :math:`\\\\frac{\\sum_n {A_n |p_n - p_0|}}{\\sum_n {A_n}}`\n where :math:`p_n` is the property (e.g., atomic number) of a neighbor\n and :math:`p_0` is the property of a site. If signed parameter is assigned\n True, signed difference of the properties is returned instead of absolute\n difference.\n Features:\n - \"local property stat in [property]\"\n References:\n `Ward et al. _PRB_ 2017 `_\n \"\"\"\n\n def __init__(self, data_source=MagpieData(), weight='area', properties=('Electronegativity',)):\n \"\"\" Initialize the featurizer\n Args:\n data_source (AbstractData) - Class from which to retrieve\n elemental properties\n weight (str) - What aspect of each voronoi facet to use to\n weigh each neighbor (see VoronoiNN)\n properties ([str]) - List of properties to use (default=['Electronegativity'])\n signed (bool) - whether to return absolute difference or signed difference of\n properties(default=False (absolute difference))\n \"\"\"\n self.data_source = data_source\n self.properties = properties\n self.weight = weight\n\n @staticmethod\n def from_preset(preset):\n \"\"\"\n Create a new LocalPropertyStats class according to a preset\n Args:\n preset (str) - Name of preset\n \"\"\"\n\n if preset == 'interpretable':\n return LocalPropertyStatsNew(\n data_source=MagpieData(),\n properties=[\n 'MendeleevNumber',\n 'Column',\n 'Row',\n 'Electronegativity',\n 'NsValence',\n 'NpValence',\n 'NdValence',\n 'NfValence',\n 'NValence',\n 'NsUnfilled',\n 'NpUnfilled',\n 'NdUnfilled',\n 'NfUnfilled',\n 'NUnfilled',\n 'GSbandgap',\n ],\n )\n else:\n raise ValueError('Unrecognized preset: ' + preset)\n\n def featurize(self, strc, idx):\n # Get the targeted site\n my_site = strc[idx]\n\n # Get the tessellation of a site\n nn = get_nearest_neighbors(\n VoronoiNN(weight=self.weight, cutoff=8, compute_adj_neighbors=False),\n strc,\n idx,\n )\n\n # Get the element and weight of each site\n elems = [n['site'].specie for n in nn]\n weights = [n['weight'] for n in nn]\n\n # Compute the difference for each property\n output = np.zeros((len(self.properties),))\n output_signed = np.zeros((len(self.properties),))\n output_max = np.zeros((len(self.properties),))\n output_min = np.zeros((len(self.properties),))\n\n total_weight = np.sum(weights)\n for i, p in enumerate(self.properties):\n my_prop = self.data_source.get_elemental_property(my_site.specie, p)\n n_props = self.data_source.get_elemental_properties(elems, p)\n output[i] = (np.dot(weights, np.abs(np.subtract(n_props, my_prop))) / total_weight)\n output_signed[i] = (np.dot(weights, np.subtract(n_props, my_prop)) / total_weight)\n output_max[i] = np.max(np.subtract(n_props, my_prop))\n output_min[i] = np.min(np.subtract(n_props, my_prop))\n return np.hstack([output, output_signed, output_max, output_min])\n\n def feature_labels(self):\n\n return (['local difference in ' + p for p in self.properties] +\n ['local signed difference in ' + p for p in self.properties] +\n ['maximum local difference in ' + p for p in self.properties] +\n ['minimum local difference in ' + p for p in self.properties])\n\n def citations(self):\n return [\n '@article{Ward2017,'\n 'author = {Ward, Logan and Liu, Ruoqian '\n 'and Krishna, Amar and Hegde, Vinay I. '\n 'and Agrawal, Ankit and Choudhary, Alok '\n 'and Wolverton, Chris},'\n 'doi = {10.1103/PhysRevB.96.024104},'\n 'journal = {Physical Review B},'\n 'pages = {024104},'\n 'title = {{Including crystal structure attributes '\n 'in machine learning models of formation energies '\n 'via Voronoi tessellations}},'\n 'url = {http://link.aps.org/doi/10.1103/PhysRevB.96.014107},'\n 'volume = {96},year = {2017}}',\n '@article{jong_chen_notestine_persson_ceder_jain_asta_gamst_2016,'\n 'title={A Statistical Learning Framework for Materials Science: '\n 'Application to Elastic Moduli of k-nary Inorganic Polycrystalline Compounds}, '\n 'volume={6}, DOI={10.1038/srep34256}, number={1}, journal={Scientific Reports}, '\n 'author={Jong, Maarten De and Chen, Wei and Notestine, Randy and Persson, '\n 'Kristin and Ceder, Gerbrand and Jain, Anubhav and Asta, Mark and Gamst, Anthony}, '\n 'year={2016}, month={Mar}}',\n ]\n\n def implementors(self):\n return ['Logan Ward', 'Aik Rui Tan']\n\n\nclass CrystalNNFingerprint(BaseFeaturizer):\n \"\"\"\n A local order parameter fingerprint for periodic crystals.\n The fingerprint represents the value of various order parameters for the\n site. The \"wt\" order parameter describes how consistent a site is with a\n certain coordination number. The remaining order parameters are computed\n by multiplying the \"wt\" for that coordination number with the OP value.\n The chem_info parameter can be used to also get chemical descriptors that\n describe differences in some chemical parameter (e.g., electronegativity)\n between the central site and the site neighbors.\n \"\"\"\n\n @staticmethod\n def from_preset(preset, **kwargs):\n \"\"\"\n Use preset parameters to get the fingerprint\n Args:\n preset (str): name of preset (\"cn\" or \"ops\")\n **kwargs: other settings to be passed into CrystalNN class\n \"\"\"\n if preset == 'cn':\n op_types = {k + 1: ['wt'] for k in range(24)}\n return CrystalNNFingerprint(op_types, **kwargs)\n\n elif preset == 'ops':\n op_types = copy.deepcopy(cn_target_motif_op)\n for k in range(24):\n if k + 1 in op_types:\n op_types[k + 1].insert(0, 'wt')\n else:\n op_types[k + 1] = ['wt']\n\n return CrystalNNFingerprint(op_types, chem_info=None, **kwargs)\n\n else:\n raise RuntimeError('preset \"{}\" is not supported in ' 'CrystalNNFingerprint'.format(preset))\n\n def __init__(self, op_types, chem_info=None, **kwargs):\n \"\"\"\n Initialize the CrystalNNFingerprint. Use the from_preset() function to\n use default params.\n Args:\n op_types (dict): a dict of coordination number (int) to a list of str\n representing the order parameter types\n chem_info (dict): a dict of chemical properties (e.g., atomic mass)\n to dictionaries that map an element to a value\n (e.g., chem_info[\"Pauling scale\"][\"O\"] = 3.44)\n **kwargs: other settings to be passed into CrystalNN class\n \"\"\"\n\n self.op_types = copy.deepcopy(op_types)\n self.cnn = CrystalNN(**kwargs)\n if chem_info is not None:\n self.chem_info = copy.deepcopy(chem_info)\n self.chem_props = list(chem_info.keys())\n else:\n self.chem_info = None\n\n self.ops = {} # load order parameter objects & paramaters\n for cn, t_list in self.op_types.items():\n self.ops[cn] = []\n for t in t_list:\n if t == 'wt':\n self.ops[cn].append(t)\n else:\n ot = t\n p = None\n if cn in cn_motif_op_params.keys():\n if t in cn_motif_op_params[cn].keys():\n ot = cn_motif_op_params[cn][t][0]\n if len(cn_motif_op_params[cn][t]) > 1:\n p = cn_motif_op_params[cn][t][1]\n self.ops[cn].append(LocalStructOrderParams([ot], parameters=[p]))\n\n def featurize(self, struct, idx):\n \"\"\"\n Get crystal fingerprint of site with given index in input\n structure.\n Args:\n struct (Structure): Pymatgen Structure object.\n idx (int): index of target site in structure.\n Returns:\n list of weighted order parameters of target site.\n \"\"\"\n\n nndata = self.cnn.get_nn_data(struct, idx)\n max_cn = sorted(self.op_types)[-1]\n\n cn_fingerprint = []\n\n if self.chem_info is not None:\n prop_delta = {} # dictionary of chemical property to final value\n for prop in self.chem_props:\n prop_delta[prop] = 0\n sum_wt = 0\n elem_central = struct.sites[idx].specie.symbol\n specie_central = str(struct.sites[idx].specie)\n\n for k in range(max_cn):\n cn = k + 1\n wt = nndata.cn_weights.get(cn, 0)\n if cn in self.ops:\n for op in self.ops[cn]:\n if op == 'wt':\n cn_fingerprint.append(wt)\n\n if self.chem_info is not None and wt != 0:\n # Compute additional chemistry-related features\n sum_wt += wt\n neigh_sites = [d['site'] for d in nndata.cn_nninfo[cn]]\n\n for prop in self.chem_props:\n # get the value for specie, if not fall back to\n # value defined for element\n prop_central = self.chem_info[prop].get(\n specie_central,\n self.chem_info[prop].get(elem_central),\n )\n\n for neigh in neigh_sites:\n elem_neigh = neigh.specie.symbol\n specie_neigh = str(neigh.specie)\n prop_neigh = self.chem_info[prop].get(\n specie_neigh,\n self.chem_info[prop].get(elem_neigh),\n )\n\n prop_delta[prop] += (wt * (prop_neigh - prop_central) / cn)\n\n elif wt == 0:\n cn_fingerprint.append(wt)\n else:\n neigh_sites = [d['site'] for d in nndata.cn_nninfo[cn]]\n opval = op.get_order_parameters(\n [struct[idx]] + neigh_sites,\n 0,\n indices_neighs=list(range(1,\n len(neigh_sites) + 1)),\n )[0]\n opval = opval or 0 # handles None\n cn_fingerprint.append(wt * opval)\n chem_fingerprint = []\n\n if self.chem_info is not None:\n for val in prop_delta.values():\n chem_fingerprint.append(val / sum_wt)\n\n return cn_fingerprint + chem_fingerprint\n\n def feature_labels(self):\n labels = []\n max_cn = sorted(self.op_types)[-1]\n for k in range(max_cn):\n cn = k + 1\n if cn in list(self.ops.keys()):\n for op in self.op_types[cn]:\n labels.append('{} CN_{}'.format(op, cn))\n if self.chem_info is not None:\n for prop in self.chem_props:\n labels.append('{} local diff'.format(prop))\n return labels\n\n def citations(self):\n return []\n\n def implementors(self):\n return ['Anubhav Jain', 'Nils E.R. Zimmermann']\n","sub_path":"oximachine_featurizer/featurizer_local_property.py","file_name":"featurizer_local_property.py","file_ext":"py","file_size_in_byte":13002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"199346118","text":"# generic\nfrom datetime import datetime\n\nfrom django.db.models import Q\nfrom django.contrib.auth import get_user_model\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth.models import User\nfrom rest_framework.pagination import PageNumberPagination\nfrom django.shortcuts import get_object_or_404\nfrom django.contrib.auth.decorators import login_required\n\nfrom bourseapp import models\nfrom . import serializers\nimport operator\nimport functools\n\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.decorators import api_view, permission_classes\n\nfrom drf_rw_serializers import generics, viewsets, mixins\n\nfrom rest_framework.pagination import PageNumberPagination\nfrom django.http import JsonResponse\nfrom django.db.models import Count, F\n\n\"\"\"\n-- Category class --\n\"\"\"\n\n\nclass CategoryAPIView(mixins.CreateModelMixin, generics.ListAPIView): # DetailView CreateView FormView\n lookup_field = 'pk' # slug, id # url(r'?P\\d+')\n serializer_class = serializers.CategorySerializer\n\n # permission_classes = []#[IsOwnerOrReadOnly]\n # queryset = BlogPost.objects.all()\n\n # search, ?q=tt\n def get_queryset(self):\n qs = models.Category.objects.all()\n query = self.request.GET.get(\"q\")\n if query is not None:\n qs = qs.filter(\n Q(title__icontains=query)\n # | Q(pic__icontains=query)\n ).distinct()\n\n query_list = self.request.GET.get(\"list\")\n if query_list is not None:\n ls = query_list.split('_')\n for itm in ls:\n param = itm.split(':')\n itmId = param[0]\n itmVar = param[1]\n models.Category.objects.filter(pk=itmId).update(orderNum=itmVar)\n\n return qs\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n # post method for creat item\n def post(self, request, *args, **kwargs):\n return self.create(request, *args, **kwargs)\n\n # def get_serializer_context(self, *args, **kwargs):\n # return {\"request\": self.request}\n\n\nclass CategoryRudView(generics.RetrieveUpdateDestroyAPIView): # DetailView CreateView FormView\n lookup_field = 'pk' # slug, id # url(r'?P\\d+')\n serializer_class = serializers.CategorySerializer\n permission_classes = [IsAuthenticated, ] # [IsOwnerOrReadOnly]\n\n # queryset = BlogPost.objects.all()\n\n def get_queryset(self):\n return models.Category.objects.all()\n\n # def get_serializer_context(self, *args, **kwargs):\n # return {\"request\": self.request}\n\n # def get_object(self):\n # pk = self.kwargs.get(\"pk\")\n # return BlogPost.objects.get(pk=pk)\n\n\nclass SymbolsAPIView(mixins.CreateModelMixin, generics.ListAPIView):\n lookup_field = 'pk' # slug, id # url(r'?P\\d+')\n serializer_class = serializers.SymbolSerializer\n\n # search, ?q=tt\n def get_queryset(self):\n qs = models.Company.objects.all()\n query = self.request.GET.get(\"q\")\n if query is not None:\n qs = qs.filter(\n Q(symbol__startswith=query)\n # | Q(pic__icontains=query)\n ).distinct()\n\n query_category = self.request.GET.get(\"c\")\n if query_category is not None:\n qs = qs.filter(\n Q(category=query_category)\n ).distinct()\n\n return qs\n\n\nclass ChartSymbolsAPIView(mixins.CreateModelMixin, generics.ListAPIView):\n lookup_field = 'pk' # slug, id # url(r'?P\\d+')\n serializer_class = serializers.ChartSymbolsSerializer\n\n # search, ?q=tt\n def get_queryset(self):\n qs = models.Chart.objects.all()\n query = self.request.GET.get(\"q\")\n if query is not None:\n qs = qs.filter(\n Q(company__symbol__startswith=query)\n # | Q(pic__icontains=query)\n ).distinct()\n\n return qs\n\n\nclass StandardResultsSetPagination(PageNumberPagination):\n page_size = 20\n page_size_query_param = 'page_size'\n max_page_size = 100\n\n\nclass UserList(mixins.CreateModelMixin, generics.ListAPIView):\n lookup_field = 'pk' # slug, id # url(r'?P\\d+')\n serializer_class = serializers.UserSerializer\n permission_classes = [IsAuthenticated] # [IsOwnerOrReadOnly, IsAuthenticated]\n # pagination_class = StandardResultsSetPagination\n\n # search, ?q=tt\n def get_queryset(self):\n qs = User.objects.all()\n query = self.request.GET.get(\"q\")\n if query is not None:\n qs = qs.filter(\n Q(first_name__icontains=query)\n | Q(last_name__icontains=query)\n | Q(username__icontains=query)\n ).distinct()\n\n return qs[:20]\n\n\nclass ChatMessageAPIView(mixins.CreateModelMixin, generics.ListAPIView): # DetailView CreateView FormView\n lookup_field = 'pk' # slug, id # url(r'?P\\d+')\n serializer_class = serializers.ChatMessageSerializer\n permission_classes = [IsAuthenticated, ] # [IsOwnerOrReadOnly]\n pagination_class = StandardResultsSetPagination\n\n # search, ?q=tt\n def get_queryset(self):\n qs = models.ChatMessage.objects.all()\n # limit msgs\n if self.request.user.groups.filter(name='level1').exists() is False and self.request.user.is_superuser is False:\n qs = qs.filter(\n Q(receiver=self.request.user) | Q(sender=self.request.user)\n ).distinct()\n\n query = self.request.GET.get(\"q\")\n if query is not None:\n qs = qs.filter(\n Q(description__icontains=query)\n # | Q(pic__icontains=query)\n ).distinct()\n\n query_target = self.request.GET.get(\"target\")\n if query_target is not None:\n qs = qs.filter(\n (Q(receiver=query_target) & Q(sender=self.request.user))\n |\n (Q(receiver=self.request.user) & Q(sender=query_target))\n ).distinct()\n\n query_user2admin = self.request.GET.get(\"user2admin\")\n query_admin = self.request.GET.get(\"admin\")\n if query_user2admin is not None and query_admin is not None:\n qs = qs.filter(\n (Q(receiver=query_user2admin) & Q(sender=query_admin))\n |\n (Q(receiver=query_admin) & Q(sender=query_user2admin))\n ).distinct()\n\n return qs\n\n def perform_create(self, serializer):\n # serializer.save(sender=self.request.user)\n serializer.save()\n # tick all unseen messages\n if get_user_model().objects.get(id=self.request.data['sender']).username == 'admins':\n user_reciver = get_user_model().objects.get(id=self.request.data['receiver'])\n unReadMsg = models.ChatMessage.objects.filter(Q(sender=user_reciver) & Q(isSeen=False))\n unReadMsg.update(isSeen=True)\n\n # post method for creat item\n def post(self, request, *args, **kwargs):\n return self.create(request, *args, **kwargs)\n\n # def get_serializer_context(self, *args, **kwargs):\n # return {\"request\": self.request}\n\n\nclass ChatMessageRudView(generics.RetrieveUpdateDestroyAPIView): # DetailView CreateView FormView\n lookup_field = 'pk' # slug, id # url(r'?P\\d+')\n serializer_class = serializers.ChatMessageSerializer\n permission_classes = [IsAuthenticated, ] # [IsOwnerOrReadOnly]\n\n # queryset = BlogPost.objects.all()\n\n def get_queryset(self):\n return models.ChatMessage.objects.all()\n\n\nclass TechnicalUserAPIView(mixins.CreateModelMixin, generics.ListAPIView): # DetailView CreateView FormView\n lookup_field = 'pk' # slug, id # url(r'?P\\d+')\n serializer_class = serializers.TechnicalUserSerializer\n permission_classes = [IsAuthenticated, ] # [IsOwnerOrReadOnly]\n\n # search, ?q=tt\n def get_queryset(self):\n\n query = self.request.GET.get(\"share\")\n query_company = self.request.GET.get(\"company\")\n if query is not None and query_company is not None:\n qs = models.TechnicalUser.objects.filter(\n Q(isShare=True)\n & Q(company=query_company)\n ).distinct()\n return qs\n\n qs = models.TechnicalUser.objects.filter(user=self.request.user)\n\n if query_company is not None:\n qs = qs.filter(\n Q(company=query_company)\n # | Q(pic__icontains=query)\n ).distinct()\n return qs\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n # post method for creat item\n def post(self, request, *args, **kwargs):\n return self.create(request, *args, **kwargs)\n\n\nclass TechnicalUserRudView(generics.RetrieveUpdateDestroyAPIView): # DetailView CreateView FormView\n lookup_field = 'pk' # slug, id # url(r'?P\\d+')\n serializer_class = serializers.TechnicalUserSerializer\n permission_classes = [IsAuthenticated, ] # [IsOwnerOrReadOnly]\n\n # queryset = BlogPost.objects.all()\n\n def get_queryset(self):\n return models.TechnicalUser.objects.all()\n\n\ndef chart_detail(request, company_id):\n chart = get_object_or_404(models.Chart, company=company_id, timeFrame='D1')\n profile_json = {\n \"data\": chart.data.url,\n }\n return JsonResponse(profile_json, safe=False)\n\n\ndef ChartView(request):\n\n # chart = get_object_or_404(models.Chart, company__symbol__icontains='شاخص بازار بورس', timeFrame='D1')\n chart_list = models.Chart.objects.filter(Q(company__symbol__icontains='شاخص کل')\n & Q(timeFrame='D1'))\n # print(chart_list)\n if len(chart_list) > 0:\n chart = chart_list.first()\n # print(chart.data.url)\n profile_json = {\n \"data\": chart.data.url,\n }\n else:\n profile_json = {\n \"data\": \"not found\",\n }\n return JsonResponse(profile_json, safe=False)\n\n\n@login_required\ndef AddSymbolAnalyze(request):\n\n symbols = request.GET.getlist('symbols[]')\n if symbols is not None:\n company_list = models.Company.objects.filter(id__in=symbols)\n for item in symbols:\n company = get_object_or_404(models.Company, pk=int(item))\n obj, created = models.RequestSymbol.objects.get_or_create(\n user=request.user,\n company=company,\n )\n else:\n return JsonResponse({'data': 'nothing to add'}, safe=False)\n return JsonResponse({'data': 'symbols added'}, safe=False)\n\n\nclass ListSymbolAnalyze(mixins.CreateModelMixin, generics.ListAPIView):\n lookup_field = 'pk' # slug, id # url(r'?P\\d+')\n serializer_class = serializers.ListSymbolSerializer\n permission_classes = [IsAuthenticated, ] # [IsOwnerOrReadOnly]\n # pagination_class = StandardResultsSetPagination\n\n def get_queryset(self):\n qs = []\n\n query_rem = self.request.GET.get(\"remove\")\n if query_rem is not None:\n models.RequestSymbol.objects.filter(id=query_rem).delete()\n return qs\n\n query = self.request.GET.get(\"q\")\n if query is not None:\n qs = models.RequestSymbol.objects.filter(\n Q(user=query)\n ).distinct()\n\n return qs\n\n\n\n@login_required\ndef AddPortfolio(request):\n\n symbols = request.GET.getlist('symbols[]')\n if symbols is not None:\n company_list = models.Company.objects.filter(id__in=symbols)\n for item in symbols:\n company = get_object_or_404(models.Company, pk=int(item))\n obj, created = models.StockPortfolio.objects.get_or_create(\n user=request.user,\n company=company,\n )\n else:\n return JsonResponse({'data': 'nothing to add'}, safe=False)\n return JsonResponse({'data': 'symbols added'}, safe=False)\n\n\nclass ListPortfolio(mixins.CreateModelMixin, generics.ListAPIView):\n lookup_field = 'pk' # slug, id # url(r'?P\\d+')\n serializer_class = serializers.ListStockPortfolio\n permission_classes = [IsAuthenticated, ] # [IsOwnerOrReadOnly]\n # pagination_class = StandardResultsSetPagination\n\n def get_queryset(self):\n qs = []\n\n query_rem = self.request.GET.get(\"remove\")\n if query_rem is not None:\n models.StockPortfolio.objects.filter(id=query_rem).delete()\n return qs\n\n query = self.request.GET.get(\"q\")\n if query is not None:\n qs = models.StockPortfolio.objects.filter(\n Q(user=query)\n ).distinct()\n\n return qs\n\n\n@api_view(['POST'])\ndef symbol_candle(request, company_name, time_frame):\n # date = request.data.getlist('date[]')\n candle = request.data\n # print(request.data)\n # json = loads(request.data)\n # print(json)\n if candle is not None:\n # print('company')\n company = get_object_or_404(models.Company, alias=company_name)\n # print(company)\n for itm in candle:\n if len(itm) > 0 and models.Candle.objects.filter(Q(dateTime=itm['date'])&Q(company=company)).exists() is False:\n # print(itm['date'])\n models.Candle.objects.create(\n open=itm['open']\n , close=itm['close']\n , high=itm['high']\n , low=itm['low']\n , volume=itm['vol']\n , company=company\n , timeFrame=time_frame\n , dateTime=itm['date']\n )\n\n profile_json = {\n \"data\": 'data recieved',\n }\n\n return JsonResponse(profile_json, safe=False)\n\nfrom django.db import models as md\n@api_view(['POST'])\n# def symbol_candle_file(request, company_name, time_frame, last_date):\ndef symbol_candle_file(request, company_name, time_frame, last_date):\n # print('request')\n # print(company_name)\n # print(time_frame)\n # print(last_date)\n # print(request.user)\n\n company = get_object_or_404(models.Company, alias=company_name)\n # print(company)\n\n chart = models.Chart.objects.filter(Q(timeFrame=time_frame) & Q(company=company))\n # new item\n if chart.exists() is False:\n models.Chart.objects.create(company=company\n , data=request.FILES['file']\n , timeFrame=time_frame\n , user=request.user\n , lastCandleDate=last_date)\n # update\n else:\n print('updated')\n # dummy_obj = models.Chart.objects.first()\n # dummy_obj.lastCandleDate = last_date\n # new_date = dummy_obj.lastCandleDate\n new_date = datetime.strptime(last_date, \"%Y-%m-%d\").date()\n chart = chart.first()\n chart_date = chart.lastCandleDate\n type(chart_date)\n type(new_date)\n print(chart_date, new_date)\n if new_date > chart_date:\n print('updated success')\n chart.lastCandleDate = last_date\n chart.data = request.FILES['file']\n chart.save()\n\n profile_json = {\n \"msg\": 'data recieved',\n \"symbol\": company_name,\n \"lastDate\": last_date,\n \"timeFrame\": time_frame,\n }\n\n return JsonResponse(profile_json, safe=False)\n\n\n@api_view(['POST'])\ndef symbol_candle_json(request, company_name, time_frame):\n # date = request.data.getlist('date[]')\n candle = request.data['jsonStr']\n last_date = request.data['lastdate']\n # print(request.data)\n # print(candle)\n # json = loads(request.data)\n\n # return JsonResponse({ \"data\": 'data recieved',}, safe=False)\n\n # print(json)\n if candle is not None and last_date is not None:\n print('company')\n company = get_object_or_404(models.Company, alias=company_name)\n print(company)\n candleJson = models.CandleJson.objects.filter(Q(timeFrame=time_frame)&Q(company=company))\n print(candleJson)\n\n if len(candleJson) == 0:\n # create new entry\n models.CandleJson.objects.create(company=company\n , timeFrame=time_frame\n , candleData=candle\n , lastCandleDate=last_date)\n else:\n # update las entry\n candleJson_u = candleJson[0]\n print(candleJson_u)\n candleJson_u.candleData = candle\n candleJson_u.lastCandleDate = last_date\n candleJson_u.save()\n # remove other entry\n cntr = 0\n for itm in candleJson:\n if cntr == 0:\n pass\n else:\n itm.delete()\n cntr = cntr + 1\n\n profile_json = {\n \"data\": 'data recieved',\n }\n\n return JsonResponse(profile_json, safe=False)\n\n\nclass SymbolCandleListAPIView(generics.ListAPIView): # DetailView CreateView FormView\n lookup_field = 'pk' # slug, id # url(r'?P\\d+')\n serializer_class = serializers.CandleSerializer\n permission_classes = [IsAuthenticated, ] # [IsOwnerOrReadOnly]\n\n def get_queryset(self):\n qs = []\n\n query = self.request.GET.get(\"company\")\n query_timeFrame = self.request.GET.get(\"timeFrame\")\n # query_last = self.request.GET.get(\"last\")\n if query is not None and query_timeFrame is not None:\n\n # if query_last is not None:\n # return models.Candle.objects.latest('pk')\n\n qs = models.Candle.objects.filter(\n Q(company=query)\n & Q(timeFrame=query_timeFrame)\n ).distinct()\n\n\n return qs\n\n\nclass SymbolCandleJsonListAPIView(generics.ListAPIView): # DetailView CreateView FormView\n lookup_field = 'pk'\n serializer_class = serializers.ChartSerializer\n permission_classes = [IsAuthenticated, ] # [IsOwnerOrReadOnly]\n\n def get_queryset(self):\n qs = []\n # qs = models.CandleJson.objects.all()\n\n query = self.request.GET.get(\"company\")\n # query_time_frame = self.request.GET.get(\"timeFrame\")\n # if query is not None and query_time_frame is not None:\n if query is not None:\n qs = models.Chart.objects.filter(\n Q(company=query)\n # & Q(timeFrame=query_time_frame)\n ).distinct()\n\n return qs\n\n\ndef SymbolListTitle(request):\n\n if request.GET.get(\"timeframe\") is not None:\n list_symbol_tf = models.Chart.objects.values('company__id', 'company__symbol', 'company__alias'\n , 'timeFrame', 'lastCandleDate').order_by('company__id')\n return JsonResponse(list(list_symbol_tf), safe=False)\n\n list_symbol = models.Chart.objects.values('company__id', 'company__symbol', 'company__alias')\\\n .order_by('company__id')\\\n .annotate(dcount=Count('company__id'))\\\n .distinct()\n # print(list_symbol)\n return JsonResponse(list(list_symbol), safe=False)\n","sub_path":"bourseapp/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":19078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"321347830","text":"from tkinter import Frame, Button, Listbox, Label, StringVar, Entry, END, Tk, ANCHOR, font, Text\nfrom backend import Database\nimport os\n\n\nclass QuestionOrganizer:\n\n def __init__(self):\n self.app = Tk()\n self.app.wm_title('Question Organizer')\n self.app.resizable(0, 0)\n # TODO: Frame1 is created\n frame1 = Frame(self.app, bg='#fff', width=200, height=800)\n frame1.grid(row=0, column=0, sticky='NN')\n frame1.grid_propagate(0)\n frame1.update()\n # TODO: refresh button\n refresh = Button(self.app, text='Refresh', bg='#fff', command=self.refresh)\n refresh.place(x=0, y=0)\n self.listbox = Listbox(self.app, width=200, height=800, font=14)\n self.listbox.bind('<>', self.on_select)\n self.listbox.place(x=0, y=28)\n list_del_btn = Button(self.app, text=\"Delete\", bg='#fff', command=self.list_delete)\n list_del_btn.place(x=50, y=0)\n for item in os.listdir():\n if item.endswith('.db'):\n self.listbox.insert(END, item)\n frame2 = Frame(self.app, bg='#f23', width=800, height=800)\n frame2.grid(row=0, column=1, sticky='NW')\n frame2.grid_propagate(0)\n frame2.update()\n self.listbox1 = Listbox(self.app, width=200, height=800, bg='#fff', font=14)\n self.listbox1.place(x=800, y=30)\n self.listbox1.bind('<>', self.on_select1)\n self.table = Label(self.app, text='Tables', font=20, bg='#fff')\n self.table.place(x=800, y=0, width=200)\n db_name = StringVar\n db_label = Label(self.app, text='Subject Name', bg='#f23')\n db_label.place(x=210, y=10)\n self.db_entry = Entry(self.app, textvariable=db_name, width=35)\n self.db_entry.place(x=300, y=10)\n db_btn = Button(self.app, text='Create', bg='#fff', command=self.create_db)\n db_btn.place(y=10, x=550)\n # TODO: Table Creation\n table_name = StringVar\n table_label = Label(self.app, text='Question Type', bg='#f23')\n table_label.place(x=210, y=50)\n self.table_entry = Entry(self.app, textvariable=table_name, width=35)\n self.table_entry.place(x=300, y=50)\n table_btn = Button(self.app, text='Create', bg='#fff', command=self.create_table)\n table_btn.place(y=50, x=550)\n\n self.app.mainloop()\n\n # TODO: function defined here:\n def create_db(self):\n self.database = Database(self.db_entry.get() + '.db')\n self.refresh()\n\n def create_table(self):\n self.database.create_table(self.table_entry.get())\n self.show_tables()\n\n def refresh(self):\n self.listbox.delete(0, END)\n for item in os.listdir():\n if item.endswith('.db'):\n self.listbox.insert(END, item)\n\n def list_delete(self):\n Database(self.listbox.get(0))\n os.remove(self.listbox.get(ANCHOR))\n self.listbox.delete(ANCHOR)\n\n def on_select(self, evt):\n w = evt.widget\n b = self.listbox.get(ANCHOR)\n self.table.config(text=b)\n self.database = Database(b)\n self.show_tables()\n\n def on_select1(self, evt):\n w = evt.widget\n data = self.listbox1.get(ANCHOR)\n\n t1 = Label(self.app, text=data.upper(), bg='#f23', font=font.Font(size=30), fg='#fff')\n t1.place(x=300, y=100, width=400, height=50)\n self.t1_text = Text(self.app)\n self.t1_text.place(x=300, y=150, width=400, height=500)\n t1_btn = Button(self.app, text='Save', command=self.insert_data)\n t1_btn.place(x=300, y=700, width=100, height=40)\n\n def insert_data(self):\n data = []\n tag = ['(a)', '(b)', '(c)', '(d)', '(e)', '(f)', '(g)', '(h)', '(i)', '(j)', '(k)', '(l)']\n d = self.t1_text.get('1.0', 'end')\n\n print(d.split('\\n'))\n\n def show_tables(self):\n self.listbox1.delete(0, END)\n for item in self.database.show_tables():\n self.listbox1.insert(END, item[0])\n\n\nif __name__ == \"__main__\":\n QuestionOrganizer()\n","sub_path":"Tkinter_project/Quesion_Organizer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"505860130","text":"arr = [2]\nfor i in range(2, 1000000):\n isPrime = True\n for j in arr:\n if i % j == 0:\n isPrime = False\n break\n if isPrime:\n arr.append(i)\nn = int(input())\nfor i in range(n):\n tmp = int(input())\n num = tmp\n res = []\n while tmp != 1:\n for j in arr:\n if tmp % j == 0:\n res.append(j)\n tmp = tmp // j\n break\n sum1 = 0\n for j in str(num):\n sum1 += int(j)\n sum2 = 0\n for j in res:\n for k in str(j):\n sum2 += int(k)\n if sum1 == sum2:\n print(1)\n else:\n print(0)\n","sub_path":"Code/CodeRecords/2588/49361/300419.py","file_name":"300419.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"108414367","text":"class Interval(object):\n\n def __init__(self, s=0, e=0):\n self.start = s\n self.end = e\n\n\nclass Solution(object):\n\n def merge(self, intervals):\n # skyline problem\n\n # corner case\n if len(intervals) == 0:\n return list()\n\n skyline = list()\n for interval in intervals:\n skyline.append((interval.start, 1))\n skyline.append((interval.end, 2))\n\n skyline.sort(key=lambda a: (a[0], a[1]))\n flying = 0\n start = skyline[0][0]\n ret = list()\n for (ele, status) in skyline:\n if status == 2:\n flying -= 1;\n if flying == 0:\n ret.append([start, ele])\n elif status == 1:\n if flying == 0:\n start = ele\n flying += 1\n return ret\n","sub_path":"line-sweep/merge intervals.py","file_name":"merge intervals.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"22286475","text":"import os\nimport re\nimport sys\nimport json\nimport time\nfrom os.path import join\nfrom os.path import dirname\nfrom os.path import basename\nfrom os.path import exists\nfrom urlparse import urlparse\nfrom collections import defaultdict\nimport xml.etree.ElementTree as ET\n\nfrom anadama.util import new_file\nfrom anadama.util import matcher\nfrom cutlass.aspera import aspera as asp\n\nfrom . import ssh\nfrom .serialize import indent\nfrom .serialize import to_xml\nfrom .util import reportnum\nfrom .update import print_report\n\ndef fsize(fname):\n return os.stat(fname).st_size\n\ndef parse_fasp_url(u):\n parsed = urlparse(u)\n return parsed.netloc, parsed. path\n\nidentity = lambda x: x\ndef groupby(keyfunc=identity, seq=[]):\n grouped = defaultdict(list)\n for item in seq:\n grouped[keyfunc(item)].append(item)\n return grouped\n\ndef _sequences(sample_records):\n def _s():\n for sample in sample_records:\n for prep, seq in sample.prepseqs:\n yield seq\n\n grouped = groupby(lambda s: s.urls[0], _s())\n return [ grp[0] for grp in grouped.itervalues() ]\n\n\nclass Bag(object):\n pass\n\nfind_file = lambda n, h: matcher.find_match(n,h, kmer_lengths=(2,3))\n_hash = lambda v: \"{}{}\".format(0 if v < 0 else 1, abs(hash(v)))\n\nclass MyDict(dict):\n id = None\n\ndef gen_samples_seqs(study, metadata, seqinfo, files):\n with open(metadata, 'r') as f:\n recs = json.load(f)\n with open(seqinfo, 'r') as f:\n seqinfo = json.load(f)\n samples_seqs = list()\n for rec in recs:\n seq = Bag()\n seq.path = os.path.abspath(find_file(rec['SampleID'], files))\n seq.seq_model = seqinfo['seq_model']\n seq.lib_const = seqinfo['lib_const']\n seq.method = seqinfo['method']\n seq.id = study.id+\":seq:\"+_hash(basename(seq.path))\n sample = MyDict(rec)\n sample.id = study.id+\":sample:\"+_hash(rec['SampleID'])\n samples_seqs.append((sample, seq))\n return samples_seqs\n \n\ndef serialize(study_json, qiime_metadata, seqinfo_16s, files_16s,\n wgs_metadata, seqinfo_wgs, files_wgs, submission_fname,\n ready_fname, products_dir):\n\n def _write_xml():\n with open(study_json) as f:\n st = json.load(f)\n study = Bag()\n study.name = st['name']\n study.description = st['description']\n study.id = _hash(study.name)\n samples_seqs = gen_samples_seqs(study, qiime_metadata,\n seqinfo_16s, files_16s)\n samples_seqs += gen_samples_seqs(study, wgs_metadata,\n seqinfo_wgs, files_wgs)\n xml = to_xml(study, samples_seqs)\n indent(xml)\n et = ET.ElementTree(xml)\n et.write(submission_fname)\n\n yield {\n \"name\": \"serialize:xml: \"+submission_fname,\n \"actions\": [_write_xml],\n \"file_dep\": [qiime_metadata, wgs_metadata],\n \"targets\": [submission_fname]\n }\n\n yield {\n \"name\": \"serialize:ready_file: \"+ready_fname,\n \"actions\": [lambda *a, **kw: open(ready_fname, 'w').close()],\n \"file_dep\": [],\n \"targets\": [ready_fname]\n }\n\n\ndef upload(files_16s, files_wgs, sub_fname, ready_fname, keyfile,\n remote_path, remote_srv, user, products_dir):\n \"\"\"Upload raw sequence files and xml.\n\n :param keyfile: String; absolute filepath to private SSH keyfile for\n access to NCBI's submission server\n\n :param remote_path: String; the directory on the NCBI submission\n server where to upload data. If unset, the remote_path is\n automatically determined.\n\n :param remote_srv: String; TLD of NCBI's submission server\n\n :param user: String; username used to access NCBI's submission server\n\n \"\"\"\n\n to_upload = [ f for f in list(files_16s)+list(files_wgs)\n if not f.endswith(\".complete\") ]\n ssh_session = ssh.SSHConnection(user, remote_srv, keyfile, remote_path)\n uptodate = [ssh_session.uptodate]\n\n def _upload(local_fname, complete_fname, blithely=False):\n def _u():\n with open(sub_fname, 'r') as f:\n b = basename(local_fname)\n if b not in (\"submission.xml\", \"submit.ready\") \\\n and b not in f.read():\n return\n ret = asp.upload_file(remote_srv, user, None, local_fname,\n remote_path, keyfile=keyfile)\n if blithely or ret:\n open(complete_fname, 'w').close()\n return blithely or ret # return True if blithely is True\n return _u\n\n complete_fnames = [f+\".complete\" for f in to_upload\n if not f.endswith(\".complete\")]\n for f, complete_fname in zip(to_upload, complete_fnames):\n yield {\n \"name\": \"upload: \"+basename(f),\n \"actions\": [_upload(f, complete_fname)],\n \"file_dep\": [f],\n \"uptodate\": uptodate,\n \"targets\": [complete_fname]\n }\n\n yield {\n \"name\": \"upload: \"+basename(sub_fname),\n \"actions\": [_upload(sub_fname, sub_fname+\".complete\")],\n \"file_dep\": complete_fnames,\n \"targets\": [sub_fname+\".complete\"]\n }\n\n yield {\n \"name\": \"upload: \"+basename(ready_fname),\n \"actions\": [_upload(ready_fname, ready_fname+\".complete\", True)],\n \"file_dep\": complete_fnames+[sub_fname+\".complete\"],\n \"targets\": [ready_fname+\".complete\"]\n }\n\n\ndef report(ready_complete_fname, user, remote_srv, remote_path,\n keyfile):\n reports_dir = dirname(ready_complete_fname)\n def _download():\n c = ssh.SSHConnection(user, remote_srv, keyfile, remote_path)\n for _ in range(60*20*2): # 20 minutes in half-seconds\n report_fnames = [basename(n) for n in c.files()\n if re.search(r'report\\.[\\d.]*xml', n)\n and not exists(join(reports_dir, basename(n)))]\n if report_fnames:\n break\n else:\n time.sleep(.5)\n for n in report_fnames:\n if exists(join(reports_dir, n)):\n continue\n asp.download_file(remote_srv, user, None, join(remote_path, n),\n reports_dir, keyfile=keyfile)\n if not report_fnames:\n print >> sys.stderr, \"Timed out waiting for report xml files.\"\n return False\n most_recent_report = max(report_fnames, key=reportnum)\n print_report(join(reports_dir, most_recent_report))\n\n yield {\n \"name\": \"report:get_reports\",\n \"actions\": [_download],\n \"file_dep\": [ready_complete_fname],\n \"uptodate\": [False],\n \"targets\": [],\n }\n \n\n\n","sub_path":"envi_sra/workflows.py","file_name":"workflows.py","file_ext":"py","file_size_in_byte":6715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"325733057","text":"def index(textfile, list):\n try:\n infile = open(textfile)\n lines = infile.readlines()\n infile.close()\n\n print('{} and {}'.format(lines, list))\n except IOError:\n print('File {} not found'.format(textfile))\n\nindex('../Files/raven.txt', ['hello', 'goodbye'])\n","sub_path":"Les 9/Perkovic Exercises/p7.16.py","file_name":"p7.16.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"394347910","text":"\nfrom django.conf.urls import include, url\nfrom django.views.static import serve\nfrom django.contrib import admin\nfrom AppAparcamientos import views\nfrom django.contrib.auth.views import login, logout\nfrom proyectoAparcamientos import settings\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'static/(?P.*)$', serve, {'document_root': settings.URL_INICIAL}),\n url(r'css/(.+)$', views.css, name=\"Cargar el documento CSS\"),\n url(r'^$',views.inicio, name = \"Página principal del sitio\"),\n url(r'^about/$',views.about, name = \"Página de información\"),\n url(r'^(.*)/xml$', views.xml_inicio, name = \"XML de la página principal del sitio\"),\n url(r'^aparcamientos/$', views.pagina_aparcamientos, name = \"Página sobre todos los aparcamientos\"),\n url(r'^aparcamientos/(\\d+)$',views.pagina_aparcamiento, name = \"Página de un aparcamiento\"),\n url(r'^login', views.milogin),\n url(r'^logout', logout, {'next_page': '/'}),\n url(r'^register/$', views.register, name = \"Crear un usuario\"),\n url(r'^(.+)$', views.page_usu, name = \"Pagina personal del usuario\"),\n]\n","sub_path":"proyectoAparcamientos/proyectoAparcamientos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"85857974","text":"from django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.decorators import api_view\nfrom errorPages.views import onlyForStaffChecker\nfrom tag.models import Tag\n\n\n@csrf_exempt\n@api_view(['GET', 'POST'])\n@onlyForStaffChecker\ndef createTags(request):\n body = request.data\n print(body)\n for x in body[\"params\"][\"tags\"]:\n Tag.init(tag=x)\n response = JsonResponse({\n \"result\": \"OK\",\n })\n response.status_code = 200\n return response\n\n\n\n@csrf_exempt\n@api_view(['GET', 'POST'])\n@onlyForStaffChecker\ndef getListOfTags(request):\n response = JsonResponse({\n \"result\": \"GotOut\",\n \"data\": [{\"id\": x.id, \"tag\": x.tag} for x in Tag.objects.filter()[::-1]],\n })\n response.status_code = 200\n return response\n","sub_path":"server/tag/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"419027675","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 10 19:05:37 2020\n\n@author: pratms\n\"\"\"\nimport bs4,requests\n#import lxml\nimport urllib3\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\ntry: \n from googlesearch import search \nexcept ImportError: \n print(\"No module named 'google' found\") \n \n# to search \nimport openpyxl\n\nimport random\n\npath=r\"C:\\Users\\pratms\\pythonprojects\\webscrapping\\webscrapping_medium_top_10\\excel_doc1.xlsx\"\n\nwb_obj=openpyxl.load_workbook(path)\nsheet_obj=wb_obj.active\nm_row=sheet_obj.max_row\nprint(\"rows=\"+str(m_row))\nfor i in range(1,m_row+1):\n bookname=sheet_obj.cell(row=i,column=2).value\n bookauthor=sheet_obj.cell(row=i,column=3).value\n searchPhrase=bookname+\" by \"+bookauthor+\" goodreads\"\n #searchPhrase=\"Catch-22 by Joseph Heller in good reads\"\n print(searchPhrase)\n#searchPhrase=\"1984 by George Orwell in goodreads\" \n print(searchPhrase) \n for j in search(searchPhrase, tld=\"com\", num=10, stop=1, pause=random.randint(1,20)): \n goodreadsurl=j\n print(goodreadsurl)\n print(\"bs4 starting\")\n res=requests.get(goodreadsurl,verify=False)\n res.raise_for_status()\n soup=bs4.BeautifulSoup(res.text,'lxml')\n ratingObj=soup.find(\"span\", itemprop=\"ratingValue\")\n rating=ratingObj.getText()\n print(\"ratinng of\",bookname,bookauthor, rating)\n sheet_obj.cell(row=i,column=4).value=str(rating)\n print(\"rating write complete\")\nwb_obj.save(r\"C:\\Users\\pratms\\pythonprojects\\webscrapping\\webscrapping_medium_top_10\\excel_doc1.xlsx\")\nprint(\"excel saved\")","sub_path":"finding_book_rating.py","file_name":"finding_book_rating.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"113026155","text":"#1、写一个函数:获取用户输入的名字(name)和年龄(age),计算一下该用户到哪一年(返回值)为100岁,并打印结果”{用户名字}在XXXX年为100岁”\r\ndef user():\r\n name=input('your name:')\r\n age=int(input('your age:'))\r\n year=2018+100-age\r\n r=f'{name}在{year}年为100岁'\r\n print(r)\r\n return year\r\n\r\nuser()\r\n\r\n\r\n#2、写一个函数:获取用户输入的整数,如果它是奇数则打印”您输入的是奇数”,如果是偶数则打印”您输入的是偶数”\r\ndef get():\r\n num=int(input(\"请输入一个整数:\"))\r\n if num % 2 == 0:\r\n print(\"你输入的是偶数\")\r\n else:\r\n print(\"你输入的是奇数\")\r\n\r\nget()\r\n\r\n#3、写一个函数:输入参数是一个list,判断该list中是否有空对象(至少用三种方法实现)\r\ndef three1(lst):\r\n if lst == []:\r\n print(\"列表中没有元素\")\r\n for a in lst:\r\n if not bool(a):\r\n print(\"有空对象\")\r\n return True\r\n else:\r\n pass\r\n print(\"没有空对象\")\r\n return False\r\n\r\nthree1([0, 1, 2, 3])\r\nthree1([1, 2, 3])\r\n\r\ndef three2(lst):\r\n y = lambda x: bool(x)\r\n for x in lst:\r\n b = y(x)\r\n if not b:\r\n print(\"有空对象\")\r\n return True\r\n else:\r\n pass\r\n print(\"没有空对象\")\r\n return False\r\n\r\nthree2([0, 1, 2, 3])\r\nthree2([1, 2, 3])\r\n\r\ndef three3(lst1):\r\n all(lst1) == True\r\n if all(lst1):\r\n print(\"没有空对象\")\r\n return False\r\n else:\r\n print(\"有空对象\")\r\n return True\r\n\r\nthree3([0, 1, 2, 3])\r\nthree3([1, 2, 3])\r\n\r\n#4、写一个函数:输入参数是一个整数列表,把该列表中每个整数都平方后返回新的列表(至少用两种方法实现)\r\n\r\ndef double(lst):\r\n lst1=[x*x for x in lst]\r\n return lst1\r\n\r\ndouble([2,4,3])\r\n\r\ndef double1(lst):\r\n lst1=map(lambda x:x*x,lst)\r\n return list(lst1)\r\n\r\ndouble1([2,4,3])\r\n\r\n#5、写一个函数:输入参数是一个整数列表,使用 reduce 函数实现求和后返回结果\r\nfrom functools import reduce\r\nreduce(lambda x,y:x+y,[1,2,3])\r\n\r\n\r\n#6、写一个函数:请用列表推导式实现开方\r\ndef cube(lst):\r\n return [x*x*x for x in lst]\r\n\r\ncube([1,2,3])\r\n\r\n#7、写一个函数:输入参数是两个 list,请返回它们的共同元素所组成的新列表\r\ndef new(lst1,lst2):\r\n lst3=list(set(lst1).intersection(set(lst2)))\r\n return lst3\r\n\r\nlst1=['a','b','l']\r\nlst2=['a','b','c']\r\nnew(['a','b','l'],['a','b','c'])\r\n\r\n#8、写一个函数:找出三个整数中的最大数(至少用两种方法实现)\r\ndef Max(a,b,c):\r\n return max(a,b,c)\r\n\r\nMax(2,3,5)\r\n\r\ndef Max1(a,b,c):\r\n if a>b:\r\n max=a\r\n else:\r\n max=b\r\n if c>max:\r\n max=c\r\n return max\r\n\r\nMax1(5,7,6)","sub_path":"week3_class_room.py","file_name":"week3_class_room.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"154456473","text":"# -*- coding: utf-8 -*-\nimport theano\nimport theano.tensor as T\n\nimport activations, initializations\nfrom utils.theano_utils import shared_zeros, floatX\nfrom utils.generic_utils import make_tuple\n\nfrom theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams\nsrng = RandomStreams()\n\nclass Layer(object):\n def connect(self, previous_layer):\n self.previous_layer = previous_layer\n\n def output(self, train):\n raise NotImplementedError\n\n def get_input(self, train):\n if hasattr(self, 'previous_layer'):\n return self.previous_layer.output(train=train)\n else:\n return self.input\n\n def set_weights(self, weights):\n for p, w in zip(self.params, weights):\n p.set_value(floatX(w))\n\n def get_weights(self):\n weights = []\n for p in self.params:\n weights.append(p.get_value())\n return weights\n\n\nclass Dropout(Layer):\n '''\n Hinton's dropout. \n '''\n def __init__(self, p):\n self.p = p\n self.params = []\n\n def output(self, train):\n X = self.get_input(train)\n if self.p > 0.:\n retain_prob = 1. - self.p\n if train:\n X *= srng.binomial(X.shape, p=retain_prob, dtype=theano.config.floatX)\n else:\n X *= retain_prob\n return X\n\n\nclass Activation(Layer):\n '''\n Apply an activation function to an output.\n '''\n def __init__(self, activation):\n self.activation = activations.get(activation)\n self.params = []\n\n def output(self, train):\n X = self.get_input(train)\n return self.activation(X)\n\n\nclass Reshape(Layer):\n '''\n Reshape an output to a certain shape.\n Can't be used as first layer in a model (no fixed input!)\n First dimension is assumed to be nb_samples.\n '''\n def __init__(self, *dims):\n self.dims = dims\n self.params = []\n\n def output(self, train):\n X = self.get_input(train)\n nshape = make_tuple(X.shape[0], *self.dims)\n return theano.tensor.reshape(X, nshape)\n\n\nclass Flatten(Layer):\n '''\n Reshape input to flat shape.\n First dimension is assumed to be nb_samples.\n '''\n def __init__(self, size):\n self.size = size\n self.params = []\n\n def output(self, train):\n X = self.get_input(train)\n nshape = (X.shape[0], self.size)\n return theano.tensor.reshape(X, nshape)\n\n\nclass RepeatVector(Layer):\n '''\n Repeat input n times.\n\n Dimensions of input are assumed to be (nb_samples, dim).\n Return tensor of shape (nb_samples, n, dim).\n '''\n def __init__(self, n):\n self.n = n\n self.params = []\n\n def output(self, train):\n X = self.get_input(train)\n tensors = [X]*self.n\n stacked = theano.tensor.stack(*tensors)\n return stacked.dimshuffle((1,0,2))\n\n\nclass Dense(Layer):\n '''\n Just your regular fully connecter NN layer.\n '''\n def __init__(self, input_dim, output_dim, init='uniform', activation='linear', weights=None):\n self.init = initializations.get(init)\n self.activation = activations.get(activation)\n self.input_dim = input_dim\n self.output_dim = output_dim\n\n self.input = T.matrix()\n self.W = self.init((self.input_dim, self.output_dim))\n self.b = shared_zeros((self.output_dim))\n\n self.params = [self.W, self.b]\n\n if weights is not None:\n self.set_weights(weights)\n\n def output(self, train):\n X = self.get_input(train)\n output = self.activation(T.dot(X, self.W) + self.b)\n return output\n\n\nclass Embedding(Layer):\n '''\n Turns a list of integers into a dense vector of fixed size. \n eg. [4, 50, 123, 26] -> [0.25, 0.1]\n\n @input_dim: size of vocabulary (highest input integer + 1)\n @out_dim: size of dense representation\n '''\n def __init__(self, input_dim, output_dim, init='uniform', weights=None):\n self.init = initializations.get(init)\n self.input_dim = input_dim\n self.output_dim = output_dim\n\n self.input = T.imatrix()\n self.W = self.init((self.input_dim, self.output_dim))\n self.params = [self.W]\n\n if weights is not None:\n self.set_weights(weights)\n\n def output(self, train):\n X = self.get_input(train)\n return self.W[X]\n\n","sub_path":"layers/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"420988003","text":"\"\"\"Accepts human input via MQTT or IR remote for drive and arm functions. When complete, the beacon button on the IR\n remote will repeat the human input autonomously. If an object presents itself that was not in the original path the\n robot will move it out of the way and resume driving.\"\"\"\n\nimport robot_controller_noursecw as robo\nimport ev3dev.ev3 as ev3\nimport mqtt_remote_method_calls as com\n\n\nclass DataContainer(object):\n \"\"\" Helper class that might be useful to communicate between different callbacks.\"\"\"\n\n def __init__(self):\n self.running = True\n\n\ndef main():\n robot = robo.Snatch3r()\n mqtt_client = com.MqttClient(robot)\n mqtt_client.connect_to_pc()\n dc = DataContainer()\n # mqtt_client.connect_to_pc(\"35.194.247.175\") # Off campus IP address of a GCP broker\n rc1 = ev3.RemoteControl(channel=1)\n while not rc1.beacon:\n robot.loop_forever() # Calls a function that has a while True: loop within it to avoid letting the program end.\n if rc1.beacon:\n robot.shutdown()\n break\n if rc1.beacon:\n print(\"beacon\")\n robot.memory_replay()\n robot.shutdown()\n\n\ndef mqtt_control():\n robot = robo.Snatch3r()\n mqtt_client = com.MqttClient(robot)\n mqtt_client.connect_to_pc()\n # mqtt_client.connect_to_pc(\"35.194.247.175\") # Off campus IP address of a GCP broker\n robot.loop_forever() # Calls a function that has a while True: loop within it to avoid letting the program end.\n\n\ndef play_note(color):\n \"\"\"takes a color (type = int) and plays a note. Returns nothing.\"\"\"\n freqs = [130.81, 146.83, 164.81, 196, 220, 261.63] # major pentatonic, C3-C4\n if color == ev3.ColorSensor.COLOR_RED:\n ev3.Sound.tone(freqs[1])\n elif color == ev3.ColorSensor.COLOR_YELLOW:\n ev3.Sound.tone(freqs[2])\n elif color == ev3.ColorSensor.COLOR_GREEN:\n ev3.Sound.tone(freqs[3])\n elif color == ev3.ColorSensor.COLOR_BLUE:\n ev3.Sound.tone(freqs[4])\n elif color == ev3.ColorSensor.COLOR_BROWN:\n ev3.Sound.tone(freqs[5])\n elif color == ev3.ColorSensor.COLOR_BLACK:\n ev3.Sound.tone(freqs[6])\n\n\nmain()\n","sub_path":"projects/noursecw/ev3_project.py","file_name":"ev3_project.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"589856308","text":"####################################################\n# Author: Tyler Daddio #\n# Date: August 6, 2017 #\n# File: tcrtypes.py #\n# About: Defines types with named fields. #\n####################################################\n\nfrom math import factorial\n\ndef nCr(n,r):\n\t\"\"\" Computes n choose r \"\"\"\n\tif r > n or r < 0:\n\t\treturn 0\n\treturn factorial(n) // factorial(r) // factorial(n-r)\n\ndef pair_probability (W, wa, wb, wab):\n\tif W-wa < wb-wab:\n\t\treturn 0\n\treturn nCr(W, wab) * nCr(W-wab, wa-wab) * nCr(W-wa, wb-wab) / nCr(W, wa) / nCr(W, wb)\n\nclass UIS:\n\t\"\"\" Stores and permits manipulation of data stored in UIS files \"\"\"\n\tdef __init__ (self, ws2cid):\n\t\tself.ws2cid = ws2cid\n\t\tcid2ws = {}\n\t\tfor ws in ws2cid:\n\t\t\tcid = ws2cid[ws]\n\t\t\tcid2ws[cid[0]] = ws\n\t\t\tif not self.is_single(ws):\n\t\t\t\tcid2ws[cid[1]] = ws\n\t\tself.cid2ws = cid2ws\n\t\tself.numuis = len(self.ws2cid)\n\t\n\tdef is_single (self, ws):\n\t\treturn self.ws2cid[ws][0] == self.ws2cid[ws][1]\n\t\n\tdef has_cid (self, cid):\n\t\treturn str(cid) in self.cid2ws\n\t\n\tdef has_ws (self, ws):\n\t\treturn ws in self.ws2cid\n\t\n\tdef cid_to_ws (self, cid):\n\t\treturn self.cid2ws[str(cid)]\n\t\n\tdef ws_to_cid (self, ws):\n\t\treturn self.ws2cid[ws]\n\t\n\tdef num_uis (self):\n\t\treturn self.numuis\n\t\n\t@classmethod\n\tdef from_file (cls, f):\n\t\tuisdat = {}\n\t\tfor ln in f:\n\t\t\tif ln[0] != '#':\n\t\t\t\tdat = ln.rstrip().split(\",\")\n\t\t\t\tws = int(dat[0])\n\t\t\t\tseqs = dat[1:]\n\t\t\t\t# If length 1, duplicate value to get correct format\n\t\t\t\tif len(seqs) == 1:\n\t\t\t\t\tseqs = [seqs[0], seqs[0]]\n\t\t\t\tuisdat[ws] = seqs\n\t\treturn UIS(uisdat)\n\nclass FlowArc:\n\t\"\"\" A simple class describing an arc from a FLOW file \"\"\"\n\tdef __init__ (self, srcws, snkws, srccap, snkcap, weight, flow):\n\t\tself.srcws = srcws\n\t\tself.snkws = snkws\n\t\tself.srccap = srccap\n\t\tself.snkcap = snkcap\n\t\tself.weight = weight\n\t\tself.flow = flow\n\nclass FLOW:\n\t\"\"\" Stores and permits manipulation of data stored in FLOW files \"\"\"\n\tdef __init__ (self, arcs):\n\t\tself.arcs = arcs\n\t\n\t@classmethod\n\tdef from_file (cls, f):\n\t\t\"\"\" Creates a FLOW object from a file \"\"\"\n\t\tarcs = []\n\t\tfor ln in f:\n\t\t\tif ln[0] != '#':\n\t\t\t\tsrccap,snkcap,srcws,snkws,weight,flow = [int(x) for x in ln.rstrip().split(\",\")]\n\t\t\t\tarc = FlowArc(srcws, snkws, srccap, snkcap, weight, flow)\n\t\t\t\tarcs.append(arc)\n\t\treturn FLOW(arcs)\n\nclass OFVF:\n\t\"\"\" Stores and permits manipulation of data stored in OFVFs \"\"\"\n\tdef __init__ (self, K, M, F, classes):\n\t\tself.K = K\n\t\tself.M = M\n\t\tself.F = F\n\t\tself.classes = classes\n\t\n\t@classmethod\n\tdef from_file (cls, f):\n\t\t\"\"\" Loads OFVF data from a file and returns a new OFVF object \"\"\"\n\t\tdat = [int(x) for x in f.readline().rstrip().split(\",\")]\n\t\tK = dat[0]\n\t\tszs = []\n\t\tfor i in range(1, K+1):\n\t\t\tszs.append(dat[i])\n\t\tM = dat[K+1]\n\t\tF = dat[K+2]\n\t\tclasses = [[] for i in range(0, K)]\n\t\tfor i in range(0, K):\n\t\t\tfor j in range(0, szs[i]):\n\t\t\t\tdat = [int(x) for x in f.readline().rstrip().split(\",\")[1:]]\n\t\t\t\tcapacity = dat[0]\n\t\t\t\twells = tuple(dat[1:])\n\t\t\t\tclasses[i].append( WellSet(capacity, wells) )\n\t\treturn OFVF(K, M, F, classes)\n\t\n\tdef add_wellset (self, k, capacity, wells):\n\t\t\"\"\" Adds a WellSet to the specified class \"\"\"\n\t\tself.classes[k].append( WellSet(capacity, wells) )\n\t\n\tdef save_to_file (self, f):\n\t\t\"\"\" Saves the data in this OFVF to the given file f \"\"\"\n\t\t# Write header\n\t\tf.write(\"{}\".format(self.K))\n\t\tfor k in range(0, self.K):\n\t\t\tf.write(\",{}\".format(len(self.classes[k])))\n\t\tf.write(\",{},{},0\\n\".format(self.M, self.F))\n\t\t# Write well set data\n\t\tfor k in range(0, self.K):\n\t\t\tcls = self.classes[k]\n\t\t\tfor i in range(0, len(cls)):\n\t\t\t\tws = cls[i]\n\t\t\t\tf.write(\"{},{}\".format(len(ws.wells), ws.capacity))\n\t\t\t\tfor j in range(0, len(ws.wells)):\n\t\t\t\t\tf.write(\",{}\".format(ws.wells[j]))\n\t\t\t\tf.write(\"\\n\")\n\nclass WellSet:\n\t\"\"\" Stores data for a well set loaded from an OFVF \"\"\"\n\tdef __init__ (self, capacity, wells):\n\t\tself.capacity = capacity\n\t\tself.wells = wells\n\nclass CLONES:\n\t\"\"\" Stores and permits manipulation of data stored in CLONES files \"\"\"\n\tdef __init__ (self, clones):\n\t\tself.clones = clones\n\t\tself.lookup = {}\n\t\tfor c in self.clones:\n\t\t\tself.lookup[tuple([c.snk1, c.snk2, c.src1, c.src2])] = c\n\t\n\tdef contains (self, snk1, snk2, src1, src2):\n\t\tif snk1 > snk2:\n\t\t\ttemp = snk1\n\t\t\tsnk1 = snk2\n\t\t\tsnk2 = temp\n\t\tif src1 > src2:\n\t\t\ttemp = src1\n\t\t\tsrc1 = src2\n\t\t\tsrc2 = temp\n\t\treturn tuple([snk1, snk2, src1, src2]) in self.lookup\n\t\n\tdef cut(self, length):\n\t\tif len(self.clones) > length:\n\t\t\tself.clones = self.clones[:length]\n\t\t\tself.lookup = {}\n\t\t\tfor c in self.clones:\n\t\t\t\tself.lookup[tuple([c.snk1, c.snk2, c.src1, c.src2])] = c\n\t\n\tdef save_to_file (self, f):\n\t\t\"\"\" Saves the data in this CLONES object to the given file \"\"\"\n\t\tf.write(\"\\\"\\\",beta1,beta2,alpha1,alpha2,beta ws,alpha ws,weight,p\\n\")\n\t\tself.clones.sort(key = lambda c: c.probability, reverse = False)\n\t\tfor i in range(0, len(self.clones)):\n\t\t\tc = self.clones[i]\n\t\t\tf.write(\"{},{},{},{},{},{},{},{},{}\\n\".format(i, \n\t\t\t\tc.snk1, c.snk2, c.src1, c.src2,\n\t\t\t\t\";\".join(str(x) for x in c.snkws), \n\t\t\t\t\";\".join(str(x) for x in c.srcws), \n\t\t\t\tc.weight, c.probability))\n\t\n\t@classmethod\n\tdef from_file (cls, f):\n\t\t\"\"\" Creates a new CLONES object by loading it from a file \"\"\"\n\t\tclones = []\n\t\tf.readline() # ignore header\n\t\tfor ln in f:\n\t\t\tif ln.isspace():\n\t\t\t\tcontinue\n\t\t\ti, snk1, snk2, src1, src2 = [int(x) for x in ln.rstrip().replace(\"\\\"\",\"\").split(\",\")[:5]]\n\t\t\tclones.append( Clone(snk1, snk2, src1, src2, None, None, -1, -1, -1, -1) )\n\t\treturn CLONES(clones)\n\t\n\t@classmethod\n\tdef from_FLOW (cls, flowdat, W, srccls, snkcls, srcuis, snkuis):\n\t\t\"\"\" Creates a new CLONES object by converting the given FLOW data into clones \"\"\"\n\t\tclones = []\n\t\tfor flow in flowdat.arcs:\n\t\t\tif not(flow.srccap == 1 and flow.snkcap == 1):\n\t\t\t\tcontinue\n\t\t\ts = flow.srcws\n\t\t\tt = flow.snkws\n\t\t\tsrc = srcuis.ws_to_cid(s)\n\t\t\tsnk = snkuis.ws_to_cid(t)\n\t\t\t\n\t\t\tsrcws = tuple(srccls[s].wells)\n\t\t\tsnkws = tuple(snkcls[t].wells)\n\t\t\twa = len(srcws)\n\t\t\twb = len(snkws)\n\t\t\twab = len(set(srcws) & set(snkws))\n\t\t\tp = pair_probability(W, wa, wb, wab)\n\t\t\t\n\t\t\tclones.append( Clone(snk[0], snk[1], src[0], src[1], snkws, srcws, s, t, flow.weight, p) )\n\t\treturn CLONES(clones)\n\nclass Clone:\n\t\"\"\" Stores information about a CLONE \"\"\"\n\tdef __init__(self, snk1, snk2, src1, src2, snkws, srcws, s, t, weight, probability):\n\t\tif snk1 > snk2:\n\t\t\ttemp = snk1\n\t\t\tsnk1 = snk2\n\t\t\tsnk2 = temp\n\t\tif src1 > src2:\n\t\t\ttemp = src1\n\t\t\tsrc1 = src2\n\t\t\tsrc2 = temp\n\t\tself.snk1 = snk1\n\t\tself.snk2 = snk2\n\t\tself.src1 = src1\n\t\tself.src2 = src2\n\t\tself.snkws = snkws\n\t\tself.srcws = srcws\n\t\tself.s = s\n\t\tself.t = t\n\t\tself.weight = weight\n\t\tself.probability = probability\n\t\n\tdef is_src_single (self):\n\t\treturn self.src1 == self.src2\n\t\n\tdef is_snk_single (self):\n\t\treturn self.snk1 == self.snk2\n\ndef add_join_wellsets (ofvf, k, uis, i, j):\n\t\"\"\"\n\tCombines the i-th and j-th well sets in the\n\tk-th class in the given OFVF and adds the new\n\tdual well set record to both the OFVF and the\n\tgiven UIS.\n\t\"\"\"\n\tcls = ofvf.classes[k]\n\tws = list(set(cls[i].wells) | set(cls[j].wells))\n\tws.sort()\n\tidx = len(cls)\n\tif not(uis.has_ws(i) and uis.has_ws(j)):\n\t\treturn\n\tcid1 = uis.ws_to_cid(i)\n\tcid2 = uis.ws_to_cid(j)\n\tuis.ws2cid[idx] = [cid1[0], cid2[0]]\n\tofvf.add_wellset(k, 1, tuple(ws))\n\tuis.numuis += 1\n\ndef intersection_normals (W):\n\t\"\"\"\n\tComputes expected normal distributions describing the size\n\tof the expected size of the intersection between two\n\trandomly chosen well sets of given sizes.\n\t\"\"\"\n\tE = [[0 for i in range(W+1)] for j in range(W+1)] # expected values\n\tS = [[0 for i in range(W+1)] for j in range(W+1)] # standard deviations\n\tfor i in range(0, W):\n\t\tfor j in range(i, W):\n\t\t\tE[i][j] = (i / W) * j\n\t\t\tE[j][i] = E[i][j]\n\t\t\tVar = (i/W) * ((W-i)/(W-1)) * (j - (1/W)*j*j)\n\t\t\tS[i][j] = sqrt(Var)\n\t\t\tS[j][i] = S[i][j]\n\treturn [E, S]\n\ndef minhash (cls1, cls2, uis1, uis2, minsim, maxsim, removeduals=True):\n\t\"\"\"\n\tComposes a list of arcs representing a pairwise similarity\n\tin the specified range. Arcs are grouped by the node in\n\tthe first class as the second is used as the database into\n\twhich queries from the first class are performed.\n\t\"\"\"\n\tarcs = [[] for x in range(len(cls1))]\n\tfor i in range(0, len(cls1)):\n\t\tif (removeduals and cls1[i].capacity == 1 and uis1.is_single(i)) or cls1[i].capacity == 1:\n\t\t\tws1 = set(cls1[i].wells)\n\t\t\t# If self-searching a class, skip some indexing\n\t\t\tif cls1 is cls2:\n\t\t\t\tlow = i+1\n\t\t\telse:\n\t\t\t\tlow = 0\n\t\t\tfor j in range(low, len(cls2)):\n\t\t\t\tif (removeduals and cls2[j].capacity == 1 and uis2.is_single(j)) or cls2[j].capacity == 1:\n\t\t\t\t\tws2 = set(cls2[j].wells)\n\t\t\t\t\t# Compute jaccard similarity of well sets\n\t\t\t\t\tunin = ws1 | ws2\n\t\t\t\t\tisct = ws1 & ws2\n\t\t\t\t\tsim = len(isct) / len(unin)\n\t\t\t\t\tif sim > minsim and sim <= maxsim:\n\t\t\t\t\t\tarcs[i].append(j)\n\treturn arcs\n","sub_path":"analysis/tcrtypes.py","file_name":"tcrtypes.py","file_ext":"py","file_size_in_byte":8767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"80607343","text":"import collections\n\nfrom lxml import etree\n\n\nclass Project:\n def __init__(self, _input):\n self.sources = collections.OrderedDict()\n self.postprocesses = collections.OrderedDict()\n\n parser = etree.XMLParser(remove_blank_text=True)\n self._projectTree = etree.parse(_input, parser)\n\n for source_elem in self._projectTree.xpath('/project/sources/source'):\n self.sources[source_elem.attrib['name']] = Source(source_elem)\n\n for postprocess_elem in self._projectTree.xpath('/project/post-processing/post-process'):\n self.postprocesses[postprocess_elem.attrib['name']] = PostProcess(postprocess_elem)\n\n\nclass Source:\n def __init__(self, elem):\n attrib = elem.attrib\n\n self.name = attrib['name']\n self.type = attrib['type']\n\n if 'dump' in attrib:\n self.dump = attrib['dump']\n else:\n self.dump = False\n\n\nclass PostProcess:\n def __init__(self, elem):\n attrib = elem.attrib\n\n self.name = attrib['name']\n\n if 'dump' in attrib:\n self.dump = attrib['dump']\n else:\n self.dump = False\n","sub_path":"interminepy/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"60204299","text":"# -*- coding: utf-8 -*-\nimport random\nfrom hashlib import md5\n\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.views.generic import DetailView, ListView\nfrom django.views.generic.edit import CreateView\n\nfrom .forms import (\n RegistroCongresoForm, RegistroCursoForm,\n RegistroMesasDeDebateForm\n)\nfrom .models import (\n Conferencista, Curso,\n RegistroCongreso, RegistroCurso, RegistroMesasDeDebate\n)\n\n\nclass HomeView(ListView):\n queryset = Conferencista.objects.filter(\n activo=True\n ).order_by(\n 'nombre'\n )\n context_object_name = 'conferencistas'\n template_name = 'congreso/home.html'\n\n def get_context_data(self, **kwargs):\n context = super(HomeView, self).get_context_data(**kwargs)\n context['cursos'] = Curso.objects.filter(\n activo=True\n ).order_by(\n 'nombre'\n )[:6]\n return context\n\n\nclass ConferencistasView(ListView):\n queryset = Conferencista.objects.filter(\n activo=True\n ).order_by(\n 'nombre'\n )\n context_object_name = 'conferencistas'\n template_name = 'congreso/conferencistas/list.html'\n\n\nclass ConferencistaView(DetailView):\n queryset = Conferencista.objects.filter(\n activo=True\n )\n context_object_name = 'conferencista'\n template_name = 'congreso/conferencistas/detail.html'\n\n\nclass CursosView(ListView):\n queryset = Curso.objects.filter(\n activo=True\n ).order_by(\n 'nombre'\n )\n context_object_name = 'cursos'\n template_name = 'congreso/cursos/list.html'\n\n def get_context_data(self, **kwargs):\n context = super(CursosView, self).get_context_data(**kwargs)\n context['form'] = RegistroCursoForm()\n return context\n\n\nclass CursoView(DetailView):\n queryset = Curso.objects.filter(\n activo=True\n )\n context_object_name = 'curso'\n template_name = 'congreso/cursos/detail.html'\n\n\nclass BaseRegisterCreateView(SuccessMessageMixin, CreateView):\n\n def generate_register_key(self, instance):\n unique_data = \"{0}{1}{2}{3}{4}{5}\".format(\n instance.nombre.encode('utf-8'),\n instance.apellido_paterno.encode('utf-8'),\n instance.apellido_materno.encode('utf-8'),\n instance.correo_electronico.encode('utf-8'),\n instance.escuela_de_procedencia.encode('utf-8'),\n random.randint(0, 10000000)\n )\n dirty_key = md5(unique_data).hexdigest()\n return (dirty_key[:8]).upper()\n\n def form_valid(self, form):\n self.register_key = self.generate_register_key(form.instance)\n form.instance.clave_de_registro = self.register_key\n\n form.instance.nombre = form.instance.nombre.upper()\n form.instance.apellido_paterno = form.instance.apellido_paterno.upper()\n form.instance.apellido_materno = form.instance.apellido_materno.upper()\n\n return super(BaseRegisterCreateView, self).form_valid(form)\n\n def get_success_message(self, cleaned_data):\n return self.dirty_success_message.format(\n cleaned_data['nombre'].encode('utf-8'),\n self.register_key\n )\n\n\nclass RegistroCursoCreateView(BaseRegisterCreateView):\n model = RegistroCurso\n form_class = RegistroCursoForm\n success_url = reverse_lazy('congreso:cursos')\n template_name = \"congreso/cursos/create.html\"\n dirty_success_message = (\n 'Felicidades {0}! has sido registrado '\n 'exitosamente al curso \"{1}\". '\n 'Tu clave de registro es: {2}'\n )\n\n def get_success_message(self, cleaned_data):\n return self.dirty_success_message.format(\n cleaned_data['nombre'].encode('utf-8'),\n cleaned_data['curso'].nombre.encode('utf-8'),\n self.register_key\n )\n\n\nclass RegistroCongresoCreateView(BaseRegisterCreateView):\n model = RegistroCongreso\n form_class = RegistroCongresoForm\n success_url = reverse_lazy('congreso:home')\n template_name = \"congreso/congreso/create.html\"\n dirty_success_message = (\n 'Felicidades {0}! has sido registrado '\n 'exitosamente al Congreso. '\n 'Tu clave de registro es: {1}'\n )\n\n\nclass RegistroMesasDeDebateCreateView(BaseRegisterCreateView):\n model = RegistroMesasDeDebate\n form_class = RegistroMesasDeDebateForm\n success_url = reverse_lazy('congreso:home')\n template_name = \"congreso/mesasdebate/create.html\"\n dirty_success_message = (\n 'Felicidades {0}! has sido registrado '\n 'exitosamente a las Mesas de debate. '\n 'Tu clave de registro es: {1}'\n )\n","sub_path":"congreso/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"30790865","text":"from app import ml_model_path as model_path\n\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nimport numpy as np\n\nvocab_size = 10000\noov_tok = \"\"\nmax_len = 120\ntrunc_type = \"post\"\nembedding_dim= 16\ntokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_tok)\n\ndef tokenize(reviews):\n\n tokenizer.fit_on_texts(reviews)\n word_index = tokenizer.word_index\n\n sequences = tokenizer.texts_to_sequences(reviews)\n padded = pad_sequences(sequences, maxlen=max_len)\n\n print(padded)\n return padded\n\n\ndef get_model():\n return tf.keras.models.load_model(model_path)\n\n\ndef preprocess_data(data):\n p_data = []\n for d in data: \n print(\"-------------->\", d)\n p_data.append( tokenize(d) )\n\n return p_data\n\ndef train_data(text, labels):\n data = tokenize(text)\n labels = np.array(labels)\n\n\n print(data)\n print(labels)\n\n model = get_model()\n model.compile(loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n\n num_epochs = 10\n model.fit(data, labels, epochs=num_epochs)\n\n model.save(model_path)\n\n\ndef prediction_to_labels(predictions):\n labels = []\n threshold= 0.2\n\n for pr in predictions:\n print('----->', pr)\n prob = round(round(pr[0], 2), 1)\n if prob > threshold:\n labels.append('Positive')\n else:\n labels.append('Negative')\n\n return labels\n\ndef predict_data(reviews):\n data = tokenize(reviews)\n model = get_model()\n\n predictions = model.predict(data)\n print(predictions)\n labels = prediction_to_labels(predictions)\n\n return labels\n\n","sub_path":"review_service/app/helpers/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"563796150","text":"## import packages \nimport pandas as pd \nimport os \nfrom scipy.spatial.distance import pdist\nimport numpy as np \nimport hdbscan\nimport datetime\n\n## constant\ndate = datetime.datetime.today().strftime('%Y%m%d')\nminClsuter = 3\nsubclusterThreshold = 0.3\n\n## set path \noutputPath = '/san/home/yunfeng.hu/Cluster_Algorithm_Test/'\nos.chdir(outputPath)\n\n\n## function \ndef arr_to_matrix(Array, Dimension):\n\ttri = np.zeros((Dimension, Dimension))\n\ttri[np.triu_indices(Dimension,1)] = Array\n\treturn tri\n\n\ndef similarity_matrix(DataFrame):\n\tDist = pdist(DataFrame.iloc[:,2:], metric = 'cosine')\n\tDist = arr_to_matrix(Dist, len(DataFrame))\n\tDist = Dist + Dist.T\n\tDist[np.isnan(Dist)] = 1\n\treturn Dist\n\n\ndef hdbscan_cluster(SimilarityMatrix, minClsuter):\n\tcluster = hdbscan.HDBSCAN(min_cluster_size=minClsuter, metric = 'precomputed')\n\tcluster_labels = cluster.fit_predict(SimilarityMatrix)\n\treturn cluster_labels\n\ndef unique_array_keep_order(Array):\n\tarr, idx = np.unique(Array, return_index=True)\n\treturn Array[np.sort(idx)]\n\n\n## load data \n\n# cluster file \ndfCluster = pd.ExcelFile('/san/home/yunfeng.hu/Cluster_Algorithm_Test/JaredSkill_HDBSCAN_ClusterCos_with_Scores_20180917.xlsx')\nsheetNames = dfCluster.sheet_names\ndfCluster = dfCluster.parse(sheetNames[0])\n\n# skill position file\ndfSkills = pd.read_csv('/san/home/yunfeng.hu/Cluster_Algorithm_Test/skillvectors.tsv', delimiter = '\\t', header = None)\n\n\n\n## calcualte similarity matrix \nDist = similarity_matrix(dfSkills)\n\n\nminCluster =[3,4,5,6,7,8]\nwriter = pd.ExcelWriter('JaredSkill_HDBSCAN_SubCluster_with_Scores_' + date+ '.xlsx', engine='xlsxwriter')\nfor mincluster in minCluster:\n\t## create subcluster \n\tclusters = dfCluster['ClusterID'].unique() # unique clusters\n\tskillIDs = list(dfSkills[0])\n\tdfFinal = pd.DataFrame()\n\tfor cluster in clusters:\n\t\tdffinal = pd.DataFrame()\n\t\tdfClusterTemp = dfCluster[dfCluster['ClusterID']==cluster] # cluster subset\n\t\tdfClusterTemp = dfClusterTemp[dfClusterTemp['ClusterScore']>=0.3]\n\t\tif len(dfClusterTemp)==0:\n\t\t\tpass\n\t\telse:\n\t\t\tdfClusterTempSkills = list(dfClusterTemp['SkillID'])\n\t\t\tskillIndex = [skillIDs.index(skillid) for skillid in dfClusterTempSkills]\n\t\t\tdistTemp = Dist[np.ix_(skillIndex, skillIndex)]\n\t\t\tcluster_labels = hdbscan_cluster(distTemp, mincluster)\n\t\t\tdfClusterTemp['SubClusterID'] = cluster_labels\n\t\t\t# calculate subcluster score \n\t\t\tsubclusters = unique_array_keep_order(cluster_labels)\n\t\t\tsubclusterScores = []\n\t\t\tfor subcluster in subclusters:\n\t\t\t\tdfsubclusterScore = dfClusterTemp.copy()\n\t\t\t\tdfSubclusterTemp = dfsubclusterScore[dfsubclusterScore['SubClusterID']==subcluster]\n\t\t\t\tsubclusterSkillID = list(dfSubclusterTemp['SkillID'])\n\t\t\t\tsubclusterSkillIndex = [skillIDs.index(skillid) for skillid in subclusterSkillID]\n\t\t\t\tsubclusterDist = Dist[np.ix_(skillIndex, subclusterSkillIndex)]\n\t\t\t\t# subclusterDist = Dist[np.ix_(subclusterSkillIndex, subclusterSkillIndex)]\n\t\t\t\tsubclusterDist = np.mean(subclusterDist, 1)\n\t\t\t\tdfsubclusterScore['SubClusterID'] = [subcluster]*len(dfsubclusterScore)\n\t\t\t\tdfsubclusterScore['SubClusterCore'] = [False]*len(dfsubclusterScore)\n\t\t\t\tdfsubclusterScore.loc[dfsubclusterScore['SkillID'].isin(subclusterSkillID), 'SubClusterCore'] = True\n\t\t\t\tdfsubclusterScore['SubClusterScore'] = 1-subclusterDist\n\t\t\t\tdffinal = dffinal.append(dfsubclusterScore, ignore_index = False)\n\t\t\tdffinal = dffinal.sort_values(['SubClusterID', 'SubClusterScore'], ascending = [1,0])\n\t\t\tdfFinal = dfFinal.append(dffinal, ignore_index = True)\n\n\tdfFinal.to_csv('JaredSkill_HDBSCAN_SubCluster_%s_with_Scores_%s.csv' % (mincluster, date), index= False)\n\tdfFinal.to_excel(writer, sheet_name = 'MinCluster_' + str(mincluster), index = False)\n\n\n\nwriter.save()\n","sub_path":"hdbscan_subcluster.py","file_name":"hdbscan_subcluster.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"353954567","text":"import sys\n\nfrom PIL import Image\ni = Image.open(sys.argv[1])\n\nif len(i.getpalette()) != 256 * 3 :\n\traise Exception('AAAAAAAAAAAAAAAAAAAAAA ' + len(i.getpalette()))\n\ni = i.load()\n\nprint('memory_initialization_radix=10;')\nprint('memory_initialization_vector=')\n\narray = []\nfor y in range(0, 128) :\n\tfor x in range(0, 256) :\n\t\tvalue = i[x, y]\n\t\tarray.append(value)\n\nfor x in array[:-1]:\n\tprint(str(x) + ', ')\n\nprint(str(array[-1]) + ';')","sub_path":"scripts/coe-convert-paletted.py","file_name":"coe-convert-paletted.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"339788393","text":"f = open('cadena1.nwk','r')\ng = open('cadena2.nwk','r')\n\ncadena_newick1 = f.read()\ncadena_newick2 = g.read()\n\n\nDistancia_total = 0\n\nparentesis_a = []\nhojas = []\nizquierdo = []\nderecho = []\nhojas_izquierdo = []\n\nparentesis_a2 = []\nhojas2 = []\nizquierdo2 = []\nderecho2 = []\nhojas_izquierdo2 = []\n\nfor x in range(0,len(cadena_newick1)): #Recorrer la cadena Newick.\n\n\tif cadena_newick1[x] =='(': #Agregar los paréntesis que abren a la pila.\n\t\tparentesis_a.append(cadena_newick1[x]) \n\n\telif cadena_newick1[x]!='(' and cadena_newick1[x]!=')' and cadena_newick1[x]!= ',' and cadena_newick1[x]!=' ':#Agregar las hojasa la pila.\n\t\thojas.append(cadena_newick1[x])\n\n\telif cadena_newick1[x]==')':#Sacar los paréntesis de la pila, si hay un paréntesis que cierra.\n\t\tparentesis_a.pop()\n\n\telif len(parentesis_a)==1:#Validar que sea el último paréntesis\n\t\tfor y in range(0,x):\n\t\t\tizquierdo.append(cadena_newick1[y])\n\t\tfor y in range(x,len(cadena_newick1)):\n\t\t\tderecho.append(cadena_newick1[y])\n\n#Recorrido arbol 2\n\nfor x in range(0,len(cadena_newick2)): #Recorrer la cadena Newick.\n\n\tif cadena_newick2[x] =='(': #Agregar los paréntesis que abren a la pila.\n\t\tparentesis_a2.append(cadena_newick2[x]) \n\n\telif cadena_newick2[x]!='(' and cadena_newick2[x]!=')' and cadena_newick2[x]!= ',' and cadena_newick2[x]!=' ':#Agregar las hojas2 a la pila.\n\t\thojas2.append(cadena_newick2[x])\n\n\telif cadena_newick2[x]==')':#Sacar los paréntesis de la pila, si hay un paréntesis que cierra.\n\t\tparentesis_a2.pop()\n\n\telif len(parentesis_a2)==1:#Validar que sea el último paréntesis\n\t\tfor y in range(0,x):\n\t\t\tizquierdo2.append(cadena_newick2[y])\n\t\tfor y in range(x,len(cadena_newick2)):\n\t\t\tderecho2.append(cadena_newick2[y])\n\nizquierdo.pop(0)\nizquierdo2.pop(0)\nderecho.pop(0)\nderecho.pop(len(derecho)-1)\nderecho2.pop(0)\nderecho2.pop(len(derecho2)-1)\n\n\nfor x in izquierdo:\n\tif x!='(' and x!=')' and x!=',' and x!=' ':\n\t\thojas_izquierdo.append(x)\n\nfor x in izquierdo2:\n\tif x!='(' and x!=')' and x!=',' and x!=' ':\n\t\thojas_izquierdo2.append(x)\n\nfor x in hojas_izquierdo:\n\tfor y in hojas_izquierdo2:\n\t\tif x == y:\n\t\t\tDistancia_total = Distancia_total + 1\n\nfor x in hojas_izquierdo2:\n\tfor y in hojas_izquierdo:\n\t\tif x == y:\n\t\t\tDistancia_total = Distancia_total + 1\n\n\n\n\n\n\n\n\n\n\n\n\nprint(\"Pila de paréntesis abiertos 1\")\nprint(parentesis_a)\nprint(\"-----------------------------------\")\nprint(\"Pila de hojas 1\")\nprint(hojas)\nprint(\"-----------------------------------\")\nprint(\"Arbol izquierdo 1\")\nprint(izquierdo)\nprint(\"Arbol derecho\")\nprint(derecho)\nprint(\"Hojas del arbol Izquierdo\")\nprint(hojas_izquierdo)\n\nprint(\"Pila de paréntesis abiertos 2\")\nprint(parentesis_a2)\nprint(\"-----------------------------------\")\nprint(\"Pila de hojas 2\")\nprint(hojas2)\nprint(\"-----------------------------------\")\nprint(\"Arbol izquierdo 2\")\nprint(izquierdo2)\nprint(\"Arbol derecho2\")\nprint(derecho2)\nprint(\"Hojas del arbol Izquierdo2\")\nprint(hojas_izquierdo2)\nprint(\"La Distancia_total es:\")\nprint(Distancia_total)\n\nPausa = input()\n\nf.close()\ng.close()\n\n\n","sub_path":"ProgramaTesina/cadenas.py","file_name":"cadenas.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"209168644","text":"import datetime as dt\nimport logging\nfrom lxml import etree, html\nimport pandas as pd\nimport shutil\nimport re\nimport os\nimport sys\nimport glob\nfrom subprocess import Popen\n\nndrv = r'\\\\P7FS0001\\ed'\nfileLog = ndrv + r'\\Sancho\\prog\\Dividend\\log\\GetDividend_Imagine_' + dt.datetime.now().strftime('%Y%m%d_%H%M%S') + '.log' \ndirHKexList = ndrv + r'\\Sancho\\data\\HKExData\\ListedSecurities'\n#dirHKexList = ndrv + r'\\Sancho\\data\\BBG\\Listed'\ndirITS = ndrv + r'\\Sancho\\prog\\its\\Resources\\IO Service Templates\\DownloadCurve'\ndirDvdOut = ndrv + r'\\Sancho\\data\\Imagine\\Dividend'\ndirTmp = ndrv + r'\\Sancho\\tmp'\n\n# === Setup Logger ===\nhandler = logging.FileHandler(fileLog)\nformatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')\nhandler.setFormatter(formatter)\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(handler)\nlogger.addHandler(logging.StreamHandler())\nlogger.setLevel(logging.DEBUG) \n\n# def GetStockList(fname):\n# xpath = '/html/body/printfriendly/table/*/*/table/*/*/table/*/table'\n# tree = etree.parse(fname, etree.HTMLParser())\n# table = tree.xpath(xpath)[0]\n# dfMBS = pd.read_html(etree.tostring(table), header=0)[0]\n# MBScode = dfMBS['STOCK CODE'].unique()\n# return MBScode\n\ndef GetStockList(fname):\n logger.info('Reading %s' % fname)\n dfMBS = pd.read_csv(fname)\n MBScode = dfMBS['sym'].unique()\n return MBScode\n\ndef GenInputCSV(f_in, prodIds):\n with open(f_in, 'w') as f:\n# f.write('##\\n')\n# f.write('## Replace the placeholder for curveName with an appropriate value.\\n')\n# f.write('## Adjust other data as needed.\\n')\n# f.write('##\\n')\n f.write('curveType,curveName,curveExt,asofDate,userData\\n')\n for id in prodIds:\n f.write('div,%04d.HK,HT,0,\\n' % id)\n \ndef PostProcOutput(f_allout, dtNow, dirOutRoot): \n yyyymmdd = dtNow.strftime('%Y%m%d')\n hh_mm_ss = dtNow.strftime('%H:%M:%S')\n fpDvdTxt = dirDvdOut + '/output_txt/downloadCurve_out_ ' + yyyymmdd + '.txt'\n shutil.copy2(f_allout, fpDvdTxt) \n \n \n hdrIn1 = 'Curve Name,Curve Ext,asofDate,Currency,Forward Yield,Forward Yield Type'\n hdrIn2 = 'Ex-Date,Amount,Yield,Announce Date,Record Date,Payment Date,Status,Type,Franking'\n try : \n with open(fpDvdTxt) as fh_allout:\n lines = fh_allout.readlines()\n i = -1 \n while i-2 < len(lines) :\n i += 1\n ln = lines[i]\n if re.match(r'^%s' % hdrIn1, ln):\n i += 1\n headVal = lines[i].rstrip('\\n')\n values = headVal.split(',')\n curveName = values[0]\n curveExt = values[1]\n asofDate = values[2]\n cur = values[3]\n forwardYield = values[4]\n forwardYieldType = values[5]\n i += 1\n if not re.match(r'^\\*\\*Begin Table\\*\\*', lines[i]):\n logger.error('Format changed! Expected: %s' % r'**Begin Table**' )\n return\n i += 1\n if not re.match(r'^%s' % hdrIn2, lines[i]):\n logger.error('Format changed! Expected: %s' % hdrIn2 )\n return \n dirOut = dirOutRoot + '/' + yyyymmdd\n if not os.path.exists(dirOut):\n os.makedirs(dirOut)\n f_oneout = dirOut + '/ImagineDvd_' + yyyymmdd + '_%s.csv' % curveName\n with open(f_oneout, 'w') as fh_oneout:\n fh_oneout.write('Date,Time,%s,%s\\n' % (hdrIn1,hdrIn2))\n while True:\n i += 1\n if re.match(r'^\\*\\*End Table\\*\\*', lines[i]):\n break \n fh_oneout.write('%s,%s,%s,%s\\n' % (yyyymmdd, hh_mm_ss, headVal, lines[i].rstrip())) \n \n return True\n except: \n if i == len(lines):\n logger.info(\"End of file reached.\") \n return True\n else:\n logger.error(\"Exception in user code:\", exc_info=True) \n logger.error('-'*60)\n return False\n \ndef CombineAllCSV(dirDvdOutYMD): \n dvdFiles = glob.glob(dirDvdOutYMD + '/ImagineDvd_*.csv')\n df = pd.DataFrame()\n for dvdf in dvdFiles:\n dfTmp = pd.read_csv(dvdf)\n df = df.append(dfTmp, ignore_index=True)\n return df\n\nif __name__ == \"__main__\": \n dtNow = dt.datetime.now()\n yyyymmdd = dtNow.strftime('%Y%m%d') \n #fpStock = dirHKexList + '/' + yyyymmdd + r'/MainBoardStocks_' + yyyymmdd + '.htm'\n fpStock = dirHKexList + '/' + yyyymmdd + '/HKEx_Listed_' + yyyymmdd + '.csv'\n #f_in_src = dirDvdOut + '/input_csv/downloadCurve_inp_' + yyyymmdd + '.csv' \n f_in_src = dirDvdOut + '/input_csv/downloadDividendCurve_inp_' + yyyymmdd + '.csv' \n \n try:\n prodIds = GetStockList(fpStock)\n logger.info('Got %d stocks' % len(prodIds))\n logger.info(','.join(str(x) for x in prodIds))\n \n # ==== Generate input csv for Imagine ====\n logger.info('Generating input csv for Imagine: %s' % f_in_src) \n GenInputCSV(f_in_src, prodIds)\n logger.info('Done') \n \n # ==== Get Dividend data from Imagine ==== \n logger.info('Copy input csv for Imagine: %s to %s' % (f_in_src, dirITS))\n #shutil.copy2(f_in_src, dirITS + '/downloadCurve_inp.csv') \n shutil.copy2(f_in_src, dirITS + '/downloadDividendCurve_inp.csv') \n #fpRun = dirITS + r'/downloadCurve_run.bat'\n fpRun = dirITS + r'/downloadDividendCurve_run.bat'\n logger.info('Running %s' % fpRun)\n p = Popen(fpRun, cwd=dirITS, shell=True)\n stdout, stderr = p.communicate()\n logger.info('Return code from %s : %d' % (fpRun, p.returncode))\n logger.info('Getting dividend from Imagine: Done!') \n\n # ==== Post-process Output files (Imagine output a txt with all stocks' dividends and headers)\n #f_allTXT = dirITS + '/downloadCurve_out.txt'\n f_allTXT = max(glob.iglob(dirITS + '/out/*_downloadDividendCurve.*.csv'), key=os.path.getmtime)\n logger.info('Post-processing output from Imagine: %s ' % (f_allTXT))\n res = PostProcOutput(f_allTXT, dtNow, dirDvdOut) \n if res == False:\n logger.error('Error in post-processing output file: %s' % f_allTXT)\n sys.exit(-1)\n \n # ==== Combine all dividend files into one file ====\n f_allOut = dirDvdOut + '/' + yyyymmdd + '/Dvd_Img_' + yyyymmdd + '.csv'\n logger.info('Combining all dividend files into one csv: %s' % (f_allOut))\n dfAll = CombineAllCSV(dirDvdOut + '/' + yyyymmdd)\n dfAll.to_csv(f_allOut, index=False)\n\n \n except:\n logger.error(\"Exception in user code:\", exc_info=True) \n logger.error('-'*60)\n #traceback.print_exc(file=sys.stdout) \n \n","sub_path":"Dividend/GetDividend_Imagine.py","file_name":"GetDividend_Imagine.py","file_ext":"py","file_size_in_byte":6539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"414524041","text":"import datetime\nimport re\nimport os\n\ntry:\n from StringIO import cStringIO as BytesIO\nexcept ImportError:\n from io import BytesIO\n\nimport numpy as np\nimport struct\n\nfrom . import lib\nfrom .lib import red, Bbox\nfrom .txrx import cdn_cache_control\nfrom .storage import Storage, SimpleStorage\n\n\nclass SkeletonDecodeError(Exception):\n pass\n\nclass SkeletonEncodeError(Exception):\n pass\n\nclass PrecomputedSkeleton(object):\n def __init__(self, \n vertices=None, edges=None, \n radii=None, vertex_types=None, \n segid=None\n ):\n\n self.id = segid\n\n if vertices is None:\n self.vertices = np.array([[]], dtype=np.float32)\n elif type(vertices) is list:\n self.vertices = np.array(vertices, dtype=np.float32)\n else:\n self.vertices = vertices.astype(np.float32)\n\n if edges is None:\n self.edges = np.array([[]], dtype=np.uint32)\n elif type(edges) is list:\n self.edges = np.array(edges, dtype=np.uint32)\n else:\n self.edges = edges.astype(np.uint32)\n\n if radii is None:\n self.radii = -1 * np.ones(shape=self.vertices.shape[0], dtype=np.float32)\n elif type(radii) is list:\n self.radii = np.array(radii, dtype=np.float32)\n else:\n self.radii = radii\n\n if vertex_types is None:\n # 0 = undefined in SWC (http://research.mssm.edu/cnic/swc.html)\n self.vertex_types = np.zeros(shape=self.vertices.shape[0], dtype=np.uint8)\n elif type(vertex_types) is list:\n self.vertex_types = np.array(vertex_types, dtype=np.uint8)\n else:\n self.vertex_types = vertex_types.astype(np.uint8)\n\n @classmethod\n def from_path(kls, vertices):\n \"\"\"\n Given an Nx3 array of vertices that constitute a single path, \n generate a skeleton with appropriate edges.\n \"\"\"\n if vertices.shape[0] == 0:\n return PrecomputedSkeleton()\n\n skel = PrecomputedSkeleton(vertices)\n edges = np.zeros(shape=(skel.vertices.shape[0] - 1, 2), dtype=np.uint32)\n edges[:,0] = np.arange(skel.vertices.shape[0] - 1)\n edges[:,1] = np.arange(1, skel.vertices.shape[0])\n skel.edges = edges\n return skel\n\n @classmethod\n def simple_merge(kls, skeletons):\n \"\"\"\n Simple concatenation of skeletons into one object \n without adding edges between them.\n \"\"\"\n if len(skeletons) == 0:\n return PrecomputedSkeleton()\n\n if type(skeletons[0]) is np.ndarray:\n skeletons = [ skeletons ]\n\n ct = 0\n edges = []\n for skel in skeletons:\n edge = skel.edges + ct\n edges.append(edge)\n ct += skel.vertices.shape[0]\n\n return PrecomputedSkeleton(\n vertices=np.concatenate([ skel.vertices for skel in skeletons ], axis=0),\n edges=np.concatenate(edges, axis=0),\n radii=np.concatenate([ skel.radii for skel in skeletons ], axis=0),\n vertex_types=np.concatenate([ skel.vertex_types for skel in skeletons ], axis=0),\n segid=skeletons[0].id,\n )\n\n def merge(self, skel):\n \"\"\"Combine with an additional skeleton and consolidate.\"\"\"\n return PrecomputedSkeleton.simple_merge((self, skel)).consolidate()\n\n def empty(self):\n return self.vertices.size == 0 or self.edges.size == 0\n\n def encode(self):\n edges = self.edges.astype(np.uint32)\n vertices = self.vertices.astype(np.float32)\n \n result = BytesIO()\n\n # Write number of positions and edges as first two uint32s\n result.write(struct.pack(' [1,2]\n eff_edges = eff_edges[np.lexsort(eff_edges[:,::-1].T)] # Sort rows \n eff_edges = np.unique(eff_edges, axis=0)\n\n radii_vector_map = np.vectorize(lambda idx: radii[idx])\n eff_radii = radii_vector_map(uniq_idx)\n\n vertex_type_map = np.vectorize(lambda idx: vertex_types[idx])\n eff_vtype = vertex_type_map(uniq_idx) \n \n return PrecomputedSkeleton(eff_nodes, eff_edges, eff_radii, eff_vtype, segid=self.id)\n\n def clone(self):\n vertices = np.copy(self.vertices)\n edges = np.copy(self.edges)\n radii = np.copy(self.radii)\n vertex_types = np.copy(self.vertex_types)\n\n return PrecomputedSkeleton(vertices, edges, radii, vertex_types, segid=self.id)\n\n def __eq__(self, other):\n if self.id != other.id:\n return False\n elif self.vertices.shape[0] != other.vertices.shape[0]:\n return False\n elif self.edges.shape[0] != other.edges.shape[0]:\n return False\n\n return (np.all(self.vertices == other.vertices, axis=0) \\\n and np.any(self.edges == other.edges, axis=0) \\\n and np.any(self.radii == other.radii) \\\n and np.any(self.vertex_types == other.vertex_types))\n\n def __str__(self):\n return \"PrecomputedSkeleton(segid={}, vertices=(shape={}, {}), edges=(shape={}, {}), radii=(shape={}, {}), vertex_types=(shape={}, {}))\".format(\n self.id,\n self.vertices.shape[0], self.vertices.dtype,\n self.edges.shape[0], self.edges.dtype,\n self.radii.shape[0], self.radii.dtype,\n self.vertex_types.shape[0], self.vertex_types.dtype\n )\n\nclass PrecomputedSkeletonService(object):\n def __init__(self, vol):\n self.vol = vol\n\n @property\n def path(self):\n path = 'skeletons'\n if 'skeletons' in self.vol.info:\n path = self.vol.info['skeletons']\n return path\n\n def get(self, segid):\n with SimpleStorage(self.vol.layer_cloudpath) as stor:\n path = os.path.join(self.path, str(segid))\n skelbuf = stor.get_file(path)\n\n if skelbuf is None:\n raise SkeletonDecodeError(\"File does not exist: {}\".format(path))\n\n return PrecomputedSkeleton.decode(skelbuf, segid=segid)\n\n def upload(self, segid, vertices, edges, radii=None, vertex_types=None):\n with SimpleStorage(self.vol.layer_cloudpath) as stor:\n path = os.path.join(self.path, str(segid))\n skel = PrecomputedSkeleton(\n vertices, edges, radii, \n vertex_types, segid=segid\n ).encode()\n\n stor.put_file(\n file_path='{}/{}'.format(self.path, segid),\n content=skel,\n compress='gzip',\n cache_control=cdn_cache_control(self.vol.cdn_cache),\n )\n \n def upload_multiple(self, skeletons):\n with Storage(self.vol.layer_cloudpath, progress=self.vol.progress) as stor:\n for skel in skeletons:\n path = os.path.join(self.path, str(skel.id))\n stor.put_file(\n file_path='{}/{}'.format(self.path, str(skel.id)),\n content=skel.encode(),\n compress='gzip',\n cache_control=cdn_cache_control(self.vol.cdn_cache),\n )\n \n def swc(self, segid):\n \"\"\"Prototype SWC file generator. \n\n c.f. http://research.mssm.edu/cnic/swc.html\"\"\"\n from . import __version__\n swc = \"\"\"# ORIGINAL_SOURCE CloudVolume {}\n# CREATURE \n# REGION\n# FIELD/LAYER\n# TYPE\n# CONTRIBUTOR {}\n# REFERENCE\n# RAW \n# EXTRAS \n# SOMA_AREA\n# SHINKAGE_CORRECTION \n# VERSION_NUMBER \n# VERSION_DATE {}\n# SCALE 1.0 1.0 1.0\n\n\"\"\".format(\n __version__, \n \", \".join([ str(_) for _ in self.vol.provenance.owners ]),\n datetime.datetime.utcnow().isoformat()\n )\n\n skel = self.vol.skeleton.get(segid)\n\n def parent(i):\n coords = np.where( skel.edges == i )\n edge = skel.edges[ coords[0][0] ]\n if edge[0] == i:\n return edge[1] + 1\n return edge[0] + 1\n\n for i in range(skel.vertices.shape[0]):\n line = \"{n} {T} {x} {y} {z} {R} {P}\".format(\n n=i+1,\n T=skel.vertex_types[i],\n x=skel.vertices[i][0],\n y=skel.vertices[i][1],\n z=skel.vertices[i][2],\n R=skel.radii[i],\n P=-1 if i == 0 else parent(i),\n )\n\n swc += line + '\\n'\n\n return swc\n\n","sub_path":"cloudvolume/skeletonservice.py","file_name":"skeletonservice.py","file_ext":"py","file_size_in_byte":13438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"488447677","text":"'''\r\nThis code file contains an implementation of the calinski-harabasz index. \r\n\r\nReferences \r\n----------\r\n\r\nMilligan, Glenn W., and Martha C. Cooper. \r\n\"An examination of procedures for determining the \r\nnumber of clusters in a data set.\" Psychometrika 50.2 (1985): 159-179.\r\n\r\nCalinski, T. and Harabasz, J.: A dendrite method for\r\ncluster analysis, Commun. Stat.-Theor. M., 3, 1-27,\r\ndoi:10.1080/03610927408827101, 1974\r\n'''\r\n\r\n\r\nfrom collections import Counter\r\nfrom numpy import mean, zeros, where, array\r\nfrom numpy.linalg import norm\r\n\r\ndef validation(data, clusterings, method = 'calinski-harabasz', index = False, threshold = False):\r\n\r\n \"\"\"\r\n Evaluates particular clusterings of a set of N objects\r\n using the original dataset to calculate an index which is used\r\n to determine which of the given clusterings is 'best'.\r\n\r\n Parameters\r\n ----------\r\n\r\n data : ndarray\r\n The original N by D matrix that was clustered for\r\n example by the linkage function in\r\n scipy.cluster.hierarchy.\r\n\r\n clusterings : ndarray\r\n An S by N matrix. Where S is the number of solutions to\r\n be evaluated. The output from the 'extract' function is\r\n the intended input here.\r\n\r\n method : str\r\n A string indicating what type of validation criterion is to\r\n be used. Currently 'calinski-harabasz is the only available\r\n index.\r\n\r\n index : bool \r\n Set equal to true if you would like to return indices for \r\n each clustering instead of the number of clusters.\r\n \r\n threshold : bool \r\n Set equal to true if you would like to ignore minority clusters\r\n i.e. those which are less than half the average cluster size.\r\n\r\n Returns\r\n -------\r\n number_of_clusters : int\r\n The 'optimal' number of clusters indicated by the solutions\r\n given. \r\n\r\n\r\n index : ndarray \r\n An array of the validation indices for each clustering.\r\n \r\n \r\n \"\"\"\r\n\r\n N = len(data) # Number of objects\r\n m = mean(data, axis = 0) # mean of the data \r\n CH = zeros(len(clusterings)) # vector for CH index\r\n SSWv = zeros(len(clusterings)) # vector for SSW\r\n SSBv = zeros(len(clusterings)) # vector for SSB\r\n \r\n # Go through all the clusterings one by one \r\n\r\n for i, solution in enumerate(clusterings): \r\n\r\n clusters = Counter(solution) # label -> size\r\n k = len(clusters) # Number of clusters\r\n SSB = 0 # Initial sum of squares between the clusters \r\n SSW = 0 # Initial sum of squares within the clusters\r\n\r\n # For each of the clusters updates the within and between\r\n # sums of squares.\r\n\r\n if threshold: \r\n limit = mean(list(clusters.items())) // 2\r\n else: \r\n limit = 0 \r\n \r\n for label, size in clusters.items():\r\n if size > limit: \r\n \tcluster = data[where(solution == label)] \r\n \tcluster_mean = mean(cluster, axis = 0)\r\n \tSSB += size * norm(m - cluster_mean) ** 2\r\n \tSSW += sum(norm(cluster - cluster_mean, axis = 1) ** 2)\r\n\r\n\r\n # If the number of clusters is 1 the index should\r\n # return a value of infinity but instead we return 0\r\n # otherwise this will always be maximum.\r\n\r\n if method == 'calinski-harabasz':\r\n SSWv[i] = SSW\r\n SSBv[i] = SSB\r\n\r\n if k -1 == 0 or SSW == 0:\r\n CH[i] = 0\r\n\r\n else:\r\n CH[i] = SSB / SSW * (N - k) / (k-1) # Formula of the index.\r\n\r\n\r\n\r\n if method == 'calinski-harabasz': \r\n if index: \r\n return CH\r\n else: \r\n return len(Counter(clusterings[where(CH == max(CH))][0]))\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n","sub_path":"simulations/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":3785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"559069846","text":"import ray\n\ndef init_cluster(ip_address):\n import random\n if ip_address.split(\":\")[0] in ['localhost','127.0.0.1']:\n ray.init()\n else:\n ray.init(address=ip_address)\n return random.randint(0, 9999)\n\ndef run_mapred(input_data, map_fn, reduce_fn, output_location):\n from mapreduce.raymapreduce import RayMapReduce\n import glob\n mapred = RayMapReduce(map_fn, reduce_fn)\n input_files = glob.glob(input_data)\n result = mapred(input_files)\n with open(output_location, 'w') as filehandle:\n filehandle.writelines(\"{}\\n\".format(r) for r in result)\n return result\n\ndef destroy_cluster(cluster_id):\n ray.shutdown()\n ","sub_path":"mapreduce/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"513802831","text":"# coding: utf-8\n\"\"\"Utility/high-level functions for interacting with suggestions.\"\"\"\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport logging\n\nimport django.db.models\n\n\nLOG = logging.getLogger(__name__)\n\n\nNO_SESSION_KEY = object()\n\n\nBLANK_SESSION_WARNING = (\n \"Can't track score: anonymous user has no session key. Do you need to set\"\n ' SESSION_SAVE_EVERY_REQUEST=True ?'\n)\n\n\ndef __user_from_request(req):\n \"\"\"Get either the User object or session key from a request.\n\n Returns None for anonymous users with no session keys.\n \"\"\"\n try: # Requests have a .user object\n req.user\n except AttributeError: # Probably not a request, maybe a string\n return req\n if req.user.is_authenticated():\n return req.user\n return req.session.session_key or NO_SESSION_KEY\n\n\ndef set_score(request_or_user, obj, score):\n \"\"\"Set the score for the given obj.\n\n Will attribute it to the user, if request has an authenticated user, or to\n a session.\n\n \"\"\"\n from . import models\n user = __user_from_request(request_or_user)\n if user is NO_SESSION_KEY:\n LOG.warning(BLANK_SESSION_WARNING)\n else:\n return models.UserScore.set(user, obj, score)\n\n\ndef setdefault_score(request_or_user, obj, score):\n \"\"\"Set the score for the given obj if it doesn't exist.\n\n Will attribute it to the user, if request has an authenticated user, or to\n a session.\n\n \"\"\"\n from . import models\n user = __user_from_request(request_or_user)\n if user is NO_SESSION_KEY:\n LOG.warning(BLANK_SESSION_WARNING)\n else:\n return models.UserScore.setdefault(user, obj, score)\n\n\ndef scores_for(obj):\n \"\"\"Get all scores for the given object.\"\"\"\n from . import models\n return models.UserScore.scores_for(obj)\n\n\ndef get_score(request_or_user, obj):\n \"\"\"Get a user's score for the given object.\"\"\"\n from . import models\n user = __user_from_request(request_or_user)\n return models.UserScore.get(user, obj)\n\n\ndef similar_objects(obj):\n \"\"\"Get objects most similar to obj.\n\n Returns an iterator, not a collection.\n\n \"\"\"\n return similar_to(obj).get_instances_for(obj)\n\n\ndef similar_to(obj):\n \"\"\"Get a queryset of similarity scores most similar to obj.\n\n This can allow you to use methods of the ObjectSimilarityQueryset, such as\n exclude_objects, as well as normal queryset slicing.\n\n \"\"\"\n from . import models\n obj_qset = type(obj).objects.filter(pk=obj.pk)\n high_similarity = models.ObjectSimilarity.objects.filter_objects(obj_qset)\n high_similarity = high_similarity.order_by('-score')\n return high_similarity\n\n\ndef forget_object(obj_content_type, obj_id):\n \"\"\"Remove all information about a given object.\n\n Deletes both UserScore objects and ObjectSimilarity objects.\n\n \"\"\"\n from django.db.models import Q\n from . import models\n models.UserScore.objects.filter(\n object_id=obj_id, object_content_type=obj_content_type\n ).delete()\n models.ObjectSimilarity.objects.filter(\n Q(object_1_content_type=obj_content_type, object_1_id=obj_id) |\n Q(object_2_content_type=obj_content_type, object_2_id=obj_id)\n ).delete()\n","sub_path":"src/django_recommend/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"524979874","text":"# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom functools import partial\nfrom typing import Tuple\n\nimport numpy as np\nimport pytest\nimport torch\nfrom sklearn.metrics import average_precision_score as _sk_average_precision_score\nfrom sklearn.metrics import precision_recall_curve as _sk_precision_recall_curve\nfrom torch import Tensor\n\nfrom tests.classification.inputs import _input_binary_prob\nfrom tests.classification.inputs import _input_binary_prob_plausible as _input_binary_prob_ok\nfrom tests.classification.inputs import _input_multilabel_prob as _input_mlb_prob\nfrom tests.classification.inputs import _input_multilabel_prob_plausible as _input_mlb_prob_ok\nfrom tests.helpers import seed_all\nfrom tests.helpers.testers import NUM_CLASSES, MetricTester\nfrom torchmetrics.classification.binned_precision_recall import (\n BinnedAveragePrecision,\n BinnedPrecisionRecallCurve,\n BinnedRecallAtFixedPrecision,\n)\n\nseed_all(42)\n\n\ndef recall_at_precision_x_multilabel(predictions: Tensor, targets: Tensor, min_precision: float) -> Tuple[float, float]:\n precision, recall, thresholds = _sk_precision_recall_curve(targets, predictions)\n\n try:\n tuple_all = [(r, p, t) for p, r, t in zip(precision, recall, thresholds) if p >= min_precision]\n max_recall, _, best_threshold = max(tuple_all)\n except ValueError:\n max_recall, best_threshold = 0, 1e6\n\n return float(max_recall), float(best_threshold)\n\n\ndef _sk_prec_recall_mclass_prob(predictions, targets, num_classes, min_precision):\n max_recalls = torch.zeros(num_classes)\n best_thresholds = torch.zeros(num_classes)\n\n for i in range(num_classes):\n max_recalls[i], best_thresholds[i] = recall_at_precision_x_multilabel(\n predictions[:, i], targets[:, i], min_precision\n )\n return max_recalls, best_thresholds\n\n\ndef _sk_prec_recall_binary_prob(predictions, targets, num_classes, min_precision):\n return recall_at_precision_x_multilabel(predictions, targets, min_precision)\n\n\ndef _sk_avg_prec_multiclass(predictions, targets, num_classes):\n # replace nan with 0\n return np.nan_to_num(_sk_average_precision_score(targets, predictions, average=None))\n\n\n@pytest.mark.parametrize(\n \"preds, target, sk_metric, num_classes\",\n [\n (_input_binary_prob.preds, _input_binary_prob.target, _sk_prec_recall_binary_prob, 1),\n (_input_binary_prob_ok.preds, _input_binary_prob_ok.target, _sk_prec_recall_binary_prob, 1),\n (_input_mlb_prob_ok.preds, _input_mlb_prob_ok.target, _sk_prec_recall_mclass_prob, NUM_CLASSES),\n (_input_mlb_prob.preds, _input_mlb_prob.target, _sk_prec_recall_mclass_prob, NUM_CLASSES),\n ],\n)\nclass TestBinnedRecallAtPrecision(MetricTester):\n atol = 0.02\n\n @pytest.mark.parametrize(\"ddp\", [True, False])\n @pytest.mark.parametrize(\"dist_sync_on_step\", [True, False])\n @pytest.mark.parametrize(\"min_precision\", [0.05, 0.1, 0.3, 0.5, 0.8, 0.95])\n def test_binned_pr(self, preds, target, sk_metric, num_classes, ddp, dist_sync_on_step, min_precision):\n # rounding will simulate binning for both implementations\n preds = Tensor(np.round(preds.numpy(), 2)) + 1e-6\n\n self.run_class_metric_test(\n ddp=ddp,\n preds=preds,\n target=target,\n metric_class=BinnedRecallAtFixedPrecision,\n sk_metric=partial(sk_metric, num_classes=num_classes, min_precision=min_precision),\n dist_sync_on_step=dist_sync_on_step,\n metric_args={\n \"num_classes\": num_classes,\n \"min_precision\": min_precision,\n \"num_thresholds\": 101,\n },\n )\n\n\n@pytest.mark.parametrize(\n \"preds, target, sk_metric, num_classes\",\n [\n (_input_binary_prob.preds, _input_binary_prob.target, _sk_avg_prec_multiclass, 1),\n (_input_binary_prob_ok.preds, _input_binary_prob_ok.target, _sk_avg_prec_multiclass, 1),\n (_input_mlb_prob_ok.preds, _input_mlb_prob_ok.target, _sk_avg_prec_multiclass, NUM_CLASSES),\n (_input_mlb_prob.preds, _input_mlb_prob.target, _sk_avg_prec_multiclass, NUM_CLASSES),\n ],\n)\nclass TestBinnedAveragePrecision(MetricTester):\n\n @pytest.mark.parametrize(\"ddp\", [True, False])\n @pytest.mark.parametrize(\"dist_sync_on_step\", [True, False])\n @pytest.mark.parametrize(\n \"num_thresholds, thresholds\", ([101, None], [301, None], [None, torch.linspace(0.0, 1.0, 101)])\n )\n def test_binned_pr(self, preds, target, sk_metric, num_classes, ddp, dist_sync_on_step, num_thresholds, thresholds):\n # rounding will simulate binning for both implementations\n preds = Tensor(np.round(preds.numpy(), 2)) + 1e-6\n\n self.run_class_metric_test(\n ddp=ddp,\n preds=preds,\n target=target,\n metric_class=BinnedAveragePrecision,\n sk_metric=partial(sk_metric, num_classes=num_classes),\n dist_sync_on_step=dist_sync_on_step,\n metric_args={\n \"num_classes\": num_classes,\n \"num_thresholds\": num_thresholds,\n \"thresholds\": thresholds\n },\n )\n\n\n@pytest.mark.parametrize(\n \"metric_class\", [BinnedAveragePrecision, BinnedRecallAtFixedPrecision, BinnedPrecisionRecallCurve]\n)\ndef test_raises_errors_and_warning(metric_class):\n if metric_class == BinnedRecallAtFixedPrecision:\n metric_class = partial(metric_class, min_precision=0.5)\n\n with pytest.warns(\n DeprecationWarning,\n match=\"Argument `num_thresholds` \"\n \"is deprecated in v0.4 and will be removed in v0.5. Use `thresholds` instead.\"\n ):\n metric_class(num_classes=10, num_thresholds=100)\n\n with pytest.raises(\n ValueError, match=\"Expected argument `thresholds` to either\"\n \" be an integer, list of floats or a tensor\"\n ):\n metric_class(num_classes=10, thresholds={'temp': [10, 20]})\n","sub_path":"tests/classification/test_binned_precision_recall.py","file_name":"test_binned_precision_recall.py","file_ext":"py","file_size_in_byte":6447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"108859949","text":"def tokenize(message):\n message = message.lower()\n all_words = re.findall(\"[a-z0-9']+\", message)\n return set(all_words) # remove duplicates\n\ndef count_words(training_set):\n \"\"\"training set consists of pairs (message, is_spam)\"\"\"\n counts = defaultdict(lambda: [0, 0])\n for message, is_spam in training_set:\n for word in tokenize(message):\n counts[word][0 if is_spam else 1] += 1\n return counts\n\ndef word_probabilities(counts, total_spams, total_non_spams, k=0.5):\n \"\"\"turn the word_counts into a list of triplets\n w, p(w | spam) and p(w | -spam)\"\"\"\n return [(w,\n (spam + k) / (total_spams + 2 * k),\n (non_spam +k) / (total_non_spams + 2 * k))\n for w, (spam, non_spam) in counts.items()]\n\ndef spam_probability(word_probs, message):\n message_words = tokenize(message)\n log_prob_if_spam = log_prob_if_not_spam = 0.0\n\n # iterate through each word in our vocabulary\n for word, prob_if_spam, prob_if_not_spam in word_probs:\n # if 'word' appears in the message\n # add the log probability of seeing it\n if word in message_words:\n log_prob_if_spam += math.log(prob_if_spam)\n log_prob_if_not_spam += math.log(prob_if_not_spam)\n\n # if 'word' doesn't appear in the message\n # add the log probability of _not_ seeing it\n # which os log(1 - probability of seeing if)\n else:\n log_prob_if_spam += math.log(1.0 - prob_if_spam)\n log_prob_if_not_spam += math.log(1.0 - prob_if_not_spam)\n\n prob_if_spam = math.exp(log_prob_if_spam)\n prob_if_not_spam = math.exp(log_prob_if_not_spam)\n return prob_if_spam / (prob_if_spam + prob_if_not_spam)\n\nclass NaiveBayesClassifier:\n\n def __init__(self, k=0.5):\n self.k = k\n self.word_probs = []\n\n def train(self, training_set):\n\n # count spam and non-spam messages\n num_spams = len([is_spam\n for message, is_spam in training_set\n if is_spam])\n num_non_spams = len(training_set) - num_spams\n\n # run training data through our 'pipeline'\n word_counts = count_words(training_set)\n self.word_probs = word_probabilities(word_counts,\n num_spams,\n num_non_spams,\n self.k)\n\n def classify(self, message):\n return spam_probability(self.word_probs, message)\n\n#### Testing our model\n\nimport glob, re\n\n# modify the path with wherever you've put the files\npath = '/path/'\ndata = []\n# glob.glob return every filename that matches the wildcarded path\nfor fn in glob.glob(path):\n is_spam = \"ham\" not in fn\n\n with open(fn, 'r') as file:\n for line in file:\n if line.startswith(\"Subject:\"):\n # remove the leading \"Subject: \" and keep what's left\n subject = re.sub(\"^Subject: \", \"\", line).strip()\n data.append((subject, is_spam))\n\nrandom.seed(0) # just so you get the same answers as me\ntrain_data, test_data = split_data(data, 0.75)\n\nclassifier = NaiveBayesClassifier()\nclassifier.train(train_data)\n\n# triplets (subject, actual is_spam, predicted spam probability)\nclassified = [(subject, is_spam, classifier.classify(subject))\n for subject, is_spam in test_data]\n\n# assume that spam_probability > 0.5 corresponds th spam_prediction\n# and count the combinations of (actual is_spam, predicted is_spam)\ncounts = Counter((is_spam, spam_probability > 0.5)\n for _, is_spam, spam_probability in classified)\n\n# sort by spam_probability from smallest to largest\nclassified.sort(key=lambda row: row[2])\n\n# the highest predicted spam probabilities among the non-spams\nspammiest_hams = filter(lambda row: not row[1], classified)[-5:]\n\n# the lowest predicted spam probabilities among the actual spams\nhammiest_spams = filter(lambda row: row[1], classified)[:5]\n\ndef p_spam_given_word(word_prob):\n \"\"\"uses bayes's theorem to compute p(spam | message contains word)\"\"\"\n # word_prob is one of the triplets produced by word_probabilities\n word, prob_if_spam, prob_if_not_spam = word_prob\n return prob_if_spam / (prob_if_spam + prob_if_not_spam)\n\nwords = sorted(classifier.word_probs, key=p_spam_given_word)\n\nspammiest_words = words[-5:]\nhammiest_words = words[:5]\n\ndef drop_final_s(word):\n return re.sub(\"s$\", \"\", word)\n\n","sub_path":"DataScience_first_principles/naive_bayes/implementation.py","file_name":"implementation.py","file_ext":"py","file_size_in_byte":4462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"111772473","text":"#ESCAPE THE ABYSS\n#CELL\n#LEVEL 1\nimport random\nimport time\nimport os\nimport sys\nimport pickle\nimport termcolor\nfrom termcolor import colored\nfrom gameconfig import *\nfrom descriptions import * \n\ncellCommands = [\n 'gonorth',\n 'gosouth',\n 'goeast',\n 'gowest',\n 'readnote',\n 'jumpwindow',\n 'checkbrick',\n 'takekey',\n 'usekey',\n 'takepotion'\n ] \n\nclass cellVars:\n potion = True\n cellDoor = \"locked\"\n cellBrick = False\n\n#1st time playing the game, introduction to the CELL.\ndef cellIntroduction(playerName):\n textPrinting()\n\n print(colored('\"Just going to lay there?\"', 'green').center(93, \" \"))\n print()\n time.sleep(1)\n print(colored('\"pity, such a pathetic, lazy, disappointment.\"', 'green').center(93, \" \"))\n time.sleep(2)\n textPrinting()\n\n print(colored('\"Open your eyes.\"', 'green').center(93, \" \"))\n print()\n time.sleep(1)\n print(colored('\"Show me you are worthy\"', 'green').center(93, \" \"))\n time.sleep(2)\n textPrinting()\n\n print(colored('\"Good... good, thats right.\"', 'green').center(93, \" \"))\n print()\n time.sleep(1)\n print(colored('\"RISE!\"', 'green').center(93, \" \"))\n time.sleep(3)\n\n gameVars.playerProfile['playernew'] = False\n saveProfileGame(playerName)\n cellInit(playerName)\n\ndef userInputcell():\n userInputcellting = 1\n while userInputcellting == 1:\n\n #Getting user input\n print()\n Print(divider)\n userInputcell = input(colored(\" > \", 'green'))\n\n #Splitting input into words\n userInSplit = userInputcell.split()\n\n #Getting string length\n stringLength = len(userInSplit)\n #Checking if the string is empty\n if stringLength < 1:\n Error(\"You have to give me a command\")\n\n #For single word commands\n if stringLength == 1:\n command = userInSplit[0].lower()\n\n if command in playerCommands:\n if command == \"inventory\":\n #Printing the inventory\n printInventory()\n if command == \"stats\":\n #Print player stats\n printStats()\n if command == \"clear\":\n clearScreen()\n else:\n print()\n errorResponse()\n\n #For commands > single words\n if stringLength == 2 or stringLength > 2:\n #Conditions for is the string is more than 1 word\n verb = userInSplit[0].lower()\n obj = userInSplit[-1].lower()\n #Command is first and last word of input\n command = (verb + obj)\n\n #Checking if verb is a player command\n if verb in playerCommands:\n\n if verb == \"drop\":\n if obj not in oneToTen:\n print()\n Error(\"*Use the number of the inventory item not the name*\")\n continue\n else:\n itemName = gameVars.playerProfile['inventory'][\"{0}. \".format(obj)]\n if itemName != \"Empty\":\n Alert(\"Dropped {0}\".format(itemName))\n gameVars.playerProfile['inventory'][\"{0}. \".format(obj)] = \"Empty\"\n saveProfileGame(gameVars.playerProfile['playername'])\n continue\n else:\n print()\n Error(\"*You have nothing to drop*\")\n continue\n\n if verb == \"move\":\n move = userInSplit[-2]\n if move in oneToTen:\n if obj in oneToTen:\n store = gameVars.playerProfile['inventory'][\"{0}. \".format(move)]\n if store == \"Empty\":\n print()\n Error(\"*There is nothing to move*\")\n continue\n else:\n gameVars.playerProfile['inventory'][\"{0}. \".format(move)] = \"Empty\"\n gameVars.playerProfile['inventory'][\"{0}. \".format(obj)] = store\n Alert(\"{0} Moved from {1} to {2}\".format(store, move, obj))\n continue\n else:\n print()\n Error(\"*Choose a valid number, fool*\")\n continue\n else:\n print()\n Error(\"*Choose a valid number, fool*\")\n continue\n\n if verb == \"drink\" and obj == \"potion\" and gameVars.playerProfile[\"healingitems\"][\"potion\"] != 0:\n if gameVars.playerProfile[\"playerhealth\"] != 100:\n drinkingPotion()\n continue\n else:\n Alert(\"Your Health is already full\")\n continue\n else:\n if verb == \"drink\" and obj == \"potion\" and gameVars.playerProfile[\"healingitems\"][\"potion\"] == 0:\n print()\n Error(\"You do not have any potions\")\n continue\n\n if command in cellCommands:\n\n if command == \"gonorth\" and cellVars.cellDoor == \"locked\":\n print(colored(cellNorth, 'green'))\n gameVars.text = cellNorth\n \n if command == \"goeast\":\n print(colored(cellEast, 'green'))\n gameVars.text = cellEast\n \n if command == \"gosouth\":\n print(colored(cellSouth, 'green'))\n gameVars.text = cellSouth\n \n if command == \"gowest\":\n print(colored(cellWest, 'green'))\n gameVars.text = cellWest\n \n if command == \"jumpwindow\":\n print(colored(cellWindow, 'green'))\n gameVars.text = cellWindow\n \n if command == \"checkbrick\":\n print(colored(cellBrick, 'green'))\n gameVars.text = cellBrick\n cellVars.cellBrick = \"true\"\n \n if command == \"takepotion\":\n if cellVars.potion == True:\n addingPotion()\n cellVars.potion = False\n else:\n print()\n Error(\"You have already retrieved the potion\")\n\n if command == \"takekey\":\n invItem = \"Cell Key\"\n addItem(invItem)\n \n if command == \"usekey\":\n keyItem = \"Cell Key\"\n for i in gameVars.playerProfile['inventory']:\n if keyItem in gameVars.playerProfile['inventory'][i]:\n Print(unlockingCellDoor)\n cellVars.cellDoor = \"unlocked\"\n removeItem(keyItem)\n print()\n Print(\" You have escaped the cell.\")\n Print(\" Let us see what lies ahead...\")\n Print(\" *Press enter to continue*\")\n #Continue function\n ctn = input()\n if ctn == \"\":\n level1Input()\n else:\n Error(\"I said press enter... hmm\")\n level1Input()\n else:\n print()\n Error(\"You do not have the correct key...\")\n\n continue\n else:\n print()\n errorResponse()\n continue\n\ndef cellInit(playerName):\n menuStart()\n loadProfileGame(playerName)\n gameVars.level = \"cell\"\n gameVars.potionStrength = 25\n Print(cellOpen)\n userInputcell()\n","sub_path":"cell.py","file_name":"cell.py","file_ext":"py","file_size_in_byte":8473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"80562005","text":"import json\nfrom konlpy.tag import Mecab\nfrom konlpy.tag import Hannanum\nfrom konlpy.tag import Kkma\nfrom konlpy.tag import Komoran\nfrom konlpy.tag import Twitter\n\nimport math\nimport time\nimport operator\nFILEPATH=\"./data.json\"\nDATA={}\ncls=Mecab()\nmaxfreq=dict()\n\ndef TF(nouns):\n\tret=dict()\n\tfreq=dict()\n\tfor noun in nouns:\n\t\tif(len(noun)<2):\n\t\t\tcontinue\n\t\tfreq[noun]=0\n\tfor noun in nouns:\n\t\tif(len(noun)<2):\n\t\t\tcontinue\n\t\tfreq[noun]+=1\n\tfor noun in nouns:\n\t\tif(len(noun)<2):\n\t\t\tcontinue\n\t\tret[noun]=0.5\n\t\tret[noun]+=(0.5*freq[noun])/maxfreq[noun]\n\treturn ret\n\ndef TF3(nouns):\n\tallsize=len(nouns)\n\tret=dict()\n\tfor noun in nouns:\n\t\tif(len(noun)<2):\n\t\t\tcontinue\n\t\tret[noun]=1\n\treturn ret\n\ndef TF2(nouns):\n\tallsize=len(nouns)\n\tret=dict()\n\tfor noun in nouns:\n\t\tif(len(noun)<2):\n\t\t\tcontinue\n\t\tret[noun]=0\n\n\tfor noun in nouns:\n\t\tif(len(noun)<2):\n\t\t\tcontinue\n\t\tret[noun]+=1\n\n\tfor r in ret:\n\t\tret[r]/=allsize\n\n\treturn ret\n\ndef TFIDF(allword, tf):\n\tret=tf\n\tfor word in ret:\n\t\tidf=allword[word]\n\t\tret[word]*=idf\n\t\t\n\treturn ret\ndef initallword(allword, nouns):\n\tfor noun in nouns:\n\t\tif(len(noun)<2):\n\t\t\tcontinue\n\t\tallword[noun]=0\n\ndef readjson(fn):\n\tf=open(fn,'r')\n\tjs=json.loads(f.read())\n\tf.close()\n\treturn js\n\ndef main():\n\tallword=dict()\n\tstart_time=time.time()\n\tDATA=readjson(FILEPATH)\n\ti=0\n\n\tfor data in DATA:\n\t\tsubject=data['subject']\n\t\tcontents=data['contents']\n\t\traw=subject+' '+contents\n\t\tnouns=cls.nouns(raw)\n\t\tinitallword(allword, nouns)\n\t\tinitallword(maxfreq, nouns)\n\n\tfor data in DATA:\n\t\tsubject=data['subject']\n\t\tcontents=data['contents']\n\t\traw=subject+' '+contents\n\t\tnouns=cls.nouns(raw)\n\t\tdd=dict()\n\t\tfor noun in nouns:\n\t\t\tif(len(noun))<2:\n\t\t\t\tcontinue\n\t\t\tdd[noun]=0\n\t\tfor noun in nouns:\n\t\t\tif(len(noun))<2:\n\t\t\t\tcontinue\n\t\t\tdd[noun]+=1\n\n\t\tfor noun in nouns:\n\t\t\tif(len(noun))<2:\n\t\t\t\tcontinue\n\t\t\tif(maxfreq[noun]=3):\n\t\t\t#\tbreak\n\t\t\tprint (kk[0])\n\t\t\tfinal[kk[0]]+=1\n\t\t\tj+=1\n\t\tprint ('----------------------------------------------')\n\tfinal=sorted(final.items(), key=operator.itemgetter(1), reverse=True)\n\tprint (final)\nif __name__==\"__main__\":\n\tmain()\n","sub_path":"NLP/TFIDF.py","file_name":"TFIDF.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"75000098","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('proj', '0017_auto_20151007_1845'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='cv',\n name='specialization',\n field=models.CharField(max_length=30, null=True, blank=True),\n ),\n ]\n","sub_path":"proj/migrations/0018_cv_specialization.py","file_name":"0018_cv_specialization.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"543477833","text":"\n# coding: utf-8\n\n# In[2]:\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport sys\nimport tensorflow as tf\nimport numpy as np\nfrom tqdm import tqdm\nimport cv2\nfrom SBU.VideoReader import SBUReader\nimport resource\n#os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"\"\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\ndef convert_to(videos, action_labels, actor_labels, name, directory):\n if videos.shape[0] != action_labels.shape[0]:\n raise ValueError('Videos size %d does not match action labels size %d.' %\n (videos.shape[0], action_labels.shape[0]))\n if videos.shape[0] != actor_labels.shape[0]:\n raise ValueError('Videos size %d does not match actor labels size %d.' %\n (videos.shape[0], actor_labels.shape[0]))\n\n num_examples = videos.shape[0]\n\n filename = os.path.join(directory, name + '.tfrecords')\n print('Writing', filename)\n writer = tf.python_io.TFRecordWriter(filename)\n for index in range(num_examples):\n video_raw = videos[index].tostring()\n example = tf.train.Example(features=tf.train.Features(feature={\n 'action_label': _int64_feature(int(action_labels[index])),\n 'actor_label': _int64_feature(int(actor_labels[index])),\n 'video_raw': _bytes_feature(video_raw)\n }))\n writer.write(example.SerializeToString())\n writer.close()\n\ndef video_processing(videos_dir):\n vreader = SBUReader(depth=16, sigma=1.0, ksize=4)\n #X, Y_action, Y_actor = vreader.loaddata_LR(videos_dir, train=False)\n\n train_lst, val_lst, test_lst = vreader.loaddata_HR(videos_dir)\n X, Y_action, Y_actor = train_lst[0], train_lst[1], train_lst[2]\n\n print('X shape:{}\\nY_action shape:{}\\nY_actor shape:{}'.format(X.shape,\n Y_action.shape, Y_actor.shape))\n\n return train_lst, val_lst, test_lst\n\n\ndef mem():\n print('Memory usage: % 2.2f MB' % round(\n resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024.0,1)\n )\n\ndef memoryhog(folder):\n path = os.path.join('/home/wuzhenyu_sjtu/Data_Preparation/SBU_videos/noisy_version/RGB', folder)\n print(path)\n train_lst, val_lst, test_lst = video_processing(path)\n convert_to_records(train_lst, 'training_noisy_{}'.format(folder))\n convert_to_records(val_lst, 'validation_noisy_{}'.format(folder))\n convert_to_records(test_lst, 'testing_noisy_{}'.format(folder))\n\n\ndef convert_to_records(lst, name):\n directory = '/home/wuzhenyu_sjtu/Data_Preparation/tfrecords'\n X, Y_action, Y_actor = lst[0], lst[1], lst[2]\n convert_to(X, Y_action, Y_actor, name, directory)\n\nif __name__ == \"__main__\":\n from joblib import Parallel, delayed\n num_cores = 5\n Parallel(n_jobs=num_cores)(delayed(memoryhog)(q) for q in next(os.walk('/home/wuzhenyu_sjtu/Data_Preparation/SBU_videos/noisy_version/RGB'))[1])\n","sub_path":"SBU-exp/data_preparation/convert2records.py","file_name":"convert2records.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"201289182","text":"\"\"\"Tests for the peridynamics modules.\"\"\"\nimport numpy as np\nfrom peridynamics.neighbour_list import create_neighbour_list\nfrom peridynamics.peridynamics import damage, bond_force\n\n\ndef test_damage():\n \"\"\"Test damage function.\"\"\"\n family = np.array([10, 5, 5, 1, 5, 7, 10, 3, 3, 4], dtype=np.int32)\n n_neigh = np.array([5, 5, 3, 0, 4, 5, 8, 3, 2, 1], dtype=np.int32)\n\n damage_actual = damage(n_neigh, family)\n damage_expected = (family - n_neigh) / family\n\n assert np.allclose(damage_actual, damage_expected)\n\n\nclass TestForce():\n \"\"\"Test force calculation.\"\"\"\n\n def test_initial_force(self):\n \"\"\"Ensure forces are zero when there is no displacement.\"\"\"\n r0 = np.array([\n [0.0, 0.0, 0.0],\n [1.0, 0.0, 0.0],\n [0.0, 1.0, 0.0],\n [2.0, 0.0, 0.0],\n [0.0, 0.0, 1.0],\n ])\n horizon = 1.1\n volume = np.ones(5)\n bond_stiffness = 1.0\n nl, n_neigh = create_neighbour_list(r0, horizon, 3)\n\n force_expected = np.zeros((5, 3))\n force_actual = bond_force(r0, r0, nl, n_neigh, volume, bond_stiffness)\n\n assert np.allclose(force_actual, force_expected)\n\n def test_force(self):\n \"\"\"Ensure forces are in the correct direction using a minimal model.\"\"\"\n r0 = np.array([\n [0.0, 0.0, 0.0],\n [1.0, 0.0, 0.0],\n [1.0, 1.0, 0.0],\n ])\n horizon = 1.01\n elastic_modulus = 0.05\n bond_stiffness = 18.0 * elastic_modulus / (np.pi * horizon**4)\n volume = np.full(3, 0.16666667)\n nl, n_neigh = create_neighbour_list(r0, horizon, 3)\n\n # Displace particles, but do not update neighbour list\n r = r0 + np.array([\n [0.0, 0.0, 0.0],\n [0.05, 0.0, 0.0],\n [0.05, 0.05, 0.0]\n ])\n\n actual_force = bond_force(r, r0, nl, n_neigh, volume,\n bond_stiffness)\n\n # Ensure force array is correct\n force_value = 0.00229417\n expected_force = np.array([\n [force_value, 0., 0.],\n [-force_value, force_value, 0.],\n [0., -force_value, 0.]\n ])\n assert np.allclose(actual_force, expected_force)\n","sub_path":"peridynamics/test/test_peridynamics.py","file_name":"test_peridynamics.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"128012721","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('cms', '0016_auto_20160608_1535'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='SnlmtSlaiderZoomSettings',\n fields=[\n ('cmsplugin_ptr', models.OneToOneField(primary_key=True, serialize=False, auto_created=True, related_name='snlmt_slaider_zoom_snlmtslaiderzoomsettings', parent_link=True, to='cms.CMSPlugin')),\n ('title', models.CharField(verbose_name='название', default='', max_length=100, blank=True)),\n ('thumbnail', models.BooleanField(verbose_name='рамка', default=False)),\n ],\n options={\n 'abstract': False,\n },\n bases=('cms.cmsplugin',),\n ),\n ]\n","sub_path":"snlmt_plugins/snlmt_slaider_zoom/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"119531752","text":"#coding=utf-8\nimport socket\nimport re\nimport multiprocessing\n\n\nclass WSGIServer(object):\n\n def __init__(self, server_address):\n # 创建一个tcp套接字\n self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # 允许立即使用上次绑定的port\n self.listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n # 绑定\n self.listen_socket.bind(server_address)\n # 变为被动,并制定队列的长度\n self.listen_socket.listen(2)\n\n def serve_forever(self):\n # \"循环运行web服务器,等待客户端的链接并为客户端服务\"\n while True:\n # 等待新客户端到来\n client_socket, client_address = self.listen_socket.accept()\n print(client_address) # for test\n new_process = multiprocessing.Process(target=self.handleRequest, args=(client_socket,))\n new_process.start()\n\n # 因为子进程已经复制了父进程的套接字等资源,所以父进程调用close不会将他们对应的这个链接关闭的\n client_socket.close()\n\n def handleRequest(self, client_socket):\n # \"用一个新的进程,为一个客户端进行服务\"\n recv_data = client_socket.recv(1024).decode('utf-8')\n print(recv_data)\n requestHeaderLines = recv_data.splitlines()\n for line in requestHeaderLines:\n print(line)\n\n request_line = requestHeaderLines[0]\n get_file_name = re.match(\"[^/]+(/[^ ]*)\", request_line).group(1)\n print(\"file name is ===>%s\" % get_file_name) # for test\n\n if get_file_name == \"/\":\n get_file_name = DOCUMENTS_ROOT + \"/index.html\"\n else:\n get_file_name = DOCUMENTS_ROOT + get_file_name\n\n print(\"file name is ===2>%s\" % get_file_name) # for test\n\n try:\n f = open(get_file_name, \"rb\")\n except IOError:\n response_header = \"HTTP/1.1 404 not found\\r\\n\"\n response_header += \"\\r\\n\"\n response_body = \"====sorry ,file not found====\"\n else:\n response_header = \"HTTP/1.1 200 OK\\r\\n\"\n response_header += \"\\r\\n\"\n response_body = f.read()\n f.close()\n finally:\n client_socket.send(response_header.encode('utf-8'))\n client_socket.send(response_body)\n client_socket.close()\n\n\n# 设定服务器的端口\nSERVER_ADDR = (HOST, PORT) = \"\", 8888\n# 设置服务器服务静态资源时的路径\nDOCUMENTS_ROOT = \"./html\"\n\n\ndef main():\n httpd = WSGIServer(SERVER_ADDR)\n print(\"web Server: Serving HTTP on port %d ...\\n\" % PORT)\n httpd.serve_forever()\n\n\nif __name__ == \"__main__\":\n main()\n pass\n\n","sub_path":"python和linux高级编程阶段/07-http协议-web服务器-并发服务器01/03-Web静态服务器-3-多进程.py","file_name":"03-Web静态服务器-3-多进程.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"229202578","text":"from flask import Flask, render_template, request, jsonify\nfrom predict_sentiment_analysis import get_sentiment\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello_whale():\n return render_template(\"whale_hello.html\")\n\n@app.route('/predict', methods = ['GET', 'POST'])\ndef predict():\n if request.method == 'GET':\n input = request.args.get('input')\n else:\n input = request.get_json(force=True)['input']\n if not input:\n return 'No input value found'\n response = jsonify({'text': get_sentiment(input)})\n response.headers.add('Access-Control-Allow-Origin', '*')\n return response\n\nif __name__ == '__main__':\n app.run(debug=True,use_reloader=False, host='0.0.0.0')\n","sub_path":"part4/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"412974269","text":"import random\nimport requests\nfrom bs4 import BeautifulSoup\nfrom pprint import pprint\n\nnumbers = random.sample(range(800, 861), 5)\nfor num in numbers:\n count = 0\n url = f'https://dhlottery.co.kr/gameResult.do?method=byWin&drwNo={num}'\n req = requests.get(url).text\n soup = BeautifulSoup(req, 'html.parser')\n\n lottery = soup.select('.ball_645')\n print(f'{num} 회차 당첨 번호')\n for lotto in lottery:\n print(lotto.text, end=' ')\n count += 1\n if count == 6:\n print('+', end=' ')\n print('\\n')\n","sub_path":"Python/dict_project/lotto_1.py","file_name":"lotto_1.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"61566700","text":"#! usr/bin/env python\n\n\"\"\"gibbs_sampling.py: Gibbs sampling of an ising model\"\"\"\n\n__author__ = \"elkbrs\"\n\n# imports\nimport numpy as np\nimport pandas as pd\nfrom datetime import date\n\n\n# class\nclass GibbsSampler(object):\n\n def __init__(self, model, burnin=1000, iters=2500, interval=250):\n self.n_nodes = model.size\n self.states = [model.cardinality(i) for i in range(self.n_nodes)] # cardianlity (states) for each node!\n # self.states = model.cardinality()\n np.random.seed(seed=42)\n self.upnext = np.zeros((1, self.n_nodes)).ravel() #self._init_rand()\n self.cur = np.zeros((1, self.n_nodes)).ravel() #self._init_rand()\n self.burnin = burnin\n self.T = iters\n # self.samples = pd.DataFrame(columns=range(self.n_nodes))\n self.interval = interval\n self.model = model\n\n def full_sample(self, cont=None):\n \"\"\"\n\n :param cont: last assignment\n :return:\n \"\"\"\n T = self.burnin + self.T\n if cont:\n self.upnext = cont # TODO possible bug here\n T = self.T\n for i in xrange(T):\n record = i > self.burnin or cont is not None\n self._round(record)\n for j in xrange(self.interval):\n self._round(record=False)\n\n def sample(self, samps=1):\n \"\"\"\n a single sampling process\n :param samps: number of samples to return\n :return:\n \"\"\"\n ret_val = np.zeros(shape=(samps, self.n_nodes))\n for i in xrange(samps):\n self._round(record=True)\n ret_val[i] = self.upnext.copy()\n for j in xrange(self.interval):\n self._round(record=False)\n return ret_val\n\n\n def _round(self, record=True):\n self.cur = self.upnext.copy()\n for i in xrange(self.n_nodes):\n factors = self._factor_compute(i) # assuming locally normalized factors\n energy = 1./(1. + np.exp(-factors))\n theta_i = self.model.unary_dict[i].prob\n self.upnext[i] = self._sample_prob(theta_i, energy)\n # assert np.all(np.greater_equal(self.states, self.upnext)), 'sampled state above'+\\\n # 'possible number'\n\n # self.upnext[i] = 1 if p <= energy else 0\n # if record:\n # self.samples.loc[len(self.samples)] = self.upnext\n\n def _factor_compute(self, i):\n s_i = self.cur[i]\n pairs = np.asarray([self.model.theta_ij(i, j, int(s_i), int(self.cur[j]))\n for j in self.model.nei(i)])\n unary = self.model.theta_i(i, int(s_i))\n return pairs.sum()+unary\n\n\n # def get(self):\n # return self.samples\n\n #\n # def get_matrix(self, last=False):\n # return self.samples.as_matrix() if not last else self.samples.as_matrix()[:-1]\n #\n # def load(self, fname, full=True, form='pickle'):\n # if form == 'pickle':\n # if full:\n # self.samples = pd.read_pickle(fname)\n # else:\n # self.upnext = np.load(fname)\n # elif form == 'csv':\n # self.samples = pd.read_csv(fname)\n # else:\n # raise ('unsupported load method:' + form)\n # return self.samples\n #\n # def save(self, full=True, form='pickle'):\n # fname = 'samples' + str(date.today()) + '_samp_' + str(self.T) + '_p_' + str(self.n_nodes)\n # if form == 'pickle':\n # fname += '.pkl'\n # if full:\n # self.samples.to_pickle(fname)\n # else:\n # fname = 'row_samp_' + str(self.T) + '_p_' + str(self.n_nodes)\n # np.save(fname, self.upnext)\n # elif form == 'csv':\n # fname += '.csv'\n # self.samples.to_csv(fname)\n # else:\n # raise ('unsupported save method:' + form)\n # return fname\n\n def _init_rand(self):\n \"\"\"\n Hopefully this will turn out to a faster converging method rather\n than taking all nodes as ones\n \"\"\"\n init = np.random.random(self.n_nodes)\n init[init < 0.5] = 0\n init[init >= 0.5] = 1\n return init\n\n\n def _sample_prob(self, dist, p):\n \"\"\"\n currently _discrete supports only discrete dist.\n \"\"\"\n # prob = prob.flatten()\n # dist supposed to be positive\n # hence norm is just sum\n mask = dist > 0\n assert np.all(mask), 'dist:\\n{}'.format(dist)\n # norm = dist.sum() #np.linalg.norm(dist)\n # norm = norm if norm else 1e-8\n # prob = dist / norm\n # prob = np.cumsum(prob)\n i = np.searchsorted(dist, p)\n i = i if i < dist.shape[0] else i - 1\n return i\n # for i in xrange(len(prob)):\n # if p < prob[i]:\n # return i\n # raise ('_sample_discrete, weird shit, p=' +\n # str(p) + ' prob=' + np.array_str(dist))\n","sub_path":"samplers/gibbs_sampler.py","file_name":"gibbs_sampler.py","file_ext":"py","file_size_in_byte":5000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"648589737","text":"\"\"\"\n 从多处使用线程同时下载文件练习\n *文件资源库从本地目录变为 网络地址address\n *多线程从网络中获取文件,在本地下载1个\n\"\"\"\nusl = ['/home/tarena/桌面/',\n '/home/tarena/模板/',\n '/home/tarena/音乐/',\n '/home/tarena/图片/',\n '/home/tarena/下载/',\n '/home/tarena/视频/']\nFTP='/home/tarena'\nfrom threading import Thread,Lock\nimport os\nfrom socket import *\nclass FerServer(Thread):\n def __init__(self,c):\n super().__init__()\n self.c = c\n def run(self):\n while True:\n data = self.c.recv(128)\n def dowload(self,filename):\n try:\n open(FTP,'wb')\n except Exception as e:\n print(e)\n\n\ndef main():\n s =socket()\n s.bind(('127.0.0.1',8888))\n s.listen(3)\n print(\"listen the port 8080...\")\n while True:\n try:\n c, addr = s.accept()\n print(\"Connect from \", addr)\n except KeyboardInterrupt:\n os._exit(0)\n except Exception as e:\n print(e)\n continue\n t = FerServer(c)\n t.start()\n\n\n\n","sub_path":"month02/exercise2/exercise04.py","file_name":"exercise04.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"288804996","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport math\nimport torch.nn.functional as F\n\n############################################################\n# ResNet\n############################################################\ndef conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * 4)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n\n def __init__(self, block, layers, num_classes=1000):\n self.inplanes = 64\n super(ResNet, self).__init__()\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def load_weights(self, path):\n model_dict = self.state_dict()\n print('loading model from {}'.format(path))\n try:\n #state_dict = torch.load(self.path)\n # self.load_state_dict({k: v for k, v in state_dict.items() if k in self.state_dict()})\n pretrained_dict = torch.load(path)\n from collections import OrderedDict\n tmp = OrderedDict()\n for k,v in pretrained_dict.items():\n if k in model_dict:\n tmp[k] = v\n # pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}\n # model_dict.update(pretrained_dict)\n model_dict.update(tmp)\n self.load_state_dict(model_dict)\n except:\n print ('loading model failed, {} may not exist'.format(path))\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n C1 = self.maxpool(x)\n\n C2 = self.layer1(C1)\n C3 = self.layer2(C2)\n C4 = self.layer3(C3)\n C5 = self.layer4(C4)\n\n return C1, C2, C3, C4, C5\n\n############################################################\n# Pose Estimation Graph\n############################################################\n\nclass pose_estimation(nn.Module):\n def __init__(self, class_num, pretrain=True):\n super(pose_estimation, self).__init__()\n self.resnet = ResNet(Bottleneck, [3, 4, 6, 3]) # resnet50\n if pretrain == True:\n self.model_path = '/data/xiaobing.wang/.torch/models/resnet50-19c8e357.pth'\n self.resnet.load_weights(self.model_path)\n self.apply_fix()\n self.block = nn.Sequential(nn.Conv2d(512, 128, 1, 1, 0),nn.ReLU(inplace=True),\n nn.Conv2d(128, 128, 3, 1, 1), nn.ReLU(inplace=True),\n\t\t nn.Conv2d(128, 128, 3, 1, 1), nn.ReLU(inplace=True),\n\t\t nn.Conv2d(128, 128, 3, 1, 1), nn.ReLU(inplace=True),\n\t\t nn.Conv2d(128, 512, 3, 1, 1), nn.ReLU(inplace=True)\n\t\t )\n self._init_weights(self.block)\n self.predict = nn.Conv2d(512, 25, 1, 1, 0)\n\n def _init_weights(self, model):\n for m in model:\n if isinstance(m, nn.Conv2d):\n m.weight.data.normal_(0, 0.01)\n if m.bias is not None:\n m.bias.data.zero_()\n def apply_fix(self):\n # 1. fix bn\n # 2. fix conv1 conv2\n for param in self.resnet.conv1.parameters():\n param.requires_grad = False\n for param in self.resnet.layer1.parameters():\n param.requires_grad = False\n\n\n def forward(self, x):\n C1, C2, C3, C4, C5 = self.resnet(x)\n\n out = self.block(C3)\n predict = self.predict(out)\n return predict","sub_path":"models/bk/CPM_ResNet.py","file_name":"CPM_ResNet.py","file_ext":"py","file_size_in_byte":7009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"103011760","text":"#!/usr/bin/env python\n#this is a copy of someting i wrote for a class; contains an example of argparse and requests \nimport argparse\nimport requests\nimport sys\n\nparser = argparse.ArgumentParser (description='writes a url to file')\nparser.add_argument('myurl', help='enter a url')\nparser.add_argument('myfile', help='outputfile')\nparser.add_argument('--content', '-c' , default='html', choices=['html', 'json'] , help='content output format. default html')\nargs = parser.parse_args()\n\nr = requests.get(args.myurl ,verify=False )\n\nif args.content == 'json':\n try:\n mycontent = r.json()\n except ValueError:\n print(\"Error not JSON\")\n sys.exit(1)\nelse: \n mycontent = r.text\n\nfile = open(args.myfile, 'w+')\nfile.write(mycontent.encode(\"UTF-8\"))\n\n\n\n\n\n\n","sub_path":"my_python/argparse_requests.py","file_name":"argparse_requests.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"292882937","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Software : nothing\n# @File : redis_base.py\n# @Author : zaniu (Zzaniu@126.com)\n# @Date : 2019/3/20 14:29 \n# @Description : redis订阅\nimport datetime\nimport functools\nimport hashlib\nimport json\nimport os\nimport pickle\n\nimport redis\n\n\nBASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\ndef now_time():\n return datetime.datetime.now()\n\n\ndef md5(value):\n \"\"\"value是unicode,unicode无法存储,需要转换成str,需要指定某种编码(encode)去转换成str\"\"\"\n return hashlib.md5(json.dumps(value).encode()).hexdigest()\n\n\nclass RedisHelper:\n def __init__(self, chan='default'):\n self.__conn = redis.Redis(host='111.230.151.179', password='!@admin')\n self.chan = chan\n\n def public(self, msg):\n self.__conn.publish(self.chan, msg) # 发布订阅消息\n return True\n\n def subscribe(self):\n pub = self.__conn.pubsub() # 打开订阅功能\n pub.subscribe(self.chan) # 声明/设置 订阅频道\n pub.parse_response() # 开始订阅,第一次会返回一条订阅信息,第二次开始持续订阅\n return pub\n\n\ndef singleton(cls):\n \"\"\"\n 将一个类作为单例\n 来自 https://wiki.python.org/moin/PythonDecoratorLibrary#Singleton\n \"\"\"\n\n cls.__new_original__ = cls.__new__\n\n @functools.wraps(cls.__new__)\n def singleton_new(cls, *args, **kw):\n it = cls.__dict__.get('__it__')\n if it is not None:\n return it\n\n cls.__it__ = it = cls.__new_original__(cls, *args, **kw)\n it.__init_original__(*args, **kw)\n return it\n\n cls.__new__ = singleton_new\n cls.__init_original__ = cls.__init__\n cls.__init__ = object.__init__\n\n return cls\n\n\n@singleton\nclass MyRq:\n TIME_OUT = 600\n\n def __init__(self):\n self.funcs = {}\n\n def route(self, **kwargs):\n \"\"\"借鉴 flask route 实现\"\"\"\n def decorator(f):\n # 借鉴RQ,任务不能与 task.delay() 在同一个文件\n assert f.__module__ != \"__main__\", 'Functions from the __main__ module cannot be processed by workers'\n task_name = '.'.join([f.__module__, f.__name__])\n self.add_func(task_name, **kwargs)\n f.run = f\n f.delay = self.run(task_name)\n return f\n return decorator\n\n def add_func(self, task_name, **kwargs):\n if self.funcs.__contains__(task_name): raise Exception('重复函数: {}'.format(task_name))\n self.funcs.update({\n task_name: {\n 'queue': kwargs.get('queue', 'default'),\n 'timeout': kwargs.get('timeout', self.TIME_OUT),\n }\n })\n\n def run(self, task_name):\n def delay(*args, **kwargs):\n print('发布任务: ', task_name)\n # TODO 目前是订阅形式,以后要将这个放到redis上面去,pickle,加特定前缀用来标识,ID可有可无吧(暂时不知道ID的意义)\n self.funcs.get(task_name).update({'args': pickle.dumps(args), 'kwargs': pickle.dumps(kwargs)})\n RedisHelper(self.funcs.get(task_name).get('queue')).public(pickle.dumps({task_name: self.funcs.get(task_name)}))\n return delay\n","sub_path":"redis_publish/redis_base.py","file_name":"redis_base.py","file_ext":"py","file_size_in_byte":3256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"450010036","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nradiobutn-eg3.py\nCreated on Tue May 14 14:12:58 2019\n\n@author: madhu\n\"\"\"\n\nimport tkinter as tk\n\nroot = tk.Tk()\nv = tk.IntVar()\nv.set(20) # initializing the choice, i.e. Python\n\nlanguages = [\n (\"Python\",10),\n (\"Perl\",20),\n (\"Java\",30),\n (\"C++\",40),\n (\"C\",50)\n]\n\ndef ShowChoice():\n print(v.get())\n\ntk.Label(root, \n text=\"\"\"Choose your favourite \nprogramming language:\"\"\",\n justify = tk.LEFT,\n font = 'Verdana 26 bold',\n padx = 20).pack()\n\n#for val, language in enumerate(languages):\nfor language in languages:\n tk.Radiobutton(root, \n text=language[0],\n font = 'Verdana 26 bold',\n width=20,\n indicatoron = 0,\n padx = 20, \n variable=v, \n# value=val,\n value=language[1],\n command=ShowChoice).pack(anchor=tk.W)\n\nroot.mainloop()\n","sub_path":"radiobutn-eg3.py","file_name":"radiobutn-eg3.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"304349142","text":"from flask import Blueprint\n\nfrom MORTWebsite.API.users import routes as user_api_routes\nfrom MORTWebsite.API.orders import routes as orders_api_routes\nfrom MORTWebsite.API.cms import routes as cms_api_routes\n\nroutes = user_api_routes\nroutes += orders_api_routes\nroutes += cms_api_routes\n\napi = Blueprint('api', __name__)\n\nfor r in routes:\n api.add_url_rule(\n r['rule'],\n endpoint=r.get('endpoint', None),\n view_func=r['view_func'],\n **r.get('options', {}))\n","sub_path":"MORTWebsite/API/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"566050772","text":"import torch\nimport torch.nn as nn\nfrom sklearn.model_selection import train_test_split, StratifiedKFold , KFold\nimport torch.nn.functional as F\nfrom fastai.core import split_by_idxs\nfrom fastai.core import children\n\nclass Unet34(nn.Module):\n def __init__(self, rn):\n super().__init__()\n self.rn = rn\n self.sfs = [SaveFeatures(rn[i]) for i in [2,4,5,6]]\n self.up1 = UnetBlock(512,256,128)\n self.up2 = UnetBlock(128,128,128)\n self.up3 = UnetBlock(128,64,128)\n self.up4 = UnetBlock(128,64,128)\n self.up5 = nn.ConvTranspose2d(128, 1, 2, stride=2)\n \n def forward(self,img,depth):\n x = F.relu(self.rn(img))\n x = self.up1(x, self.sfs[3].features)\n x = self.up2(x, self.sfs[2].features)\n x = self.up3(x, self.sfs[1].features)\n x = self.up4(x, self.sfs[0].features)\n x = self.up5(x)\n return x[:,0]\n \n def close(self):\n for sf in self.sfs: sf.remove()\n \nclass SaveFeatures():\n features=None\n def __init__(self, m): self.hook = m.register_forward_hook(self.hook_fn)\n def hook_fn(self, module, input, output): self.features = output\n def remove(self): self.hook.remove()\n \nclass UnetBlock(nn.Module):\n def __init__(self, up_in, x_in, n_out):\n super().__init__()\n up_out = x_out = n_out//2\n self.x_conv = nn.Conv2d(x_in, x_out, 1)\n self.tr_conv = nn.ConvTranspose2d(up_in, up_out, 2, stride=2)\n self.bn = nn.BatchNorm2d(n_out)\n \n def forward(self, up_p, x_p):\n up_p = self.tr_conv(up_p)\n x_p = self.x_conv(x_p)\n cat_p = torch.cat([up_p,x_p], dim=1)\n return self.bn(F.relu(cat_p))\n \nclass UnetModel():\n def __init__(self,model,lr_cut,name='unet'):\n self.model,self.name = model,name\n self.lr_cut = lr_cut\n\n def get_layer_groups(self, precompute):\n lgs = list(split_by_idxs(children(self.model.rn), [self.lr_cut]))\n return lgs + [children(self.model)[1:]]\n","sub_path":"models/unet.py","file_name":"unet.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"338449828","text":"import warnings\nimport numpy as np\nimport pandas as pd\nimport scipy.stats as st\nimport statsmodels.api as sm\nfrom warnings import filterwarnings\nfilterwarnings('ignore')\nfrom keyBoost.consensus.utils import deduplication\nfrom keyBoost.consensus.ranking import rank_consensus\n\n\n# Allows to set an optimal scale for the histogram in terms of bins\ndef freedman_diaconis_rule(data):\n a = np.array(data)\n if len(data) <2:\n return 1\n h = 2*(np.percentile(data,75)-np.percentile(data,25))*len(data)**(-1/3)\n\n if h==0:\n return len(data)\n else:\n return int(np.ceil((max(data)-min(data))/h))\n\n\n\n# Estimation of the parameters of an a priori selected statistical model\ndef maximum_likelyhood_estimation(data,\n distribution):\n\n data = np.array(data, dtype=float)\n\n params = distribution.fit(data)\n\n arg = params[:-2] # distribution parameter vector\n loc = params[-2] # location parameter\n scale = params[-1] # scale parameter\n\n return arg, loc, scale\n\n\n# Selects the best discriminative statistical model in terms of the SSE metric\n\ndef DSM_selection(data,\n distributions,\n bins):\n\n y, x = np.histogram(a=data,\n bins=bins,\n density=True)\n x = (x + np.roll(x,-1))[:-1] / 2.0\n\n # By default, we suppose that the data fits a gaussian model\n\n best_distribution = st.norm\n best_arg,best_loc,best_scale = (None, 0.0, 1.0)\n best_sse = np.inf\n\n for distribution in distributions:\n\n arg, loc, scale = maximum_likelyhood_estimation(data,distribution)\n\n pdf = distribution.pdf(x, loc=loc, scale=scale, *arg)\n sse = np.sum(np.power(y-pdf,2.0))\n\n if best_sse > sse:\n best_distribution = distribution\n best_arg = arg\n best_loc = loc\n best_scale = scale\n best_sse = sse\n\n\n return best_distribution, best_arg, best_loc, best_scale\n\n\n# packs isolated parameters of a statistical model into a single list\n\ndef pack_params(arg,loc,scale):\n params = list()\n a = [arg,loc,scale]\n for x in a:\n if type(x)!=tuple:\n params.append(x)\n else:\n for t in x:\n params.append(t)\n return tuple(params)\n\n# performs Kolmogorov Smirnov Test\n\ndef kolmogorov_smirnov_test(distribution,\n data,\n arg,\n loc,\n scale,alpha):\n\n args = pack_params(arg,loc,scale)\n\n _, p_value = st.kstest(rvs=data,\n cdf=distribution.name,\n args=args,\n alternative='two-sided')\n\n\n return True if p_value >= alpha else False # Pass the test if we do not reject H0 : the score distribution is discriminative\n\n\n# Checks that the MLE parmaters lies within the boundaries of what we set as discriminative parameters\n# for each statistical model\n\ndef DSM_params_check(distribution,\n arg):\n\n if distribution == st.powerlaw:\n\n return True if 0 l:\n\n auc_lamda = calc_te_auc(clf_lamda, data)\n auc_nu = calc_te_auc(clf_nu, data)\n if auc_lamda < auc_nu:\n x_queue.append(lamda)\n y_queue.append(auc_lamda)\n\n interval[0] = lamda\n lamda = nu\n clf_lamda = clf_nu\n nu = calc_nu()\n clf_nu = RandomForestClassifier(**dict([[param, nu], ['random_state', 0]])).fit(train_x, train_y)\n\n else:\n x_queue.append(nu)\n y_queue.append(auc_nu)\n\n interval[1] = nu\n nu = lamda\n clf_nu = clf_lamda\n lamda = calc_lamda()\n clf_lamda = RandomForestClassifier(**dict([[param, lamda], ['random_state', 0]])).fit(train_x, train_y)\n\n # print(interval[0], lamda, nu, interval[1])\n\n clf_low = RandomForestClassifier(**dict([[param, interval[0]], ['random_state', 0]])).fit(train_x, train_y)\n clf_up = RandomForestClassifier(**dict([[param, interval[1]], ['random_state', 0]])).fit(train_x, train_y)\n\n return interval[0], calc_te_auc(clf_low, data), interval[1], calc_te_auc(clf_up, data), time.time()-start_time, (x_queue, y_queue)\n\n\nif '__main__' == __name__:\n with open('./data/data.pkl', 'rb') as f:\n data = pickle.load(f)\n\n with open('param.json', 'r') as f:\n params = json.load(f)\n\n for param in params:\n lower, lower_auc, upper, upper_auc, exec_time, points = golden_search(param,\n data,\n params[param])\n print(param)\n print(f'lower bound: {lower}, auc: {lower_auc}')\n print(f'upper bound: {upper}, auc: {upper_auc}')\n print(f'execute time: {exec_time}')\n print('*' * 50)\n pickle.dump(points, open(f'./log/golden_{param}.pkl', 'wb'))\n","sub_path":"golden_search.py","file_name":"golden_search.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"422792022","text":"inp = open('Prob07.in.txt', 'r')\r\n\r\nt = int(inp.readline())\r\n\r\nfor _ in range(t):\r\n n = int(inp.readline())\r\n arr = []\r\n bad = []\r\n for __ in range(n):\r\n arr.append(inp.readline().strip())\r\n\r\n for i in range(len(arr)):\r\n x = arr[i].lower()\r\n if x != x[::-1]:\r\n bad.append(str(i + 1))\r\n if len(bad) >= 1:\r\n print(\"False -\", \", \".join(bad))\r\n else:\r\n print(\"True\")\r\n","sub_path":"07.py","file_name":"07.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"127225206","text":"import os\nimport numpy as np\n\n\ndef getPaths(folder): #Must be in dir with desired names \n\tf = os.popen('ls /Users/haynesstephens1/Desktop/research/uh-ifa/smass-data/{0}'.format(folder))\n\tpaths = []\n\tfor i in f.readlines():\n\t\tpaths.append('/Users/haynesstephens1/Desktop/research/uh-ifa/smass-data/{0}/'.format(folder) + i.strip('\\n'))\n\treturn paths\n\n\ndef loadWavelengths(path):\n\tarr = np.loadtxt(path)\n\twavelengths = arr[:, 0]\n\treturn wavelengths\n\n\ndef increasing(wavelengths):\n\tif wavelengths[0] > wavelengths[-1]:\n\t\treturn False\n\telse:\n\t\treturn True\n\n\ndef correctUnits(wavelengths):\n\tif not increasing(wavelengths):\n\t\twavelengths = wavelengths[::-1]\n\tfirst = wavelengths[0]\n\tif first < (1):\n\t\tunit = 'micro'\n\telif first < (10 ** 3):\n\t\tunit = 'nano'\n\telif first < (10 ** 4):\n\t\tunit = 'angstrom'\n\n\tif unit == 'nano':\n\t\twavelengths = wavelengths / (10 ** 3)\n\telif unit == 'angstrom':\n\t\twavelengths = wavelengths / (10 ** 4)\n\treturn wavelengths\n\n\ndef goodRange(wavelengths):\n\tfirst = wavelengths[0]\n\tlast = wavelengths[-1]\n\tif (first <= 0.45) and (last >= 2.45):\n\t\treturn True\n\telse:\n\t\treturn False\n\n\ndef makeBadFolder(folder):\n\tos.system('mkdir -p /Users/haynesstephens1/Desktop/research/uh-ifa/smass-data/{0}/bad'.format(folder))\n\treturn\n\n\ndef moveBadFile(path, folder):\n\tos.system('mv {0} /Users/haynesstephens1/Desktop/research/uh-ifa/smass-data/{1}/bad'.format(path, folder))\n\treturn\n\n\ndef getTheGoods(folder):\n\tpaths = getPaths(folder)\n\tmakeBadFolder(folder)\n\tfor path in paths:\n\t\ttry:\n\t\t\twavelengths = loadWavelengths(path)\n\t\t\twavelengths = correctUnits(wavelengths)\n\t\t\tif not goodRange(wavelengths):\n\t\t\t\tmoveBadFile(path, folder)\n\t\texcept ValueError:\n\t\t\tprint(path)\n\t\t\tmoveBadFile(path, folder)\n\tprint('GOT THE GOODS.')\n\treturn\n\n\ndef printLowHigh(folder):\n\tpaths = getPaths(folder + '/bad')\n\tfor path in paths:\n\t\ttry:\n\t\t\twavelengths = loadWavelengths(path)\n\t\t\tprint(wavelengths[0], wavelengths[-1])\n\t\texcept ValueError:\n\t\t\tprint(path)\n\treturn\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ifa/smass/smassFilter.py","file_name":"smassFilter.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"271081197","text":"import os\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\n# Database\n# https://docs.djangoproject.com/en/3.2/ref/settings/#databases\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'wedding_quiz',\n 'HOST': '',\n 'PORT': '',\n }\n}\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'django-insecure-_!+3w&excto@0az!t*32yriwxpwkvq$7@=x(@4a1hvl=4rxys9'\n\n\nDEBUG = True","sub_path":"wedding_quiz/local_settings.py","file_name":"local_settings.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"435824905","text":"from picamera.array import PiRGBArray\nfrom picamera import PiCamera\nimport time\nimport cv2\nimport numpy as np\nimport math\nimport vision21 as vision\nfrom networktables import NetworkTable\n\n#set up tables\nipAddress = \"192.168.1.110\"\ntable = \"Vision\"\n\n#initialise the camera\nframerate = 5\nresolutionX = 640\nresolutionY = 480\nshutterspeed = 500\niso = 500\ncamera,rawCapture = vision.camera_initialise(framerate,resolutionX,resolutionY,shutterspeed,iso)\nvp = vision.init_network_tables(ipAddress, table)\n\n#settings for low target\ntarget = vision.Target()\ntarget.add_HSV_values(np.array([40,80,70]), np.array([80, 200,255]))\ntarget.add_vertices(4,10)\ntarget.add_width_and_height(5,5)\ntarget.add_solidity(0.4,1)\ntarget.add_aspect_ratio(.2,1)\nh = 0\ns = 0\nv = 0\n# allow the camera to warmup\ntime.sleep(0.1)\n# capture frames from the camera\nfor frame in camera.capture_continuous(rawCapture, format=\"bgr\", use_video_port=True):\n\t# grab the raw NumPy array representing the image, then initialize the timestamp\n\t# and occupied/unoccupied text\n\timgOriginal = frame.array\n\t\n\tkey = cv2.waitKey(1) & 0xFF\n\t\n\t#this is set to work with the gear targets. The image size and solidity need to be changed to work with other targets\n\tstatus = \"No Targets\"\n\t\n\t#change the name of the image file as needed. File needs to be in the same directory as the script\n\timgHSV = cv2.cvtColor(imgOriginal, cv2.COLOR_BGR2HSV)\n\th = 0 \n\tbreak1 = 0\n\tbreak2 = break1\n\t# for reflective tape with our green medusa \n\tfor h in range(0,100):\n\t\t\n\t\tfor s in range(0,255):\n\t\t\t\n\t\t\tfor v in range(0,255):\n\t\t\t\tif key == ord(\"q\"):\n\t\t\t\t\tbreak\n\t\t\t\tif h< 15:\n\t\t\t\t\ttarget.add_HSV_values(np.array([0,0,0]), np.array([h, s,v]))\n\t\t\t\telse:\n\t\t\t\t\ttarget.add_HSV_values(np.array([h-15,s-15,v-15]), np.array([h,s,v]))\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\timgThresh = cv2.inRange(imgHSV, target.lower_HSV, target.upper_HSV)\n\t\t\t\timgThresh2 = imgThresh\n\t\t\t\t#cv2.imshow('imgThresh2', imgThresh2)\n\t\t\t\tcv2.imwrite('imgThresh', imgThresh2)\n\t\t\t\t# find contours in the edge map\n\t\t\t\t(im2, cnts, hierarchy) = cv2.findContours(imgThresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\t\n\n\t\t\t\t#save center values\n\t\t\t\tlistCenterX = []\n\t\t\t\tlistCenterY = []\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t# loop over the contours\n\t\t\t\tfor c in cnts:\n\t\t\t\t\t# approximate the contour\n\t\t\t\t\tperi = cv2.arcLength(c, True)\n\t\t\t\t\tapprox = cv2.approxPolyDP(c, 0.01 * peri, True)\n\t\t\t\t \n\t\t\t\t\t# ensure that the approximated contour is \"roughly\" rectangular\n\t\t\t\t\tif len(approx) >= target.vertices_lower and len(approx) <= target.vertices_upper:\n\t\t\t\t\t\t# compute the bounding box of the approximated contour and\n\t\t\t\t\t\t# use the bounding box to compute the aspect ratio\n\t\t\t\t\t\tx, y, w, h = cv2.boundingRect(approx)\n\t\t\t\t\t\taspectRatio = w / float(h)\n\t\t\t\t \n\t\t\t\t\t\t# compute the solidity of the original contour\n\t\t\t\t\t\tarea = cv2.contourArea(c)\n\t\t\t\t\t\thullArea = cv2.contourArea(cv2.convexHull(c))\n\t\t\t\t\t\tsolidity = area / float(hullArea)\n\t\t\t\t\t\t \n\t\t\t\t\t\t# compute whether or not the width and height, solidity, and aspect ratio of the contour falls within appropriate bounds\n\t\t\t\t\t\tkeepDims = w > target.width and h > target.height\n\t\t\t\t\t\tkeepSolidity = solidity > target.solidity_lower and solidity < target.solidity_upper\n\t\t\t\t\t\tkeepAspectRatio = aspectRatio >= target.aspect_ratio_lower and aspectRatio <= target.aspect_ratio_upper\n\t\t\t\t\t\t\n\t\t\t\t\t\t# ensure that the contour passes all our tests\n\t\t\t\t\t\tif keepDims and keepSolidity and keepAspectRatio:\n\t\t\t\t\t\t\t# draw an outline around the target and update the status\n\t\t\t\t\t\t\t# text\n\t\t\t\t\t\t\timgOriginal = vision.outline_rectangle_red(imgOriginal, approx)\n\t\t\t\t\t\t\tstatus = \"Target(s) Acquired\"\n\t\t\t\t \n\t\t\t\t\t\t\t# compute the center of the contour region and draw the\n\t\t\t\t\t\t\t# crosshairs\n\t\t\t\t\t\t\tM = cv2.moments(approx)\n\t\t\t\t\t\t\tlistCenterX, listCenterY, imgOriginal = vision.center_of_contour(imgOriginal,approx,w,h,M,listCenterX,listCenterY)\n\t\t\t\t\t\t\tax,ay,aw,ah = cv2.boundingRect(c)\n\t\t\t\t\t\t\tcv2.rectangle(imgOriginal,(ax,ay),(ax+aw,ay+ah),(0,255,0),2)\n\t\t\t\t\t\t\t\n\t\t\tif key == ord(\"q\"):\n\t\t\t\tbreak1= 1\n\t\t\t\tbreak\t\t\t\t\n\t\t\tv +=10\n\t\tif break1 == 1:\n\t\t\tbreak2 =1\n\t\t\tbreak\n\t\ts+=10\n\tif break2 == 1:\n\t\tbreak\n\th+=10\n\t# draw the status text on the frame\t\n\timgOriginal = vision.draw_box(imgOriginal)\n\timgOriginal,cX,cY = vision.show_center_data(listCenterX,listCenterY,imgOriginal,status,vp)\n\timgOriginal = vision.show_dist_data(imgOriginal,listCenterX,vp)\n\terrorX = vision.calc_percent_error_X(resolutionX, listCenterX)\n\timgOriginal = vision.disp_percent_error_X(imgOriginal, errorX,listCenterX,vp)\n\tdel listCenterX[:]\n\tdel listCenterY[:]\n\t\n\t# clear the stream in preparation for the next frame\n\t#cv2.imshow(\"Frame\", imgOriginal)\n\tkey = cv2.waitKey(1) & 0xFF\n\trawCapture.truncate(0)\n \n\t# if the `q` key was pressed, break from the loop\n\tif key == ord(\"q\"):\n\t\tbreak\n\ncamera.close()\ncv2.destroyAllWindows()\n","sub_path":"1_23gearvisionVideo.py","file_name":"1_23gearvisionVideo.py","file_ext":"py","file_size_in_byte":4761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"265486603","text":"\"\"\"Somme des nombres de 0 a n\nAuteur : Manon Louvard\ndate : 11 septembre 2019\"\"\"\n\n# initialisation des variables\nn = int(input(\"n ? \\n\"))\nres = 0\ni = 0\n\n# boucle tant que i <= n\n# additionne tous les entiers i compris entre 0 et n\nwhile i <= n :\n\tres = res + i\n\ti += 1\n\n# affiche la somme obtenue\nprint(\"Somme = \", res)\n","sub_path":"Cours/Fiche1/02_somme.py","file_name":"02_somme.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"393698278","text":"import requests\nimport json\n\n# Magic value\n_key = '8wN4p5aXqbVsbK3-O5R9ekbSN-5d2a'\n_url = 'https://elevation-api.io/api/elevation?key=%s&resolution=%s&points=(%f,%f)'\n# _url = 'https://elevation-api.io/api/elevation?resolution=%s&points=(%f,%f)'\n_defaultResolution = '30'\n\ndef queryElevationApi (latitude, longitude, resolution=None, verbose=False):\n\n fmtUrl = _url % (_key, resolution or _defaultResolution, latitude, longitude)\n # fmtUrl = _url % (resolution or _defaultResolution, latitude, longitude)\n\n if verbose:\n print(\"Querying\", fmtUrl)\n response = requests.get(fmtUrl)\n\n if verbose:\n print(response)\n return response\n\ndef getElevation (latitude, longitude, resolution=None, verbose=False):\n return json.loads(queryElevationApi(latitude,longitude,resolution,verbose).text)['elevations'][0]['elevation']\n","sub_path":"hack/code/elevation.py","file_name":"elevation.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"463014159","text":"import os\n\nif __name__ == '__main__':\n matrices = []\n matrices_locations = []\n\n for dirname, _, filenames in os.walk('../matrices/mtx'):\n for filename in filenames:\n print(filename)\n matrices_locations.append(os.path.join(dirname, filename))\n matrices.append(filename)\n\n print(matrices)\n","sub_path":"development/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"544868151","text":"import io\nfrom nodal import types\n\ndef split_node_name(node):\n dot = node.find('.')\n if dot != -1:\n group = node[:dot]\n node = node[dot+1:]\n else:\n group = ''\n return group, node\n\ndef join_node_name(group, node):\n return (group + '.' if group else '') + node\n\ndef check_shell(node_type, shell):\n if shell is None:\n raise RuntimeError(\"%s nodes need to run in a shell\" % node_type)\n\ndef check_args(__node, **kwargs):\n for name, value in kwargs.items():\n if value is None:\n raise RuntimeError(\"Input '%s' to node '%s' cannot be none\" % (name, __node))\n\ndef check_functions(node_type):\n shell = lambda shell: check_shell(node_type, shell)\n args = lambda __node, **kwargs: check_args(node_type + '.' + __node, **kwargs)\n\n return shell, args\n\ndef repr_value(v):\n if v is None:\n return 'None'\n\n elif isinstance(v, str):\n return v\n\n elif callable(v) and not (isinstance(v, io.IOBase) or\n isinstance(v, bytes) or\n isinstance(v, bytearray)):\n return repr(v)\n\n else:\n return types.str(v)\n","sub_path":"nsh/node_lib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"257753147","text":"from keras import backend as K\nfrom keras.models import load_model\nimport os\nimport numpy as np\nimport scipy\n\nfrom imagestoarray import preprocess_image, deprocess_image\n\nMODEL = load_model('model3.h5')\n\nDREAM = MODEL.input\n\nHYPERPARAMETERS = {\n 'step':0.01, # Gradient ascent step size\n 'num_octave':3, # Number of scales at which to run gradient ascent\n 'octave_scale':1.4, # Size ratio between scales\n 'iterations':20 , # Number of ascent steps per scale\n 'max_loss':10.\n}\n\nIMAGE_PATH = 'pitbull/images/' + os.listdir('pitbull/images/')[0]\n\nSETTINGS = None\n\ndef define_loss(K=K, settings=SETTINGS, model=MODEL):\n layer_dict = dict([(layer.name, layer) for layer in model.layers])\n loss = K.variable(0.)\n for layer_name in list(layer_dict.keys()):\n # Add the L2 norm of the features of a layer to the loss.\n # Ignoring settings for now\n #assert layer_name in layer_dict.keys(), 'Layer ' + layer_name + ' not found in model.'\n #coeff = settings['features'][layer_name]\n coeff = 1\n x = layer_dict[layer_name].output\n # We avoid border artefacts by only involving non-border pixels in the loss.\n scaling = K.prod(K.cast(K.shape(x), 'float32'))\n if K.image_data_format() == 'channels_first':\n loss += coeff * K.sum(K.square(x[:, :, 2: -2, 2: -2])) / scaling\n else:\n loss += coeff * K.sum(K.square(x[:, 2: -2, 2: -2, :])) / scaling\n return loss\n\n\ndef compute_gradients(loss, dream=DREAM, K=K):\n grads = K.gradients(loss, dream)[0]\n grads /= K.maximum(K.mean(K.abs(grads)), K.epsilon())\n return grads\n\n\ndef eval_loss_and_grads(x):\n #fetch_loss_and_grads defined in at runtime\n outs = fetch_loss_and_grads([x])\n loss_value = outs[0]\n grad_values = outs[1]\n return loss_value, grad_values\n\n\ndef resize_img(img, size):\n img = np.copy(img)\n if K.image_data_format() == 'channels_first':\n factors = (1, 1,\n float(size[0]) / img.shape[2],\n float(size[1]) / img.shape[3])\n else:\n factors = (1,\n float(size[0]) / img.shape[1],\n float(size[1]) / img.shape[2],\n 1)\n return scipy.ndimage.zoom(img, factors, order=1)\n\n\ndef gradient_ascent(x, iterations, step, max_loss=None):\n for i in range(iterations):\n loss_value, grad_values = eval_loss_and_grads(x)\n if max_loss is not None and loss_value > max_loss:\n break\n print('..Loss value at', i, ':', loss_value)\n x += step * grad_values\n return x\n\n\ndef save_img(img, fname):\n pil_img = deprocess_image(np.copy(img))\n scipy.misc.imsave(fname, pil_img)\n\n\ndef path_to_pyramid(base_image_path=IMAGE_PATH, num_octave=HYPERPARAMETERS['num_octave'],\n octave_scale=HYPERPARAMETERS['octave_scale']):\n img = preprocess_image(base_image_path)\n if K.image_data_format() == 'channels_first':\n original_shape = img.shape[2:]\n else:\n original_shape = img.shape[1:3]\n successive_shapes = [original_shape]\n for i in range(1, num_octave):\n shape = tuple([int(dim / (octave_scale ** i)) for dim in original_shape])\n successive_shapes.append(shape)\n successive_shapes = successive_shapes[::-1]\n original_img = np.copy(img)\n shrunk_original_img = resize_img(img, successive_shapes[0])\n return successive_shapes, original_img, shrunk_original_img\n\n\ndef deepdream(successive_shapes, img, shrunk_original_img, iterations=HYPERPARAMETERS['iterations'],\n step=HYPERPARAMETERS['step'], max_loss=HYPERPARAMETERS['max_loss']):\n for shape in successive_shapes:\n print('Processing image shape', shape)\n img = resize_img(img, shape)\n img = gradient_ascent(img,\n iterations=iterations,\n step=step,\n max_loss=max_loss)\n upscaled_shrunk_original_img = resize_img(shrunk_original_img, shape)\n same_size_original = resize_img(original_img, shape)\n lost_detail = same_size_original - upscaled_shrunk_original_img\n\n img += lost_detail\n shrunk_original_img = resize_img(original_img, shape)\n\n return img\n\n\nif __name__ == '__main__':\n loss = define_loss()\n grads = compute_gradients(loss)\n outputs = [loss, grads]\n fetch_loss_and_grads = K.function([DREAM], outputs)\n successive_shapes, original_img, shrunk_original_img = path_to_pyramid()\n print(x.shape for x in successive_shapes)\n dream_img = deepdream(successive_shapes, original_img, shrunk_original_img)\n save_img(dream_img, fname=IMAGE_PATH + 'dream' + '.png')\n","sub_path":"deepdream/deepdreamalgorithm.py","file_name":"deepdreamalgorithm.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"211628717","text":"import random\n\nvowels = 'a' or 'e' or 'i' or 'o' or 'u'\n\ndef num_vowels(string):\n count = 0\n for i in string:\n if i in vowels:\n count += 1\n print(count)\n\nnum_vowels(\"Sara\")\n","sub_path":"prog.py","file_name":"prog.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"475110183","text":"import time\nimport random\nimport sys\nimport os\nimport grpc\n\nimport pytest\n\n# include directory intergration/rpc for module import\nsys.path.append(\n os.path.abspath(\n os.path.join(os.path.split(__file__)[0], \"../rpc\")\n )\n)\nfrom controller.controller_client import ControllerClient # NOQA\n\n\nGRPC_CONTROLLER = \"localhost:9501\"\n\n\n@pytest.fixture\ndef grpc_client(request):\n c = ControllerClient(GRPC_CONTROLLER)\n request.addfinalizer(lambda: cleanup(c))\n return cleanup(c)\n\n\ndef cleanup(grpc_client):\n try:\n v = grpc_client.volume_get()\n except grpc.RpcError as grpc_err:\n if \"Socket closed\" not in grpc_err.details():\n raise grpc_err\n return grpc_client\n\n if v.replicaCount != 0:\n grpc_client.volume_shutdown()\n for r in grpc_client.replica_list():\n grpc_client.replica_delete(r.address)\n return grpc_client\n\n\n@pytest.fixture\ndef random_str():\n return 'random-{0}-{1}'.format(random_num(), int(time.time()))\n\n\ndef random_num():\n return random.randint(0, 1000000)\n\n\ndef test_replica_list(grpc_client):\n replicas = grpc_client.replica_list()\n assert len(replicas) == 0\n\n\ndef test_replica_create(grpc_client):\n f = 'file://' + random_str()\n replica = grpc_client.replica_create(address=f)\n assert replica.address == f\n\n grpc_client.replica_create(address=f)\n grpc_client.replica_create(address=f)\n\n rs = grpc_client.replica_list()\n assert len(rs) == 1\n assert rs[0].address == f\n assert rs[0].mode == 'WO'\n\n f2 = 'file://' + random_str()\n with pytest.raises(grpc.RpcError) as e:\n grpc_client.replica_create(address=f2)\n assert 'Can only have one WO replica at a time' in str(e.value)\n\n r = grpc_client.replica_update(rs[0].address, mode='RW')\n assert r.mode == 'RW'\n\n replica2 = grpc_client.replica_create(address=f2)\n assert replica2.address == f2\n\n rs = grpc_client.replica_list()\n assert len(rs) == 2\n\n\ndef test_replica_delete(grpc_client):\n f = 'file://' + random_str()\n r1 = grpc_client.replica_create(address=f+'1')\n grpc_client.replica_update(r1.address, mode='RW')\n r2 = grpc_client.replica_create(address=f+'2')\n grpc_client.replica_update(r2.address, mode='RW')\n r3 = grpc_client.replica_create(address=f+'3')\n grpc_client.replica_update(r3.address, mode='RW')\n\n rs = grpc_client.replica_list()\n assert len(rs) == 3\n\n grpc_client.replica_delete(r1.address)\n rs = grpc_client.replica_list()\n assert len(rs) == 2\n\n grpc_client.replica_delete(r1.address)\n rs = grpc_client.replica_list()\n assert len(rs) == 2\n\n grpc_client.replica_delete(r2.address)\n rs = grpc_client.replica_list()\n assert len(rs) == 1\n\n grpc_client.replica_delete(r3.address)\n rs = grpc_client.replica_list()\n assert len(rs) == 0\n\n\ndef test_replica_change(grpc_client):\n f = 'file://' + random_str()\n r1 = grpc_client.replica_create(address=f)\n assert r1.mode == 'WO'\n\n r1 = grpc_client.replica_update(r1.address, mode='RW')\n assert r1.mode == 'RW'\n\n r1 = grpc_client.replica_get(r1.address)\n assert r1.mode == 'RW'\n\n\ndef test_start(grpc_client):\n v = grpc_client.volume_get()\n assert v.replicaCount == 0\n\n addresses = ['file://' + random_str(), 'file://' + random_str()]\n v = grpc_client.volume_start(replicas=addresses)\n\n rs = grpc_client.replica_list()\n assert len(rs) == 2\n assert v.replicaCount == 2\n\n found_addresses = [r.address for r in rs]\n assert set(found_addresses) == set(addresses)\n\n\ndef test_shutdown(grpc_client):\n v = grpc_client.volume_get()\n assert v.replicaCount == 0\n\n addresses = ['file://' + random_str(), 'file://' + random_str()]\n v = grpc_client.volume_start(replicas=addresses)\n assert v.replicaCount == 2\n\n v = grpc_client.volume_shutdown()\n assert v.replicaCount == 0\n\n rs = grpc_client.replica_list()\n assert len(rs) == 0\n\n\ndef test_metric(grpc_client):\n replies = grpc_client.metric_get()\n\n cnt = 0\n while cnt < 5:\n try:\n metric = next(replies).metric\n assert metric.readBandwidth == 0\n assert metric.writeBandwidth == 0\n assert metric.readLatency == 0\n assert metric.writeLatency == 0\n assert metric.iOPS == 0\n cnt = cnt + 1\n except StopIteration:\n time.sleep(1)\n\n\ndef test_port_update():\n grpc_client = ControllerClient(GRPC_CONTROLLER)\n v = grpc_client.volume_get()\n assert v.replicaCount == 0\n\n addresses = ['file://' + random_str(), 'file://' + random_str()]\n v = grpc_client.volume_start(replicas=addresses)\n assert v.replicaCount == 2\n\n new_url = \"localhost:9505\"\n new_port = 9505\n grpc_client.port_update(new_port)\n\n new_grpc_client = ControllerClient(new_url)\n v = new_grpc_client .volume_get()\n assert v.replicaCount == 2\n\n cleanup(new_grpc_client)\n old_port = 9501\n new_grpc_client.port_update(old_port)\n","sub_path":"integration/core/test_controller.py","file_name":"test_controller.py","file_ext":"py","file_size_in_byte":4966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"584460409","text":"import os\nimport numpy as np\n\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import fbeta_score\n\ndef crawl_dir_rec(directory, filetype):\n \"\"\" Crawls a directory recursively to return a list of all files of a given file type \"\"\"\n files = []\n for entry in os.listdir(directory):\n entry_path = os.path.join(directory, entry)\n if os.path.isdir(entry_path):\n files += crawl_dir_rec(entry_path, filetype)\n elif os.path.isfile(entry_path):\n files.append(entry_path)\n\n files = [file for file in files if file.endswith(filetype)]\n return files\n\ndef cross_validate_svm2(features, labels):\n i = 0\n \n for feature, label in zip(features, labels):\n i += 1\n \n print('--------------------------------')\n print('Perspective', i, '\\n')\n kf = KFold(n_splits=5, shuffle=True)\n kf.get_n_splits(feature)\n scores = []\n f2_scores_0 = []\n f2_scores_1 = []\n\n for train_index, test_index in kf.split(feature):\n # print('Train ratio: ', float(len(train_index)) / len(feature))\n X_train, X_test = feature[train_index], feature[test_index]\n y_train, y_test = label[train_index], label[test_index]\n\n clf = SVC(kernel='rbf', C=1)\n clf.fit(X_train, y_train)\n score = clf.score(X_test, y_test)\n predictions = clf.predict(X_test)\n f2_score_0 = fbeta_score(y_test, predictions, beta=2, pos_label=0, average='binary')\n f2_score_1 = fbeta_score(y_test, predictions, beta=2, pos_label=1, average='binary')\n\n scores.append(score)\n f2_scores_0.append(f2_score_0)\n f2_scores_1.append(f2_score_1)\n \n print('AVG Accuracy:', np.mean(scores))\n print('AVG F2 (nao loja):', np.mean(f2_scores_0))\n print('AVG F2 (loja):', np.mean(f2_scores_1))\n print('AVG F2 (total):', 0.5 * np.mean(f2_scores_0) + 0.5 * np.mean(f2_scores_1))\n print('Confusion table:')\n print(classification_report(y_test, predictions, target_names=['nao loja', 'loja']))\n \ndef cross_validate_svm(features, labels, joint=False, cut=False):\n # each training sample will be part of a matrix (perspective x k-fold)\n X_train = [[] for i in range(len(features))]\n X_test = [[] for i in range(len(features))]\n y_train = [[] for i in range(len(features))]\n y_test = [[] for i in range(len(features))]\n \n # collect splits\n for i in range(len(features)):\n kf = KFold(n_splits=5, shuffle=True)\n kf.get_n_splits(features[i])\n for train_index, test_index in kf.split(features[i]):\n # print('Train ratio: ', float(len(train_index)) / len(feature))\n # print(len(features[i][train_index]))\n np.random.shuffle(train_index)\n \n if cut:\n cut_pos = int(len(train_index) / len(features))\n else:\n cut_pos = len(train_index)\n X_train[i].append(features[i][train_index[:cut_pos]])\n X_test[i].append(features[i][test_index])\n y_train[i].append(labels[i][train_index[:cut_pos]])\n y_test[i].append(labels[i][test_index])\n \n \n total_acc = 0\n # go through each perspective\n for i in range(len(X_train)): \n print('--------------------------------')\n print('Perspective', i, '\\n')\n \n scores = []\n f2_scores_0 = []\n f2_scores_1 = []\n \n # go through each split\n for j in range(len(X_train[0])):\n feat_test = X_test[i][j]\n label_test = y_test[i][j]\n \n # collect all perspectives of respective split\n if joint:\n feat_train = np.vstack([X_train[k][j] for k in range(len(features))])\n label_train = np.hstack([y_train[k][j] for k in range(len(features))])\n else:\n feat_train = X_train[i][j]\n label_train = y_train[i][j]\n \n clf = SVC(kernel='rbf', C=1)\n clf.fit(feat_train, label_train)\n\n score = clf.score(feat_test, label_test)\n predictions = clf.predict(feat_test)\n f2_score_0 = fbeta_score(label_test, predictions, beta=2, pos_label=0, average='binary')\n f2_score_1 = fbeta_score(label_test, predictions, beta=2, pos_label=1, average='binary')\n\n scores.append(score)\n f2_scores_0.append(f2_score_0)\n f2_scores_1.append(f2_score_1)\n \n acc = np.mean(scores)\n total_acc += acc * 1.0 / len(X_train)\n print('AVG Accuracy:', acc)\n print('AVG F2 (nao loja):', np.mean(f2_scores_0))\n print('AVG F2 (loja):', np.mean(f2_scores_1))\n print('AVG F2 (total):', 0.5 * np.mean(f2_scores_0) + 0.5 * np.mean(f2_scores_1))\n print('Confusion table:')\n print(classification_report(label_test, predictions, target_names=['nao loja', 'loja']))\n print('Total accuaracy:', total_acc)","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"42877426","text":"# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\nimport boto3\nimport pytest\nfrom assertpy import assert_that\nfrom botocore.exceptions import ClientError\n\n\n@pytest.mark.dimensions(\"us-east-2\", \"c5.xlarge\", \"centos7\", \"slurm\")\n@pytest.mark.usefixtures(\"instance\", \"os\", \"scheduler\")\n@pytest.mark.parametrize(\"dashboard_enabled, cw_log_enabled\", [(True, True), (True, False), (False, False)])\ndef test_dashboard(\n dashboard_enabled,\n cw_log_enabled,\n region,\n pcluster_config_reader,\n clusters_factory,\n test_datadir,\n):\n cluster_config = pcluster_config_reader(\n dashboard_enabled=str(dashboard_enabled).lower(),\n cw_log_enabled=str(cw_log_enabled).lower(),\n )\n cluster = clusters_factory(cluster_config)\n cw_client = boto3.client(\"cloudwatch\", region_name=region)\n dashboard_name = \"{0}-{1}\".format(cluster.cfn_name, region)\n\n if dashboard_enabled:\n response = cw_client.get_dashboard(DashboardName=dashboard_name)\n assert_that(response[\"DashboardName\"]).is_equal_to(dashboard_name)\n if cw_log_enabled:\n assert_that(response[\"DashboardBody\"]).contains(\"Head Node Logs\")\n else:\n assert_that(response[\"DashboardBody\"]).does_not_contain(\"Head Node Logs\")\n else:\n try:\n cw_client.get_dashboard(DashboardName=dashboard_name)\n except ClientError as e:\n assert_that(e.response[\"Error\"][\"Code\"]).is_equal_to(\"ResourceNotFound\")\n","sub_path":"tests/integration-tests/tests/dashboard/test_dashboard.py","file_name":"test_dashboard.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"133563739","text":"import os, openpyxl, csv\n\nos.chdir('/home/samabaly/Bureau/Fichiers/Etats')\n\nfor file in os.listdir():\n\tif file.endswith(\".xlsx\"):\n\t\tfilename = os.path.join(file)\n\t\tcsv_file, ext = os.path.splitext(file)\n\t\txlsfile = openpyxl.load_workbook(filename)\n\t\ttitle = xlsfile.sheetnames\n\t\tsheet = xlsfile[title[0]]\n\n\t\tcolumns = [2, 4, 5, 6, 7, 15]\n\n\t\tHEADER = (\"Montant\", \"No\", \"Annee\", \"Prenom\", \"Nom\", \"No_dossier\")\n\t\tcsv_filename = csv_file+'.csv'\n\t\twith open(csv_filename, \"w\", newline=\"\") as csvfile:\n\t\t\tetat = csv.writer(csvfile)\n\t\t\tetat.writerow(HEADER)\n\t\t\trows = iter(sheet.rows)\n\t\t\tnext(rows)\n\t\t\tnext(rows)\n\n\t\t\twhile True:\n\t\t\t\ttry:\n\t\t\t\t\trow = next(rows)\t\t\t\t\n\t\t\t\t\tDATA = [row[i].value for i in columns]\n\t\t\t\t\t# print(DATA)\n\t\t\t\t\t# os.chdir('/home/samabaly/Bureau/Fichiers/Etats/Csv')\n\t\t\t\t\tetat.writerow(DATA)\n\t\t\t\texcept StopIteration:\n\t\t\t\t\tbreak","sub_path":"Fichiers/files01.py","file_name":"files01.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"73152624","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nimport torchvision.models as models\nfrom torchsummary import summary\n\nimport data_utils\n\n# torch.set_grad_enabled(False)\n\nclass ResBlock(nn.Module):\n def __init__(self, inplanes, planes, downsample=False):\n super(ResBlock, self).__init__()\n self.downsample = downsample\n self.conv0 = nn.Conv2d(inplanes, planes, 3, padding=1, stride=(2 if downsample else 1))\n self.conv1 = nn.Conv2d(planes, planes, 3, padding=1)\n self.bn = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=False)\n self.conv_shortcut = nn.Conv2d(inplanes, planes, 3, padding=1, stride=(2 if downsample else 1))\n \n def forward(self, x):\n y = self.conv0(x)\n y = self.bn(y)\n y = self.relu(y)\n \n y = self.conv1(y)\n y = self.bn(y)\n\n shortcut = self.conv_shortcut(x)\n\n y += shortcut\n y = self.relu(y)\n\n return y\n\n\nclass Model(nn.Module):\n def __init__(self, char_count=4803, in_channels=1, out_channels=1, tiny=False):\n super(Model, self).__init__()\n\n self.tiny = tiny\n self.res0 = ResBlock(1, 32, downsample=True)\n \n if self.tiny:\n self.conv = nn.Conv2d(32, char_count, 3, padding=1, stride=1)\n else:\n self.res1 = ResBlock(32, 32*4)\n self.res2 = ResBlock(32*4, 32*16)\n\n self.res3 = ResBlock(32*16, 32*32, downsample=True)\n self.res4 = ResBlock(32*32, 32*64)\n self.conv = nn.Conv2d(32*64, char_count, 3, padding=1, stride=1)\n\n self.relu = nn.ReLU(inplace=False)\n self.global_avgpool = nn.AdaptiveAvgPool2d([1, 3])\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, x):\n y = self.res0(x)\n \n if not self.tiny:\n y = self.res1(y)\n y = self.res2(y)\n y = self.res3(y)\n y = self.res4(y)\n\n y = self.conv(y)\n y = self.relu(y)\n y = self.global_avgpool(y)\n y = self.softmax(y)\n return y\n\nif __name__ == '__main__':\n model = Model(char_count=data_utils.char_count)\n x = torch.from_numpy(np.random.normal(size=[1, 1, 50, 150]).astype(np.float32))\n y = model(x)\n output = torch.squeeze(torch.argmax(y, dim=1))\n print(x.size(), y.size(), output)\n\n # print(model)\n print(f'total parameters: {sum(p.numel() for p in model.parameters())}')\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n summary(model.to(device), (1, 50, 150))\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"600026634","text":"from util import loader\nfrom wrappers.update import Update\nfrom games.base_class import Game\n\n\nclass RainbowSix(Game):\n\tdef __init__(self):\n\t\tsuper().__init__('Rainbow Six Siege', homepage='https://rainbow6.ubisoft.com/siege/en-us/')\n\n\tdef scan(self):\n\t\tdata = loader.json(\"https://prod-tridionservice.ubisoft.com/live/v1/News/Latest?pageSize=6&pageIndex=0\"\n\t\t\t\t\t\t\t\"&language=en-US&templateId=tcm%3A152-76778-32&detailPageId=tcm%3A150-194572-64\"\n\t\t\t\t\t\t\t\"&keywordList=233416&useSeoFriendlyUrl=true\")['items'] # Returns XML\n\t\tfor p in data:\n\t\t\tsoup = loader.direct_soup(p['Content'])\n\t\t\t_img = soup.find('img')['src']\n\t\t\t_title = soup.find('h3').text\n\t\t\t_desc = soup.find('strong').text\n\t\t\t_url = 'https://rainbow6.ubisoft.com/' + soup.find('a')['href']\n\t\t\tyield Update(game=self, update_name=_title, post_url=_url, desc=_desc, color='#333740', image=_img)\n\n\nif __name__ == \"__main__\":\n\tlol = RainbowSix()\n\tfor u in lol.scan():\n\t\tprint(u)\n","sub_path":"patchalerts/games/rainbowsix.py","file_name":"rainbowsix.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"516558950","text":"import sys\nsys.path.append('/home/ross/CytoPy')\n\nfrom CytoPy.data.mongo_setup import global_init\nfrom CytoPy.flow.clustering import main\nfrom sklearn.cluster import AgglomerativeClustering, KMeans\nimport unittest\n\nglobal_init('test')\n\n\nclass TestFilterDict(unittest.TestCase):\n def test(self):\n test_dict = {'x': [1, 2, 3],\n 'y': [4, 5, 6]}\n self.assertListEqual(list(main.filter_dict(test_dict, ['y']).keys()),\n ['y'])\n\n\nclass TestFetchClusteringClass(unittest.TestCase):\n\n def test1(self):\n params = dict(cluster_class='kmeans',\n x='x')\n cluster, params = main._fetch_clustering_class(params)\n self.assertEqual(type(cluster), KMeans)\n\n def test2(self):\n params = dict(cluster_class='agglomerative',\n x='x')\n cluster, params = main._fetch_clustering_class(params)\n self.assertEqual(type(cluster), AgglomerativeClustering)\n self.assertListEqual(list(params.keys()), ['x'])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"CytoPy/tests/test_clustering/test_utilities.py","file_name":"test_utilities.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"299639327","text":"# the has/skip patterns closely follow the examples set by\n# the xray/xarray project\n\nimport sys\nimport platform\nimport pandas as pd\n\n\ntry:\n import unittest2 as unittest\nexcept ImportError:\n import unittest\n\n\ntry:\n import scipy\n has_scipy = True\nexcept ImportError:\n has_scipy = False\n\n\ndef requires_scipy(test):\n return test if has_scipy else unittest.skip('requires scipy')(test)\n\n\ntry:\n import ephem\n has_ephem = True\nexcept ImportError:\n has_ephem = False\n\n\ndef requires_ephem(test):\n return test if has_ephem else unittest.skip('requires ephem')(test)\n\n\ndef incompatible_conda_linux_py3(test):\n \"\"\"\n Test won't work in Python 3.x due to Anaconda issue.\n \"\"\"\n major = sys.version_info[0]\n minor = sys.version_info[1]\n system = platform.system()\n\n if major == 3 and system == 'Linux':\n out = unittest.skip('error on Linux Python 3 due to Anaconda')(test)\n else:\n out = test\n\n return out\n\n\ndef incompatible_pandas_0180(test):\n \"\"\"\n Test won't work on pandas 0.18.0 due to pandas/numpy issue with\n np.round.\n \"\"\"\n\n if pd.__version__ == '0.18.0':\n out = unittest.skip(\n 'error on pandas 0.18.0 due to pandas/numpy round')(test)\n else:\n out = test\n\n return out\n\n\ndef incompatible_pandas_0131(test):\n \"\"\"\n Test won't work on pandas 0.18.0 due to pandas/numpy issue with\n np.round.\n \"\"\"\n\n if pd.__version__ == '0.13.1':\n out = unittest.skip(\n 'error on pandas 0.13.1 due to pandas/numpy')(test)\n else:\n out = test\n\n return out\n","sub_path":"pvlib/test/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"396422185","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\nimport sys\nimport os.path\n\nif len(sys.argv) < 2:\n print(\"provide filename\")\n exit()\n\nif not os.path.isfile(sys.argv[1]):\n print(f\"Cannot find file {sys.argv[1]}\")\n exit()\n\npfn = os.path.splitext(sys.argv[1])[0] + \".png\"\n\nprint(pfn)\n\nmylist = []\nwith open(sys.argv[1],\"rb\") as f:\n mylist = pickle.load(f)\n\ndef myp(mylist):\n x = []\n y = []\n\n ax = plt.gca()\n\n esize = np.array(mylist)\n esize = int(np.amax(esize[:,0]))\n bsize = np.array(mylist)\n bsize = int(np.amax(bsize[:,1]))\n \n xtl = np.arange(1,esize+1,1)\n xt = (xtl-1) * (bsize)\n \n i = 0\n for e,b,l in mylist:\n \n \n x.append(i)\n i += 1\n y.append(l)\n print(f\"e = {e}, b = {b}, l = {l}\")\n \n plt.plot(x,y,ls='solid')\n ax.set_xticks(xt)\n ax.set_xticklabels(xtl)\n\n for tick in ax.xaxis.get_major_ticks():\n tick.label.set_fontsize('x-small') \n for tick in ax.yaxis.get_major_ticks():\n tick.label.set_fontsize('x-small') \n\n\n ax.set_xlabel('epoch')\n ax.set_ylabel('loss')\n plt.savefig(pfn)\n\n\nmyp(mylist)\n\n","sub_path":"plot_loss.py","file_name":"plot_loss.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"260812856","text":"#!/usr/bin/env python\r\n# coding: utf-8\r\nfrom __future__ import unicode_literals, division\r\n\r\nimport math\r\nimport time\r\nimport sys\r\nimport socket\r\nimport signal\r\nimport redis\r\n\r\nFLAG = True\r\n\r\nhosts = \"127.0.0.1\"\r\nport = 6379\r\nlog_path_tail = \"/tmp/ansible_long.log\"\r\n\r\n\r\ndef get_last_lines(f, num=10):\r\n \"\"\"读取文件的最后几行\r\n \"\"\"\r\n size = 1000\r\n try:\r\n f.seek(-size, 2)\r\n except IOError: # 文件内容不足size\r\n f.seek(0)\r\n return f.readlines()[-num:]\r\n\r\n data = f.read()\r\n lines = data.splitlines()\r\n n = len(lines)\r\n while n < num:\r\n size *= int(math.ceil(num / n))\r\n try:\r\n f.seek(-size, 2)\r\n except IOError:\r\n f.seek(0)\r\n return f.readlines()[-num:]\r\n data = f.read()\r\n lines = data.splitlines()\r\n n = len(lines)\r\n\r\n return lines[-num:]\r\n\r\n\r\ndef process_line(r, channel, line):\r\n r.publish(channel, line.strip())\r\n\r\n\r\ndef sig_handler(signum, frame):\r\n global FLAG\r\n FLAG = False\r\n\r\n\r\n# 收到退出信号后,以比较优雅的方式终止脚本\r\nsignal.signal(signal.SIGTERM, sig_handler)\r\n# 为了避免日志输出过多,浏览器承受不住,设置5分钟后脚本自动停止\r\nsignal.signal(signal.SIGALRM, sig_handler)\r\nsignal.alarm(300)\r\n\r\n\r\ndef get_hostname():\r\n return socket.gethostname()\r\n\r\n\r\ndef force_str(s):\r\n if isinstance(s, unicode):\r\n s = s.encode(\"utf-8\")\r\n return s\r\n\r\n\r\ndef tail():\r\n r = redis.StrictRedis(host=hosts, port=port, db=5)\r\n log_path = log_path_tail \r\n line_count = 100\r\n # 往redis频道发送实时日志\r\n channel = \"logs:{hostname}:{log_path}\".format(hostname=hosts, log_path=log_path)\r\n\r\n with open(log_path, 'r') as f:\r\n last_lines = get_last_lines(f, line_count)\r\n for line in last_lines:\r\n process_line(r, channel, force_str(line))\r\n try:\r\n while FLAG: # 通过信号控制这个变量,实现优雅退出循环\r\n line = f.readline()\r\n if not line:\r\n time.sleep(0.05)\r\n continue\r\n process_line(r, channel, line)\r\n except KeyboardInterrupt:\r\n pass\r\n print(\"Exiting...\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n tail()\r\n","sub_path":"logtail.py","file_name":"logtail.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"623772494","text":"A_Z = ['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\na_z = ['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\ndef alphabet_position( char):\n ''' This function checks the position in which the letter belongs. '''\n for position in range(27):\n if char.isalpha():\n if char == A_Z[position] or char == a_z[position]:\n return position\n\ndef rotate_character( char, rot):\n ''' This function shifts the position on the letter base on the char variable and shifts it by the rot variable ''' \n if char.isalpha():\n\n current = alphabet_position(char) \n shift = rot % 26\n new_char_position = current + shift\n if new_char_position > 26:\n new_char_position = new_char_position - 26\n new_character = ''\n\n if char in A_Z:\n new_character = A_Z[new_char_position-26]\n\n if char in a_z:\n new_character = a_z[new_char_position-26]\n \n return new_character\n else:\n return char\n\n\ndef encrypt(text, rot):\n encrypt_text = ''\n\n for char in text:\n new_char = ''\n new_char = rotate_character(char, rot)\n encrypt_text += new_char\n\n return encrypt_text\n\n# print(encrypt('hello', 5))","sub_path":"caesar.py","file_name":"caesar.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"234649917","text":"def normalise_extreme_values(y, likelihood):\n from numpy import isfinite, all\n\n if not all(isfinite(y)):\n msg = \"There are non-finite values in the the provided phenotype.\"\n raise ValueError(msg)\n\n if likelihood == \"poisson\":\n _poisson_normalise_extreme_values(y)\n elif likelihood == \"binomial\":\n _binomial_normalise_extreme_values(y)\n\n return y\n\n\ndef _poisson_normalise_extreme_values(y):\n import warnings\n from numpy import clip\n\n max_val = 25000.0\n if y.values.max() > max_val:\n msg = \"Outcome values of Poisson likelihood greater\"\n msg += \" than {} is set to {} before applying GLMM.\"\n msg = msg.format(max_val, max_val)\n warnings.warn(msg)\n y.values[:] = clip(y.values, 0.0, max_val)\n\n\ndef _binomial_normalise_extreme_values(y):\n import warnings\n from numpy import minimum\n from numpy_sugar import is_all_equal\n\n max_val = 300\n v = y.values\n if v[:, 1].min() >= max_val:\n msg = \"Number of trials of Binomial likelihood greater\"\n msg += \" than {} is set to {}, and the number of successes adjusted \"\n msg += \"accordingly, before applying GLMM.\"\n msg = msg.format(max_val, max_val)\n warnings.warn(msg)\n ratio = v[:, 0] / v[:, 1]\n v[:, 1] = minimum(v[:, 1], max_val)\n v[:, 0] = ratio * v[:, 1]\n v[:, 0] = v[:, 0].round()\n\n if is_all_equal(v[:, 0]):\n msg = \"Sorry, all number of successes are equal after\"\n msg += \" we've tried to fix the high number of trials.\"\n raise ValueError(msg)\n y.values[:] = v\n","sub_path":"limix/qc/_lik.py","file_name":"_lik.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"589693720","text":"import functions\nfrom bs4 import BeautifulSoup\nfrom pandas import DataFrame\n\n# Insertamos la url\n# N5: 33 páginas\n# N4: 29 páginas\n# N3: 89 páginas\n# N2: 91 páginas\n# N1: 173 páginas\n# Parámetros\nlevel = 1\nn_pages = 173\n\n\nfinal_result = []\nindex = 1\nfor i in range(n_pages):\n url = 'https://jisho.org/search/%23words%23jlpt-n' + str(level) + '?page=' + str(i+1)\n\n html = functions.obtain_html(url)\n bs = BeautifulSoup(html, 'lxml')\n\n # Obtenemos todas las palabras\n words = bs.findAll('div', {'class':'concept_light clearfix'})\n\n # Obtenemos la lista de términos\n print('Obteniendo página {} de {}'.format(i+1, n_pages))\n page = functions.obtain_page(words, level, index)\n index = index + len(words)\n\n # Lo añadimos a la lista final\n final_result = final_result + page\n\nprint(final_result)\nprint(len(final_result))\n\ndocument = DataFrame.from_records(final_result)\ndocument.to_csv('csv/N' + str(level) + '.txt', index=False, sep='\\t')","sub_path":"root.py","file_name":"root.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"303878190","text":"import json\n\ndef create_nd(d,strx,nd): #rec funz create\n #for x in strx:\n #print(' '*len(strx),x)\n for child in strx:\n val=d.get(child,False)\n if val!=False:\n\n nd[child]=val\n strx=list()\n for child1 in val:\n #print(child1)\n strx.append(child1)\n\n #print(strx)\n #print('nd=',nd,'\\n')\n create_nd(d,strx,nd)\n else: d={}\n return nd\n\ndef genera_sottoalbero(fnome,x,fout):\n f=open(fnome,'U')\n t=f.read()\n f.close()\n diz_a=json.loads(t)\n nd=dict()\n strx=[x]\n nd=create_nd(diz_a,strx,nd)\n #print('Scrivo diz-alb\\n',nd)\n f=open(fout,'w')\n f.write(json.dumps(nd))\n f.close()\n\n\n\ndef delete_d(d,strx): #rec func delete\n #print(strx)\n for child in strx: #itero su strx\n val=d.get(child,False)#restituisce il valore della chiave altrimenti se non presente False\n if val!=False:\n del d[child] #eliminiamo la chiave child\n strx=list()\n for child1 in val:\n #print(child1)\n strx.append(child1)\n #print(strx)\n #print('d=',d,'\\n')\n delete_d(d,strx)\n else: d={}\n return d\n\ndef cancella_sottoalbero(fnome,x,fout):\n f=open(fnome,'U')\n t=f.read()\n f.close()\n diz_a=json.loads(t)\n strx=[x]\n d=delete_d(diz_a,strx)\n for k in d:\n if x in d.get(k):\n d.get(k).remove(x)\n #print('yes')\n #print(d)\n f=open(fout,'w')\n f.write(json.dumps(d))\n f.close()\n\n\n\ndef lev(d,c,nd,l):\n #print('entro con lista-> ',l)\n #print('ln',l)\n if d!={}:\n #print(l)\n for k in l:\n\n if nd.get(c,False)!=False: #se ci sono elementi ass a chiave c\n #---print('\\ngia presente-> ',nd.get(c))\n app=nd.get(c) #crea lista di elementi\n if type(app)==str:\n\n #---print('app',type(app),app)\n list_app=[app]\n #---print('provalista app->',list_app)\n\n list_app.append(k) #agg alla lista l elemento k\n #---print('list_app',list_app)\n return\n #return\n #print('sortata',app,'->',app.sort(),type(app))\n #print('metto',c,'ass',app,type(app))\n #print('sortata',app,'->',sorted(app),type(app))\n nd[c]=sorted(list_app)\n else:\n #---print('else')\n app=nd.get(c)\n app.append(k)\n nd[c]=sorted(app)\n\n #print('sortata',sorted(app))\n #return\n l=d.get(k) #l diventa una lista di valori di k\n #print('listarenew',l)\n #return\n\n else: #se non ci sono elementi ass a chiave c\n #print('2metto',c,'ass',k,'\\n')\n #---print('metto',c,'ass',k)\n nd[c]=[k] #ass (k->list) alla chiave c\n #---print(nd)\n #print('quauqa',k)\n #--print(type(nd),nd)\n #--print('qua k',k)\n l=list()\n l=d.get(k) #l diventa una lista di valori di k\n #print('lista nuova',l)\n #print('cancello',k)\n #--print('elimino',k)\n del d[k] #eliminiamo la chiave k dal dizionario\n #return\n #print('nuovo',d)\n #lev(d,c+1,nd,l)\n lev(d,c+1,nd,l)\n return nd\n else:\n return nd\n\n\ndef dizionario_livelli(fnome,fout):\n f=open(fnome,'U')\n t=f.read()\n f.close()\n d=json.loads(t)\n #next(iter(d)))\n nd=dict()\n #lista_k=list()\n #lista_k=list(d.keys())\n #l=[next(iter(d))]\n #print(l)\n insk=set()\n insv=set()\n for k,v in d.items():\n insk.add(k)\n for elemento in v:\n insv.add(elemento)\n rad=insk-insv\n #print(rad)\n #a=rad[0]\n #print('radstr',a)\n\n\n\n\n\n\n nd=lev(d,0,nd,rad)\n #---print(nd)\n f=open(fout,'w')\n f.write(json.dumps(nd))\n f.close()\n\ndef calc_g_ant(d,nd,c,gr,l):\n for k in l:\n nd[k]=gr\n if d.get(k,False)!=False:\n l=d.get(k)\n if len(d.get(k))==c:\n calc_g_ant(d,nd,c,gr+1,l)\n else:\n calc_g_ant(d,nd,c,gr,l)\n return nd\n\n\n\n\n\n\n\n\ndef dizionario_gradi_antenati(fnome,y,fout):\n f=open(fnome,'U')\n t=f.read()\n f.close()\n d=json.loads(t)\n nd=dict()\n #l=[next(iter(d))]\n insk=set()\n insv=set()\n for k,v in d.items():\n insk.add(k)\n for elemento in v:\n insv.add(elemento)\n rad=insk-insv\n #print(rad)\n nd=calc_g_ant(d,nd,y,0,rad)\n #print('diz->',nd)\n f=open(fout,'w')\n f.write(json.dumps(nd))\n f.close()\n\n\n#genera_sottoalbero('Alb100.json','ultras','prova.json')\n#cancella_sottoalbero('Alb10.json','d','prova.json')\ndizionario_livelli('Alb10.json','prova.json')\n\n#dizionario_livelli('Alb100.json','prova.json')\n#dizionario_gradi_antenati('Alb100.json',2,'prova.json')\n#dizionario_gradi_antenati('Alb100.json',2,'prova.json')\n","sub_path":"students/1755633/homework04/program01.py","file_name":"program01.py","file_ext":"py","file_size_in_byte":5245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"420389579","text":"#!/usr/bin/python\n## Convert MicroPasts photo-mask polygons to binary image masks (for 3D models)\n## Andy Bevan 15-Jun-2014\n__author__ = 'ahb108'\n## Currently for Python 2.7.5 (tested on MacOSX 10.9.2) launched in a virtual environment:\n\n# Libraries\nfrom PIL import Image # Pillow/PIL needs libjpeg support\nfrom PIL import ImageDraw\nimport urllib2\nimport json\nimport re\nimport numpy as np\nimport argparse\nimport os\n\n# Argument parser\nparser = argparse.ArgumentParser(description='This is a script to combine vector polygon masks into a binary raster mask for 3d modelling.')\nparser.add_argument('-a','--app',help='MicroPasts application', required=True)\nparser.add_argument('-t','--thr',help='Masking threshold', required=True)\nparser.add_argument('-o','--obj',help='Object to be masked', required=True)\nparser.add_argument('-w','--wd', help='Working directory',required=True)\nargs = parser.parse_args()\n\n# # Global settings ##\nos.chdir(args.wd)\nmaskthresh = float(args.thr)\napp = args.app\nobjbucket = args.obj\npybinst = 'http://crowdsourced.micropasts.org'\n\n###################################\n\n# Get the raw jpg files from download directory\next = ['.JPG', '.jpg', '.jpeg', '.JPEG']\nfiles = [ f for f in os.listdir('.') if f.endswith(tuple(ext)) ]\n\nprint(\"Masking each individual photograph...\")\nfor q in range(0, len(files)):\n# Open an example image\n img = Image.open(files[q])\n imnameonly = os.path.splitext(files[q])[0]\n# Get JSON data for tasks and find task ID for this file\n lkup = objbucket + '/' + files[q]\n url = str(pybinst) + '/app/' + str(app) + '/tasks/export?type=task&format=json'\n jurl = urllib2.urlopen(url)\n jtasks = json.loads(jurl.read())\n\n# Loop through looking for those tasks with the necessary\n# look-up image (almost always one unless tasks have been duplicated,\n# but allowing more than one just in case)\n imtasks = []\n for elm in range(0, len(jtasks)):\n onetask = jtasks[elm]\n onetaskurl = onetask['info']['url_b'].encode('utf-8')\n if re.search(lkup, onetaskurl): imtasks.extend([onetask['id']])\n \n# Get JSON data for task runs (even if they are duplicated)\n jtaskruns = []\n for a in range(0, len(imtasks)):\n url = str(pybinst) + '/app/' + str(app) + '/' + str(imtasks[a]) + '/results.json'\n jurl = urllib2.urlopen(url)\n jtaskruns.extend(json.loads(jurl.read()))\n\n# Loop through and extract outlines\n polys = []\n for a in range(0, len(jtaskruns)):\n jtaskrun = jtaskruns[a] # one contributor\n# Extract the outline and convert to tuples\n o0 = jtaskrun['info']['outline'][0][0]\n p = [] # Empty list for outline vertices\n h = img.size[1] # Get image height\n for x in range(0, len(o0)):\n xy = o0[x]\n xy[1] = h - xy[1] # reverse y-coordinates\n p.append(tuple(xy))\n polys.append(p)\n\n# Add these polygons incrementally to a mask\n mask = Image.new(\"L\", img.size, color=0)\n mask = np.asarray(mask)\n for x in polys:\n imtmp = Image.new(\"L\", img.size, color=0)\n draw = ImageDraw.Draw(imtmp)\n draw.polygon(x, fill=255 / float(len(polys)))\n imtmp = np.asarray(imtmp)\n mask = mask + imtmp\n\n# Look for holes and convert to polygons if present\n hpolys = [] # Empty list for hole polygons\n for a in range(0, len(jtaskruns)):\n jtaskrun = jtaskruns[a] # one contributor\n hls = jtaskrun['info']['holes'] # check for presence of holes data\n if hls:\n# Extract the outline and convert to tuples\n h0 = jtaskrun['info']['holes'][0][0]\n ph = [] # Empty list for outline vertices\n h = img.size[1] # Get image height\n for x in range(0, len(h0)):\n xy = h0[x]\n xy[1] = h - xy[1] # reverse y-coordinates\n ph.append(tuple(xy))\n hpolys.append(ph)\n\n# Create a reverse mask for these polygon holes if necessary and subtract\n if hpolys:\n hmask = Image.new(\"L\", img.size, color=0)\n hmask = np.asarray(hmask)\n for y in hpolys:\n imtmp = Image.new(\"L\", img.size, color=0)\n draw = ImageDraw.Draw(imtmp)\n draw.polygon(y, fill=255 / float(len(polys)))\n imtmp = np.asarray(imtmp)\n hmask = hmask + imtmp\n\n# Combine if necessary\n if len(hpolys) > 1:\n hmask = hmask * -1\n mask = mask + hmask\n mask[mask < 0] = 0\n mask = Image.fromarray(mask)\n mask = mask.convert(mode=\"L\")\n else:\n mask = Image.fromarray(mask)\n \n# Convert to binary mask based on threshold (see global settings)\n maskbin = Image.eval(mask, lambda px: 0 if px <= 255 * maskthresh else 255)\n \n# Save image mask (no EXIF but does not matter for mask)\n fn = imnameonly + '_mask.JPG'\n maskbin.save(fn)\n\nprint(\"Done.\")\n","sub_path":"photoMasking/photoMasking.py","file_name":"photoMasking.py","file_ext":"py","file_size_in_byte":4843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"90161003","text":"from django.shortcuts import render\nfrom . import draw\nfrom health.models import HealthCheck\n\n# Create your views here.\ndef input(request):\n return render(request, \"health_input.html\")\n\ndef output(request):\n \n date = request.GET['date']\n leukocyte = request.GET['leukocyte']\n platelet = request.GET['platelet']\n neutrophil = request.GET['neutrophil']\n CA199 = request.GET['CA199']\n CA125 = request.GET['CA125']\n CEA = request.GET['CEA']\n\n if date == '':\n draw.draw()\n return render(request, \"health_output.html\")\n\n if leukocyte == '':\n \tleukocyte = '-1'\n\n if platelet == '':\n \tplatelet = '-1'\n\n if neutrophil == '':\n \tneutrophil = '-1'\n\n if CA199 == '':\n \tCA199 = '-1'\n\n if CA125 == '':\n \tCA125 = '-1'\n\n if CEA == '':\n \tCEA = '-1'\n\n HealthData = HealthCheck(date = date,leukocyte = leukocyte,\n platelet = platelet,neutrophil = neutrophil,\n CA199 = CA199,CA125 = CA125,CEA=CEA)\n HealthData.save()\n\n draw.draw()\n\n return render(request, \"health_output.html\")","sub_path":"Invisible_hand/Invisible_Hand/health/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"539579878","text":"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py,md\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.4'\n# jupytext_version: 1.2.4\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# # Shark Tank\n#\n# _Shark Tank_ is a reality TV show. Contestants present their idea for a company to a panel of investors (a.k.a. \"sharks\"), who then decide whether or not to invest in that company. The investors give a certain amount of money in exchange for a percentage stake in the company (\"equity\"). If you are not familiar with the show, you may want to watch part of an episode [here](http://abc.go.com/shows/shark-tank) to get a sense of how it works.\n#\n# The data that you will examine in this lab contains data about all contestants from the first 6 seasons of the show, including:\n# - the name and industry of the proposed company\n# - whether or not it was funded (i.e., the \"Deal\" column)\n# - which sharks chose to invest in the venture (N.B. There are 7 regular sharks, not including \"Guest\". Each shark has a column in the data set, labeled by their last name.)\n# - if funded, the amount of money the sharks put in and the percentage equity they got in return\n#\n# To earn full credit on this lab, you should:\n# - use built-in `pandas` methods (like `.sum()` and `.max()`) instead of writing a for loop over a `DataFrame` or `Series`\n# - use the split-apply-combine pattern wherever possible\n#\n# Of course, if you can't think of a vectorized solution, a `for` loop is still better than no solution at all!\n\nimport pandas as pd\n\n# ## Question 0. Getting and Cleaning the Data\n\n# The data is stored in the CSV file `https://raw.githubusercontent.com/dlsun/data-science-book/master/data/sharktank.csv`. Read in the data into a Pandas `DataFrame`.\n\n## YOUR CODE HERE\n### BEGIN SOLUTION\nimport pandas as pd\ndf = pd.read_csv(\"https://raw.githubusercontent.com/dlsun/data-science-book/master/data/sharktank.csv\")\ndf.head()\n### END SOLUTION\n\n# There is one column for each of the sharks. A 1 indicates that they chose to invest in that company, while a missing value indicates that they did not choose to invest in that company. Notice that these missing values show up as NaNs when we read in the data. Fill in these missing values with zeros. Other columns may also contain NaNs; be careful not to fill those columns with zeros, or you may end up with strange results down the line.\n\n## YOUR CODE HERE\n### BEGIN SOLUTION\ndf.loc[:,[\"Corcoran\",\"Cuban\",\"Greiner\",\"Herjavec\",\"John\",\"O'Leary\",\"Harrington\",\"Guest\"]]=df.loc[:,[\"Corcoran\",\"Cuban\",\"Greiner\",\"Herjavec\",\"John\",\"O'Leary\",\"Harrington\",\"Guest\"]].fillna(0)\ndf.head()\n### END SOLUTION\n\n# Notice that Amount and Equity are currently being treated as categorical variables (`dtype: object`). Can you figure out why this is? Clean up these columns and cast them to numeric types (i.e., a `dtype` of `int` or `float`) because we'll need to perform mathematical operations on these columns.\n\n## YOUR CODE HERE\n### BEGIN SOLUTION\ndf[\"Amount\"] = df[\"Amount\"].fillna(\"$0\").str[1:].str.replace(\",\",\"\").astype(int)\ndf[\"Equity\"] = df[\"Equity\"].fillna(\"0%\").str[:-1].astype(float)\ndf.head()\n### END SOLUTION\n\n# ## Question 1. Which Company was Worth the Most?\n\n# The valuation of a company is how much it is worth. If someone invests \\\\$10,000 for a 40\\% equity stake in the company, then this means the company must be valued at \\$25,000, since 40% of \\\\$25,000 is \\\\$10,000.\n#\n# Calculate the valuation of each company that was funded. Which company was most valuable? Is it the same as the company that received the largest total investment from the sharks?\n\n## YOUR CODE HERE\n### BEGIN SOLUTION\ndf[\"Valuation\"]=df[\"Amount\"]/(df[\"Equity\"]/100)\ndisplay(df.head())\ndisplay(df.set_index(\"Company\")[\"Valuation\"].idxmax())\ndisplay(df.set_index(\"Company\")[\"Amount\"].idxmax())\n### END SOLUTION\n\n# **ENTER YOUR WRITTEN EXPLANATION HERE.**\n# ### BEGIN SOLUTION\n# No. As you can see above, they are different.\n# ### END SOLUTION\n\n# ## Question 2. Which Shark Invested the Most?\n\n# Calculate the total amount of money that each shark invested over the 6 seasons. Which shark invested the most total money over the 6 seasons? Avoid loops.\n#\n# _Hint:_ If $n$ sharks funded a given venture, then the amount that each shark invested is the total amount divided by $n$.\n\nmyfunc = lambda: 1\nmyfunc()\n\n# !pwd\n\n## YOUR CODE HERE\n### BEGIN SOLUTION\ndf2 = df.copy()\nnames = [\"Corcoran\",\"Cuban\",\"Greiner\",\"Herjavec\",\"John\",\"O'Leary\",\"Harrington\",\"Guest\"]\ndf2.loc[:,names] = df.loc[:,[\"Company\"]+names].groupby(\"Company\").apply(lambda x: x/sum(x.iloc[0,:])).fillna(0)\ndf2.loc[:,[\"Company\",\"Amount\"]+names].groupby(\"Company\").apply(lambda x: x.iloc[0,0]*x.iloc[0,1:]).sum().sort_values()\n### END SOLUTION\n\n# **ENTER YOUR WRITTEN EXPLANATION HERE.**\n# ### BEGIN SOLUTION\n# Cuban\n# ### END SOLUTION\n\n# ## Question 3. Do the Sharks Prefer Certain Industries?\n#\n# Calculate the funding rate (the proportion of companies that were funded) for each industry. Make a visualization showing this information.\n\n## YOUR CODE HERE\n### BEGIN SOLUTION\n# %matplotlib inline\ndf.loc[:,[\"Industry\",\"Amount\"]].groupby(\"Industry\").apply(lambda x: (sum(x.values > 0)/x.shape[0])[0]).sort_values().plot.bar()\n### END SOLUTION\n\n# **ENTER YOUR WRITTEN EXPLANATION HERE.**\n# ### BEGIN SOLUTION\n# Yes. Fitness and sports\n# ### END SOLUTION\n","sub_path":"labs/Shark Tank/2A. Shark Tank.py","file_name":"2A. Shark Tank.py","file_ext":"py","file_size_in_byte":5436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"260166225","text":"from django.urls import path, include\nfrom . import views\n\nurlpatterns=[\n path('', views.index),\n path('join',views.join),\n path('login',views.verify),\n path('success',views.success),\n path('books',views.wall),\n path('logout',views.reset),\n path('books/add',views.add_book),\n path('add',views.add),\n path('books/',views.book),\n path('review',views.review),\n path('users/',views.user),\n path('delete',views.destroy),\n path('authors/',views.author),\n]","sub_path":"Dojo_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"452922185","text":"from dataclasses import dataclass\nfrom enum import Enum\nfrom typing import Union, Dict\n\n\n@dataclass\nclass ExplainerDependencyReference:\n \"\"\"Class for keeping track of dependencies required to Alibi runtime.\"\"\"\n\n explainer_name: str\n alibi_class: str\n runtime_class: str\n\n\n_ANCHOR_IMAGE_TAG = \"anchor_image\"\n_ANCHOR_TEXT_TAG = \"anchor_text\"\n_ANCHOR_TABULAR_TAG = \"anchor_tabular\"\n_INTEGRATED_GRADIENTS_TAG = \"integrated_gradients\"\n\n\n# NOTE: to add new explainers populate the below dict with a new\n# ExplainerDependencyReference, referencing the specific runtime class in mlserver\n# and the specific alibi explain class.\n# this can be simplified when alibi moves to a config based init.\n\n_BLACKBOX_MODULDE = \"mlserver_alibi_explain.explainers.black_box_runtime\"\n_INTEGRATED_GRADIENTS_MODULE = \"mlserver_alibi_explain.explainers.integrated_gradients\"\n\n_TAG_TO_RT_IMPL: Dict[str, ExplainerDependencyReference] = {\n _ANCHOR_IMAGE_TAG: ExplainerDependencyReference(\n explainer_name=_ANCHOR_IMAGE_TAG,\n runtime_class=f\"{_BLACKBOX_MODULDE}.AlibiExplainBlackBoxRuntime\",\n alibi_class=\"alibi.explainers.AnchorImage\",\n ),\n _ANCHOR_TABULAR_TAG: ExplainerDependencyReference(\n explainer_name=_ANCHOR_TABULAR_TAG,\n runtime_class=f\"{_BLACKBOX_MODULDE}.AlibiExplainBlackBoxRuntime\",\n alibi_class=\"alibi.explainers.AnchorTabular\",\n ),\n _ANCHOR_TEXT_TAG: ExplainerDependencyReference(\n explainer_name=_ANCHOR_TEXT_TAG,\n runtime_class=f\"{_BLACKBOX_MODULDE}.AlibiExplainBlackBoxRuntime\",\n alibi_class=\"alibi.explainers.AnchorText\",\n ),\n _INTEGRATED_GRADIENTS_TAG: ExplainerDependencyReference(\n explainer_name=_INTEGRATED_GRADIENTS_TAG,\n runtime_class=f\"{_INTEGRATED_GRADIENTS_MODULE}.IntegratedGradientsWrapper\",\n alibi_class=\"alibi.explainers.IntegratedGradients\",\n ),\n}\n\n\nclass ExplainerEnum(str, Enum):\n anchor_image = _ANCHOR_IMAGE_TAG\n anchor_text = _ANCHOR_TEXT_TAG\n anchor_tabular = _ANCHOR_TABULAR_TAG\n integrated_gradients = _INTEGRATED_GRADIENTS_TAG\n\n\ndef get_mlmodel_class_as_str(tag: Union[ExplainerEnum, str]) -> str:\n if isinstance(tag, ExplainerEnum):\n tag = tag.value\n return _TAG_TO_RT_IMPL[tag].runtime_class\n\n\ndef get_alibi_class_as_str(tag: Union[ExplainerEnum, str]) -> str:\n if isinstance(tag, ExplainerEnum):\n tag = tag.value\n return _TAG_TO_RT_IMPL[tag].alibi_class\n","sub_path":"runtimes/alibi-explain/mlserver_alibi_explain/alibi_dependency_reference.py","file_name":"alibi_dependency_reference.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"343094888","text":"import unittest\n\nimport torch\nfrom torch.testing._internal.common_device_type import (\n dtypes,\n instantiate_device_type_tests,\n)\nfrom torch.testing._internal.common_utils import TestCase\n\n\nclass TestFoo(TestCase):\n @dtypes(torch.float16, torch.int32)\n # fails for float16, passes for int32\n def test_bar(self, device, dtype):\n assert dtype == torch.int32\n\n # passes for float16, skips for int32\n @dtypes(torch.float16, torch.int32)\n def test_baz(self, device, dtype):\n if dtype == torch.int32:\n raise unittest.SkipTest\n\n assert True\n\n\ninstantiate_device_type_tests(TestFoo, globals(), only_for=\"cpu\")\n\n\nclass TestSpam(TestCase):\n def test_ham(self, device):\n assert True\n\n @dtypes(torch.float16)\n def test_eggs(self, device, dtype):\n assert False\n\n\ninstantiate_device_type_tests(TestSpam, globals(), only_for=\"cpu\")\n","sub_path":"tests/assets/test_dtype.py","file_name":"test_dtype.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"158899977","text":"# ### [545\\. Boundary of Binary TreeCopy for Markdown](https://leetcode.com/problems/boundary-of-binary-tree/)\n\n# Difficulty: **Medium**\n\n\n# Given a binary tree, return the values of its boundary in **anti-clockwise** direction starting from root. Boundary includes left boundary, leaves, and right boundary in order without duplicate **nodes**.  (The values of the nodes may still be duplicates.)\n\n# **Left boundary** is defined as the path from root to the **left-most** node. **Right boundary** is defined as the path from root to the **right-most** node. If the root doesn't have left subtree or right subtree, then the root itself is left boundary or right boundary. Note this definition only applies to the input binary tree, and not applies to any subtrees.\n\n# The **left-most** node is defined as a **leaf** node you could reach when you always firstly travel to the left subtree if exists. If not, travel to the right subtree. Repeat until you reach a leaf node.\n\n# The **right-most** node is also defined by the same way with left and right exchanged.\n\n# **Example 1**\n\n# ```\n# Input:\n# 1\n# \\\n# 2\n# / \\\n# 3 4\n\n# Ouput:\n# [1, 3, 4, 2]\n\n# Explanation:\n# The root doesn't have left subtree, so the root itself is left boundary.\n# The leaves are node 3 and 4.\n# The right boundary are node 1,2,4\\. Note the anti-clockwise direction means you should output reversed right boundary.\n# So order them in anti-clockwise without duplicates and we have [1,3,4,2].\n# ```\n\n# **Example 2**\n\n# ```\n# Input:\n# ____1_____\n# / \\\n# 2 3\n# / \\ /\n# 4 5 6\n# / \\ / \\\n# 7 8 9 10\n\n# Ouput:\n# [1,2,4,7,8,9,10,6,3]\n\n# Explanation:\n# The left boundary are node 1,2,4\\. (4 is the left-most node according to definition)\n# The leaves are node 4,7,8,9,10.\n# The right boundary are node 1,3,6,10\\. (10 is the right-most node).\n# So order them in anti-clockwise without duplicate nodes we have [1,2,4,7,8,9,10,6,3].\n# ```\n\n\n# #### Solution\n\n# Language: **Python3**\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def boundaryOfBinaryTree(self, root: TreeNode) -> List[int]:\n if not root:\n return []\n\n ans = []\n ans.append(root.val)\n\n self.leftBoundary(root.left, ans)\n self.leaves(root.left, ans)\n self.leaves(root.right, ans)\n self.rightBoundary(root.right, ans)\n return ans\n\n def leftBoundary(self, node, ans):\n if not node or self.isLeaf(node):\n return\n\n ans.append(node.val)\n if node.left:\n self.leftBoundary(node.left, ans)\n else:\n self.leftBoundary(node.right, ans)\n\n def leaves(self, node, ans):\n if not node:\n return\n\n if self.isLeaf(node):\n ans.append(node.val)\n return\n\n self.leaves(node.left, ans)\n self.leaves(node.right, ans)\n\n def rightBoundary(self, node, ans):\n if not node or self.isLeaf(node):\n return\n\n if node.right:\n self.rightBoundary(node.right, ans)\n else:\n self.rightBoundary(node.left, ans)\n ans.append(node.val)\n\n def isLeaf(self, node):\n return not node.left and not node.right\n","sub_path":"545.boundary-of-binary-tree.py","file_name":"545.boundary-of-binary-tree.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"622475056","text":"# Copyright (c) 2016, Eric A. Blundell\n# Copyright (c) 2016, \"a cheeky yena\"\n#\n# All rights reserved.\n#\n# CheekyBot is distributed under the following BSD 3-Clause License\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport discord\n\nfrom ..botcommand import BotCommand\nfrom ..botplugin import BotPlugin\nfrom ..argumentparser import ArgumentException\n\n\ndef _user_name_arg_type(user_name):\n if '#' not in user_name:\n raise ArgumentException('User name \"{user_name}\" does not contain a # discriminator number.'\n .format(user_name=user_name))\n return user_name\n\n\ndef _user_id_arg_type(user_id):\n if not user_id.isdigit() or len(user_id) != 18:\n raise ArgumentException('User ID \"{user_id}\" is not a valid discord ID, '\n 'it should be 18 characters and only digits.'\n .format(user_id=user_id))\n return user_id\n\n\nclass ClearChannelPublicCommandHandler(BotCommand):\n def __init__(self):\n super(ClearChannelPublicCommandHandler, self) \\\n .__init__('clear-channel',\n BotCommand.PUBLIC_ACCESS)\n\n self._parser = None\n\n def on_add(self, client):\n self._parser = self.create_arg_parser(\n description='Delete every message in the channel, optionally filtering by user names or IDs.')\n\n self._parser.add_argument(\n '--users', required=False, dest='user_names', nargs='+', type=_user_name_arg_type,\n help='The names of the users whose chat you want to clear, '\n 'each username must possess a # discriminator number.')\n\n self._parser.add_argument(\n '--user-ids', required=False, dest='user_ids', nargs='+', type=_user_id_arg_type,\n help='The long discord IDs of the users whose chat you want to clear, '\n 'you can get these with {prefix}get-user-id.'\n .format(prefix=self.settings.command_prefix))\n\n async def execute(self, command_arg, message):\n args = self.parse_args(self._parser, command_arg, message.author)\n\n if args is None:\n # argument errors, or help requested\n return\n\n client = self.client # type: cheekybot.BotClient\n\n client.log.info('User \"{user}\" called \"{prefix}clear-channel\" on channel \"{channel}\" of server \"{server}\"'\n .format(user=str(message.author),\n channel=message.channel.name,\n server=message.channel.server.name,\n prefix=self.settings.command_prefix))\n\n await client.clear_channel(message.channel.server,\n message.channel,\n user_names=args.user_names,\n user_ids=args.user_ids)\n\n def format_help(self):\n return self.format_basic_help(self.describe())\n\n def describe(self):\n return self._parser.format_help()\n\n\nclass ClearServerPublicCommandHandler(BotCommand):\n def __init__(self):\n super(ClearServerPublicCommandHandler, self) \\\n .__init__('clear-server',\n BotCommand.PUBLIC_ACCESS)\n\n self._parser = None\n\n def on_add(self, client):\n self._parser = self.create_arg_parser(\n description='Delete every message in every server, optionally filtering by user names or IDs.')\n\n self._parser.add_argument(\n '--users', required=False, dest='user_names', nargs='+', type=_user_name_arg_type,\n help='The names of the users whose chat you want to clear, '\n 'each username must possess a # discriminator number.')\n\n self._parser.add_argument(\n '--user-ids', required=False, dest='user_ids', nargs='+', type=_user_id_arg_type,\n help='The long discord IDs of the users whose chat you want to clear, '\n 'you can get these with {prefix}get-user-id.'\n .format(prefix=self.settings.command_prefix))\n\n async def execute(self, command_arg, message):\n args = self.parse_args(self._parser, command_arg, message.author)\n\n if args is None:\n # argument errors, or help requested\n return\n\n log = self.log # type: logging.Logger\n client = self.client # type: cheekybot.BotClient\n\n log.info('User \"{user}\" called \"{prefix}clear-server\" on server \"{server}\"'\n .format(user=str(message.author),\n server=message.channel.server.name,\n prefix=self.settings.command_prefix))\n\n for channel in message.channel.server.channels:\n if channel.type != discord.ChannelType.voice:\n await client.clear_channel(channel.server, channel,\n user_ids=args.user_ids,\n user_names=args.user_names)\n\n def format_help(self):\n return self.format_basic_help(self.describe())\n\n def describe(self):\n return self._parser.format_help()\n\n\nclass ClearChatPublicPlugin(BotPlugin):\n def __init__(self):\n super(ClearChatPublicPlugin, self) \\\n .__init__(__name__)\n\n self._commands = [\n ClearServerPublicCommandHandler(),\n ClearChannelPublicCommandHandler()\n ]\n\n self._perms = discord.Permissions()\n self._perms.manage_messages = True\n self._perms.read_messages = True\n self._perms.read_message_history = True\n\n @property\n def required_permissions(self):\n return self._perms\n\n def on_add(self, client):\n client.add_commands(self._commands)\n\n def on_remove(self, client):\n client.remove_commands(self._commands)\n","sub_path":"src/cheekybot/coreplugins/clearchat.py","file_name":"clearchat.py","file_ext":"py","file_size_in_byte":7216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"349935569","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/local/lib/python2.7/site-packages/pycrunchbase/resource/address.py\n# Compiled at: 2017-01-13 23:45:16\nimport six\nfrom .node import Node\n\n@six.python_2_unicode_compatible\nclass Address(Node):\n \"\"\"Represents a Address on CrunchBase\"\"\"\n KNOWN_PROPERTIES = [\n 'name',\n 'street_1',\n 'street_2',\n 'postal_code',\n 'city',\n 'city_path',\n 'city_web_path',\n 'region',\n 'region_path',\n 'region_web_path',\n 'country',\n 'country_path',\n 'country_web_path',\n 'latitude',\n 'longitude',\n 'created_at',\n 'updated_at']\n\n def _coerce_values(self):\n for attr in ['latitude', 'longitude']:\n if getattr(self, attr, None):\n setattr(self, attr, float(getattr(self, attr)))\n\n return\n\n def __str__(self):\n return ('{name} {street_1}').format(name=self.name, street_1=self.street_1)\n\n def __repr__(self):\n return self.__str__()","sub_path":"pycfiles/pycrunchbase-0.3.8.macosx-10.12-x86_64.tar/address.py","file_name":"address.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"622198166","text":"#!/usr/bin/env python\n\n# Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de\n# Barcelona (UAB), and the INTEL Visual Computing Lab.\n#\n# This work is licensed under the terms of the MIT license.\n# For a copy, see .\n\n\n\n\"\"\"\nRosbridge class:\n\nClass that handle communication between mono and ROS\n\"\"\"\nimport random, time\nfrom itertools import count\nfrom multiprocessing import Event\n\nfrom rosgraph_msgs.msg import Clock\nfrom tf2_msgs.msg import TFMessage\nimport rospy\n\n\nfrom monodrive import Simulator, SimulatorConfiguration, VehicleConfiguration\n#from mono.settings import monoSettings\n#from monodrive_ros_bridge.control import InputController\nfrom monodrive_ros_bridge.markers import PlayerAgentHandler, NonPlayerAgentsHandler\nfrom monodrive_ros_bridge.sensors import BoundingBoxHandler, CameraHandler, \\\n GpsHandler, LidarHandler, ImuHandler, RpmHandler, WaypointHandler\n\nfrom monodrive.vehicles import SimpleVehicle\n\n\nclass RosVehicle(SimpleVehicle):\n def __init__(self, simulator_config, vehicle_config, restart_event=None, **kwargs):\n super(RosVehicle, self).__init__(simulator_config, vehicle_config, restart_event)\n self.running = False\n self.episode_event = Event()\n\n def start(self):\n rospy.loginfo(\"starting vehicle process\")\n self.running = True\n super(RosVehicle, self).start()\n\n def run(self):\n rospy.loginfo(\"running vehicle process\")\n while self.running:\n self.episode_event.wait()\n\n def stop(self):\n rospy.loginfo(\"stopping vehicle process\")\n self.running = False\n super(RosVehicle, self).stop()\n\n def end_episode(self):\n self.episode_event.set()\n\n\nclass MonoRosBridge(object):\n \"\"\"\n monoDrive Ros bridge\n \"\"\"\n\n def __init__(self, params):\n \"\"\"\n\n :param params: dict of parameters, see settings.yaml\n :param rate: rate to query data from mono in Hz\n \"\"\"\n self.frames_per_episode = params['Framesperepisode']\n\n # Simulator configuration defines network addresses for connecting to the simulator and material properties\n simulator_config = SimulatorConfiguration(params['SimulatorConfig'])\n\n # Vehicle configuration defines ego vehicle configuration and the individual sensors configurations\n self.vehicle_config = VehicleConfiguration(params['VehicleConfig'])\n\n self.simulator = Simulator(simulator_config)\n self.vehicle = self.simulator.get_ego_vehicle(self.vehicle_config, RosVehicle)\n\n self.param_sensors = params.get('sensors', {})\n\n self.tf_to_publish = []\n self.msgs_to_publish = []\n self.publishers = {}\n\n # definitions useful for time\n self.cur_time = rospy.Time.from_sec(\n 0) # at the beginning of simulation\n self.mono_game_stamp = 0\n self.mono_platform_stamp = 0\n\n # creating handler to handle vehicles messages\n self.player_handler = PlayerAgentHandler(\n \"player_vehicle\", process_msg_fun=self.process_msg)\n self.non_players_handler = NonPlayerAgentsHandler(\n \"vehicles\", process_msg_fun=self.process_msg)\n\n # creating handler for sensors\n self.sensors = {}\n print(self.param_sensors)\n for t, sensors in self.param_sensors.items():\n for id in sensors:\n self.add_sensor(sensors[id])\n\n # creating input controller listener\n #self.input_controller = InputController()\n\n def add_sensor(self, sensor):\n rospy.loginfo(\"Adding sensor {}\".format(sensor))\n sensor_type = sensor['type']\n id = sensor['id'] #'{0}.{1}'.format(sensor_type, sensor['id'])\n sensor_handler = None\n if sensor_type == 'Lidar':\n sensor_handler = LidarHandler\n elif sensor_type == 'Camera':\n sensor_handler = CameraHandler\n elif sensor_type == 'IMU':\n sensor_handler = ImuHandler\n elif sensor_type == 'GPS':\n sensor_handler = GpsHandler\n elif sensor_type=='RPM':\n sensor_handler = RpmHandler\n elif sensor_type == 'BoundingBox':\n sensor_handler = BoundingBoxHandler\n elif sensor_type == 'Waypoint':\n sensor_handler = WaypointHandler\n\n if sensor_handler:\n if self.sensors.get(sensor_type, None) is None:\n self.sensors[sensor_type] = []\n\n self.sensors[sensor_type].append(sensor_handler(\n id,\n self.vehicle.get_sensor(sensor_type, id),\n process_msg_fun=self.process_msg))\n else:\n rospy.logerr(\n \"Unable to handle sensor {name} of type {sensor_type}\".format(\n sensor_type=sensor_type, name=id))\n\n\n def on_shutdown(self):\n rospy.loginfo(\"Shutdown requested\")\n\n def process_msg(self, topic=None, msg=None):\n \"\"\"\n Function used to process message\n\n Here we create publisher if not yet created\n Store the message in a list (waiting for their publication) with their associated publisher\n\n Messages for /tf topics are handle differently in order to publish all transform in the same message\n :param topic: topic to publish the message on\n :param msg: monodrive_ros_bridge message\n \"\"\"\n\n #rospy.loginfo(\"publishing on {0}\".format(topic))\n\n if topic not in self.publishers:\n if topic == 'tf':\n self.publishers[topic] = rospy.Publisher(\n topic, TFMessage, queue_size=100)\n else:\n self.publishers[topic] = rospy.Publisher(\n topic, type(msg), queue_size=10)\n\n if topic == 'tf':\n # transform are merged in same message\n self.tf_to_publish.append(msg)\n else:\n self.msgs_to_publish.append((self.publishers[topic], msg))\n\n def send_msgs(self):\n for publisher, msg in self.msgs_to_publish:\n publisher.publish(msg)\n self.msgs_to_publish = []\n\n tf_msg = TFMessage(self.tf_to_publish)\n self.publishers['tf'].publish(tf_msg)\n self.tf_to_publish = []\n\n def compute_cur_time_msg(self):\n self.process_msg('clock', Clock(self.cur_time))\n\n def run(self):\n self.publishers['clock'] = rospy.Publisher(\n \"clock\", Clock, queue_size=10)\n\n rospy.loginfo('Starting Vehicle')\n # Start the Vehicle process\n #self.vehicle = self.simulator.start_vehicle(self.vehicle_config, RosVehicle)\n\n for frame in count():\n if (frame == self.frames_per_episode) or rospy.is_shutdown():\n rospy.loginfo(\"----- end episode -----\")\n break\n\n# rospy.loginfo(\"waiting for data\")\n# self.vehicle.sensor_data_ready.wait()\n\n rospy.loginfo(\"processing data\")\n for sensor in self.vehicle.sensors:\n if self.sensors.get(sensor.type, None):\n rospy.loginfo(\"getting data from {0}{1}\".format(sensor.type,sensor.sensor_id))\n\n processor = None\n sensors = self.sensors[sensor.type]\n for s in sensors:\n if s.name == sensor.sensor_id:\n processor = s\n\n try:\n data = sensor.q_vehicle.peek()\n processor.process_sensor_data(data, self.cur_time)\n except:\n while not sensor.q_vehicle.empty():\n data = sensor.q_vehicle.get()\n processor.process_sensor_data(data, self.cur_time)\n\n rospy.loginfo(\"publishing messages\")\n # publish all messages\n self.send_msgs()\n\n self.vehicle.sensor_data_ready.clear()\n control_data = self.vehicle.drive(self.vehicle.sensors, None)\n rospy.loginfo(\"--> {0}\".format(control_data))\n self.vehicle.send_control_data(control_data)\n\n rospy.loginfo(\"waiting for data\")\n self.vehicle.sensor_data_ready.wait()\n\n '''\n measurements, sensor_data = self.client.read_data()\n\n # handle time\n self.mono_game_stamp = measurements.game_timestamp\n self.cur_time = rospy.Time.from_sec(self.mono_game_stamp * 1e-3)\n self.compute_cur_time_msg()\n\n # handle agents\n self.player_handler.process_msg(\n measurements.player_measurements, cur_time=self.cur_time)\n self.non_players_handler.process_msg(\n measurements.non_player_agents, cur_time=self.cur_time)\n\n # handle sensors\n for name, data in sensor_data.items():\n self.sensors[name].process_sensor_data(data, self.cur_time)\n\n # publish all messages\n self.send_msgs()\n\n # handle control\n if rospy.get_param('mono_autopilot', True):\n control = measurements.player_measurements.autopilot_control\n self.client.send_control(control)\n else:\n control = self.input_controller.cur_control\n self.client.send_control(**control)\n '''\n\n # Waits for the restart event to be set in the control process\n self.vehicle.restart_event.wait()\n\n # Terminates control process\n self.vehicle.stop()\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n rospy.loginfo(\"Exiting Bridge\")\n return None\n","sub_path":"monodrive_ros_bridge/src/monodrive_ros_bridge/bridge.py","file_name":"bridge.py","file_ext":"py","file_size_in_byte":9670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"518863541","text":"# https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/\n\ndef solution(graph, start, visited=[]):\n visited.append(start)\n\n for edge in graph[start]:\n if edge not in visited:\n solution(graph, edge, visited) \n\n return visited\n\n\nG = {\n 0: [1, 2],\n 1: [2],\n 2: [0, 3],\n 3: [3]\n}\nassert [2, 0, 1, 3] == solution(G, 2, [])\n","sub_path":"graph/dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"39290891","text":"# Pesquisa para resolucao de problemas de atribuicao\n# \n# Introducao a Inteligencia Artificial\n# DETI / UA\n#\n# (c) Luis Seabra Lopes, 2012-2019\n#\n\n\nclass ConstraintSearch:\n\n # domains é um dicionário com o domínio de cada variável;\n # constaints e' um dicionário com a restrição aplicável a cada aresta;\n def __init__(self,domains,constraints):\n self.domains = domains\n self.constraints = constraints\n self.calls = 0\n\n # domains é um dicionário com os domínios actuais\n # de cada variável\n # ( ver acetato \"Pesquisa com propagacao de restricoes\n # em problemas de atribuicao - algoritmo\" )\n def search(self,domains=None):\n print(\"starting\")\n self.calls += 1 \n \n if domains==None:\n domains = self.domains\n\n # se alguma variavel tiver lista de valores vazia, falha\n if any([lv==[] for lv in domains.values()]):\n return None\n\n # se nenhuma variavel tiver mais do que um valor possivel, sucesso\n if all([len(lv)==1 for lv in list(domains.values())]):\n return { v:lv[0] for (v,lv) in domains.items() }\n \n # continuação da pesquisa\n # ( falta fazer a propagacao de restricoes )\n for var in domains.keys():\n if len(domains[var])>1:\n for val in domains[var]:\n newdomains = dict(domains)\n if val[0] == val[1]:\n continue\n newdomains[var] = [val]\n print(newdomains)\n newdomains = self.constrain(newdomains,var,val)\n print(newdomains)\n solution = self.search(newdomains)\n if solution != None:\n return solution\n return None\n\n def constrain(self,domain,var1,val1):\n newdomain = {}\n for var in domain.keys():\n if var1 != var:\n temp = [] + domain[var]\n for val in domain[var]:\n constraint = self.constraints[var1,var]\n if not constraint(var1,val1,var,val):\n temp.remove(val)\n domain[var] = temp\n return domain\n","sub_path":"IIA/guiao-sobre-pesquisa-Deadbeastrs/constraintsearch.py","file_name":"constraintsearch.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"411940635","text":"from socket import *\nimport json\n\nserver_port = 53533\n\nserverSock = socket(AF_INET, SOCK_DGRAM)\nserverSock.bind(('', server_port))\nip_map = {}\n\nwhile True:\n query_message, addr = serverSock.recvfrom(2048)\n response_message = get_request(query_message)\n serverSock.sendto(response_message, addr)\n\ndef get_request(query_message):\n message = json.loads(query_message.decode())\n ip = 'VALUE' in message\n if not ip:\n hostname = message['NAME']\n request_type = message['TYPE']\n return dns_query(hostname, request_type)\n else:\n hostname = message['NAME']\n ip = message['VALUE']\n request_type = message['TYPE']\n ttl = message['TTL']\n return register(hostname, ip, request_type, ttl)\n\ndef dns_query(hostname, request_type):\n content = ip_map[request_type + '' + hostname]\n fs_ip = content ['VALUE']\n return str(fs_ip).encode()\n\ndef register(hostname, ip, request_type, ttl):\n content = {'TYPE': request_type, 'NAME': hostname, 'VALUE': ip, 'TTL': ttl}\n key = request_type + '' + hostname\n ip_map[key] = content\n return json.dumps('').encode()\n\n","sub_path":"AS/As.py","file_name":"As.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"484325248","text":"# -*- coding: utf-8 -*-\n\nfrom core import *\nfrom datetime import datetime\n\nclass MyCollection(Collection):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\n\tdef load_batched(self, _id, _type, *args):\n\t\treturn set()\n\n\tdef load_events(self, agenda, from_date, to_date):\n\t\treturn set()\n\n\tdef load_last_events(self, agenda, from_date, to_date):\n\t\treturn set()\n\ncollection = MyCollection()\n\nagenda = Agenda.new(collection, \"perso\")\n\ntoday = datetime.now()\nhour = timedelta(hours=1)\nhalf = timedelta(minutes=30)\n\nev1 = Event.new(collection, today, today + hour, \"INFO_402\", \"\", set(), set())\nev2 = Event.new(collection, today + hour, today + hour * 2, \"INFO_402\", \"\", set(), set())\n\nl = WeakRefSet()\nl.add(ev1)\nl.add(ev2)\n\nprint(\"list :\")\nprint(l)\n\nprint(\"weak refs ev1\")\nprint(ev1._weakrefs)\nprint(\"weak refs ev2\")\nprint(ev2._weakrefs)\n\nprint(\"delete 2\")\nev2.delete()\nprint(\"delete 1\")\nev1.delete()\n\nprint(\"list :\")\nprint(l)\n","sub_path":"Source/check/delete_user_event.py","file_name":"delete_user_event.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"401713096","text":"# -*- coding: utf-8 -*-\n# #############################################################################\n#\n# Copyright Eezee-It (C) 2018\n# Author: Eezee-It \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program. If not, see .\n#\n###############################################################################\nfrom odoo import fields, models, api, _\nfrom odoo.exceptions import UserError\nACQUIRER_MODELS = [\n 'sale.order',\n 'payment.transaction'\n]\n\n\nclass force_update_data(models.TransientModel):\n _name = 'force.update.data'\n\n acquirer_reference = fields.Char(string=u'Acquirer Reference Id')\n\n @api.multi\n def force_update(self):\n self.ensure_one()\n context = dict(self._context or {})\n active_id = context.get('active_id', False)\n active_model = context.get('active_model', False)\n if active_id and active_model:\n record = self.env[active_model].browse(active_id)\n if active_model in ACQUIRER_MODELS:\n record.acquirer_reference = self.acquirer_reference\n else:\n raise UserError(\n _(\"This template does not belong to authorized Models\"\n \" for changing the 'acquirer_reference' field, please\"\n \" contact your administrator!\"))\n return True\n","sub_path":"payment_mollie_official/wizard/force_updates.py","file_name":"force_updates.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"254952039","text":"\"\"\"For determining contact resistance in OFETS.\n\nAuthor: Ross \n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport glob\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\nfrom scipy.optimize import curve_fit\nfrom uncertainties import ufloat, unumpy\n\n\ndef readIV(path, sample, date):\n \"\"\"Read in iv csv and loop for all in folder.\"\"\"\n iv20, iv10, iv5, iv2 = [], [], [], []\n\n for file in glob.glob(path + '/*-20-*-iv-sweep.csv'):\n try:\n data = pd.read_csv(file, header=0, delimiter='\\t')\n iv20.insert(0, data)\n except FileNotFoundError:\n print('Error! File not found: ', file)\n\n for file in glob.glob(path + '/*-10-*-iv-sweep.csv'):\n try:\n data = pd.read_csv(file, header=0, delimiter='\\t')\n iv10.insert(0, data)\n except FileNotFoundError:\n print('Error! File not found: ', file)\n\n for file in glob.glob(path + '/*-5-*-iv-sweep.csv'):\n try:\n data = pd.read_csv(file, header=0, delimiter='\\t')\n iv5.insert(0, data)\n except FileNotFoundError:\n print('Error! File not found: ', file)\n\n for file in glob.glob(path + '/*-2p5-*-iv-sweep.csv'):\n try:\n data = pd.read_csv(file, header=0, delimiter='\\t')\n iv2.insert(0, data)\n except FileNotFoundError:\n print('Error! File not found: ', file)\n\n return iv20, iv10, iv5, iv2\n\n\ndef plotIV(ivList, sample, date, saveLoc, channelLength, filmThickness,\n compliance=9.9e-6):\n \"\"\"Create plot from iv data.\"\"\"\n figIV = plt.figure(figsize=(7, 5))\n ax = figIV.gca()\n R = [] # list of resistance values\n o = [] # list of conductivity values\n\n for iv in ivList:\n # Filter out measurements at compliance.\n iv = iv.where(iv['Channel Current [A]'] < compliance)\n ax.plot(iv['Channel Voltage [V]'] / (float(channelLength) * 1e-4),\n iv['Channel Current [A]'])\n \n # Make Ohmic fit to data\n def ohmsLaw(I, R):\n return I * R\n \n popt, pcov = curve_fit(ohmsLaw, iv['Channel Current [A]'],\n iv['Channel Voltage [V]'])\n perr = np.sqrt(np.diag(pcov))\n R1 = ufloat(popt[0], perr[0])\n R.append(R1)\n # Calculate conductivity\n o1 = (1 / R1) * float(channelLength * 1e-6) * (1 / (10e-3 * filmThickness))\n o.append(o1)\n \n # Outputting the fits\n R = np.asarray(R)\n o = np.asarray(o)\n print('Resistance \\t', R.mean(), '\\t [Ohms]')\n print('Conductivity \\t', o.mean(), '\\t [S/m]')\n\n # Figure formatting\n ax.set_title(date + \" \" + sample + \" \" + str(channelLength) + \" um\")\n ax.set_xlabel('E [V / cm]')\n ax.set_ylabel('I [A]')\n ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.0e'))\n ax.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.0e')) \n \n # Outputting figure\n try:\n fname = str(saveLoc + sample + '-' + str(channelLength) +\n '-iv.png')\n figIV.savefig(fname, dpi=300)\n except FileNotFoundError:\n print(\"ERROR! DATA NOT SAVED. LOC NOT FOUND: \", saveLoc)\n \n figIV.tight_layout()\n #plt.show()\n \n return R.mean(), o.mean()\n\n\n\ndef plotResistance(R, saveLoc):\n \"\"\"Plot resistance against channel length.\"\"\"\n try:\n # Define what what we are plotting\n x = np.array(Rlist[:,0], dtype=float)\n y = np.array(unumpy.nominal_values(Rlist[:,1]), dtype=float)\n \n fig = plt.figure(figsize=(7, 5))\n ax = fig.gca()\n \n ax.errorbar(x, y, unumpy.std_devs(Rlist[:,1]), marker=\".\",\n linestyle=\"none\", label='data')\n \n # Fit contact resistance via transmission line method (linear)\n def transmissionLine(x, m, c):\n return m* x + c\n \n popt, pcov = curve_fit(transmissionLine, x, y)\n \n perr = np.sqrt(np.diag(pcov))\n contactR = ufloat(popt[1], perr[1])\n \n fitR = transmissionLine(np.linspace(0,20,80), popt[0], popt[1])\n ax.plot(np.linspace(0,20,80), fitR, label='fit')\n \n # Figure formatting\n ax.legend()\n label = str(\"Contact resistance = \" + str(contactR) + \" Ohms\")\n #ax.text(1,1, label)\n ax.set_xlabel('Channel length [um]')\n ax.set_ylabel('Resistance [Ohms]')\n ax.ticklabel_format(axis='y' ,style='sci', scilimits=(0,0))\n \n print(\"Contact resistance\\t\", contactR, \"\\t[Ohms]\")\n \n fig.tight_layout()\n \n except FileExistsError:\n print(\"Wrong format for resistance data.\")\n \n \nif __name__ == \"__main__\":\n\n # Sample metadata\n sample = \"znpc-dped2pt\"\n date = \"100418\"\n path = str(\"/home/ross/physics/data/008_EPR/100418-iv-sweeps/\" + sample + \"/\")\n saveLoc = (\"/home/ross/physics/projects/008_EPR/PLOTS/\" + sample + \"/\")\n filmThickness = ufloat(30e-9, 2e-9)\n \n # Read in data\n iv20, iv10, iv5, iv2 = readIV(path, sample, date)\n \n # Plot iv's\n R20, o20 = plotIV(iv20, sample, date, saveLoc, 20, filmThickness)\n R10, o10 = plotIV(iv10, sample, date, saveLoc, 10, filmThickness)\n R5, o5 = plotIV(iv5, sample, date, saveLoc, 5, filmThickness)\n R2, o2 = plotIV(iv2, sample, date, saveLoc, 2.5, filmThickness)\n \n # Plot resistance and conductivity\n Rlist = np.array( [ [20, R20, o20], [10, R10, o10],\n [5, R5, o5], [2.5, R2, o2] ] )\n plotResistance(Rlist, saveLoc)\n plt.show() # Render all graphs together\n","sub_path":"plot-scripts/ofetContactResis.py","file_name":"ofetContactResis.py","file_ext":"py","file_size_in_byte":5597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"317944851","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common.keys import keys\r\n\r\nbrowser=webdriver.Firefox()\r\nbrowser.get(\"link\")\r\n\r\nelm=browser.find_element_by_link_text('about')\r\nbrowser.implicitly_wait(5)\r\nelm.click()\r\nprint(broswer.current_url)","sub_path":"get current url.py","file_name":"get current url.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"190870757","text":"#!/usr/bin/python\n\n\"\"\" \n Starter code for exploring the Enron dataset (emails + finances);\n loads up the dataset (pickled dict of dicts).\n\n The dataset has the form:\n enron_data[\"LASTNAME FIRSTNAME MIDDLEINITIAL\"] = { features_dict }\n\n {features_dict} is a dictionary of features associated with that person.\n You should explore features_dict as part of the mini-project,\n but here's an example to get you started:\n\n enron_data[\"SKILLING JEFFREY K\"][\"bonus\"] = 5600000\n \n\"\"\"\n\nimport pickle\nimport sys\nimport numpy\n\nsys.path.append('../tools/features_format.py')\n\nenron_data = pickle.load(open(\"../final_project/final_project_dataset.pkl\", \"r\"))\n\n### Number of persons ###\ndef quant_persons(): \n\treturn len(enron_data.keys())\n\n### Number of features per person ###\ndef quant_features(): \n\tpersons = enron_data.keys()\n\treturn len(enron_data[persons[1]])\n\n### Quantity of a known feature ###\ndef quant_known_feature(feature): \n\tquant = 0\n\tpersons = enron_data.keys()\n\tfor person in persons:\n\t\tif enron_data[person][feature] != 'NaN':\n\t\t\tquant+=1\n\treturn quant\n\n### Quantity of a unknown feature ###\ndef quant_nan_feature(feature): \n\tquant = 0 \n\tpersons = enron_data.keys()\n\tfor person in persons:\n\t\tif enron_data[person][feature] == 'NaN':\n\t\t\tquant+=1\n\treturn quant\n\n### Total number of data points in set ###\ndef quant_data_points():\n\tpersons = quant_persons()\n\tfeatures_per_person = quant_features()\n\treturn persons * features_per_person\n\n### Convert dictionary to Numpy array ###\n","sub_path":"datasets_questions/explore_enron_data.py","file_name":"explore_enron_data.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"631620117","text":"import tensorflow as tf\nimport os, sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\ntags = ['HAB', 'HAB_C', 'BAC', 'BAC_C', 'GEO', 'GEO_C']\ntampered = []\ndef convert_output(path, filenames):\n outputs = []\n for filename in filenames:\n # filename = 'BB-cat+ner-6107735'\n # print(filename)\n with tf.gfile.GFile(path+'/'+filename+'.txt', \"r\") as f:\n with tf.gfile.GFile(path+'/'+filename+'.a2', \"r\") as f1:\n text = f.read().decode('utf-8')\n # print (text.split())\n init = len(text.split())\n a2 = f1.read().splitlines()\n red = 0\n end = 0\n for line in a2:\n if line[0] == 'T':\n split_line = line.split()\n if ';' in split_line[3]:\n split_line.remove(split_line[3]);\n tampered.append(filename)\n left = int(split_line[2]) - red\n right = int(split_line[3]) - red\n if int(split_line[3]) <= end:\n continue\n end = int(split_line[3])\n # print (text[left:right] + \" : \" + split_line[1][0:3].upper() + \" \" + str(red))\n # print (text)\n red = red + len(text)\n if text[left-1] not in [' ', '\\n']:\n left -= 1;\n if text[right] not in [' ', '\\n']:\n right += 1;\n text = text[:left] + split_line[1][0:3].upper() + ''.join([' ' + split_line[1][0:3].upper() + '_C']*len(split_line[5:])) + text[right:]\n red = red - len(text)\n new_text = ['OTH' if word not in tags else word for word in text.strip().split()]\n if init != len(text.split()):\n print (filename)\n # print(text.split())\n # print(' '.join(new_text))\n # with tf.gfile.GFile(path+'/'+filename+'.out', \"w\") as f:\n # f.write((' '.join(new_text)).encode('utf-8'))\n # break\n # return outputs\n\npath = 'data/BioNLP-ST-2016_BB-cat+ner_train'\nfilenames = []\nfor file in os.listdir(path):\n if file.endswith(\".txt\"):\n filenames.append(file[:-4])\n# print(convert_output(path,filenames))\nconvert_output(path, filenames)\n# print len(out)\n","sub_path":"Code/prepare_output.py","file_name":"prepare_output.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"223363210","text":"#encoding=utf-8\r\n\r\nimport os\r\nimport numpy as np\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nimport sys\r\n\r\ndef getDev():\r\n dev_path = './dev'\r\n train_path = './train'\r\n if not os.path.exists(dev_path):\r\n os.mkdir(dev_path)\r\n img_list = os.listdir(train_path)\r\n for i in range(len(img_list)):\r\n if i % 20 == 0:\r\n os.rename(os.path.join(train_path, img_list[i]), os.path.join(dev_path, img_list[i]))\r\n\r\ndef getLabel():\r\n file_path = './sample_submission.csv'\r\n names = []\r\n with open(file_path, 'r') as f:\r\n for line in f:\r\n # print(line)\r\n names = line.strip().split(',')[1:]\r\n break\r\n labels = {}\r\n for i in range(len(names)):\r\n labels[names[i]] = i\r\n return labels\r\n\r\ndef renamePic():\r\n Map = {}\r\n with open('labels.csv', 'r') as f:\r\n for line in f:\r\n info = line.split(',')\r\n if info[0] == 'id':\r\n continue\r\n Map[info[0]] = info[1].strip()\r\n dev_path = './dev'\r\n train_path = './train'\r\n train_list = os.listdir(train_path)\r\n num = 0\r\n for item in train_list:\r\n name = item.split('.')\r\n os.rename(os.path.join(train_path, item), os.path.join(train_path, Map[name[0]] + '+' + str(num) + '.' + name[1]))\r\n num += 1\r\n dev_list = os.listdir(dev_path)\r\n for item in dev_list:\r\n name = item.split('.')\r\n os.rename(os.path.join(dev_path, item), os.path.join(dev_path, Map[name[0]] + '+' + str(num) + '.' + name[1]))\r\n num += 1\r\n\r\ndef show(img):\r\n img = (img + 1.0) / 2.0\r\n nimg = img.numpy()\r\n plt.imshow(np.transpose(nimg, (1, 2, 0)))\r\n plt.show()\r\n\r\ndef bar(t, s, e, ls):\r\n sys.stdout.write('\\rEpoch ' + str(e) + ' [' + '*' * int(t*100/s+1) + ' ' * (100-int(t*100/s+1)) + '] ' +\r\n 'loss = %.5f' % ls)\r\n sys.stdout.flush()\r\n\r\n\r\nif __name__ == '__main__':\r\n # pass\r\n getDev()\r\n renamePic()\r\n # print(getLabel())\r\n","sub_path":"DogsClassification/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"240129154","text":"__author__ = 'joshuahiggins'\nfrom hard_car import Car\nimport pytest\n\ndef test_car_has_length():\n car = Car()\n assert car.length == 5\n\n\ndef test_car_has_location():\n car = Car()\n assert car.location == 0\n\n\ndef test_car_has_speed():\n car = Car()\n assert car.speed == 0\n\n\ndef test_car_can_not_go_faster_than_34():\n car = Car()\n car.speed = 33\n car.accelerate()\n assert car.speed == 34\n\n\ndef test_car_accelerates():\n car = Car()\n car.accelerate()\n assert car.speed == 2\n\n\ndef test_car_decelerates():\n car = Car()\n car.speed = 30\n car.decelerate()\n assert car.speed == 28\n\n\ndef test_car_can_not_go_negative():\n car = Car()\n car.speed = 0\n car.decelerate()\n assert car.speed == 0\n\n\ndef test_car_matches_speed_car_in_front():\n car1 = Car()\n car1.speed = 24\n car2 = Car()\n car2.speed = 20\n car1.slow_down(car2)\n assert car1.speed == 20\n\n\ndef test_car_checks_position_and_sets_next_speed():\n car1 = Car()\n car2 = Car()\n car1.speed = 30\n car2.speed = 25\n\n\ndef test_car_decides_to_slow_down():\n car1 = Car()\n car2 = Car()\n car1.speed = 25\n car2.speed = 27\n car1.location = 100\n car2.location = 80\n assert car2.calculate_slowdown(car1) == True\n\n\ndef test_car_does_not_slow_down():\n car1 = Car()\n car2 = Car()\n car1.speed = 25\n car2.speed = 27\n car1.location = 115\n car2.location = 80\n assert car2.calculate_slowdown(car1) == False\n\n\ndef test_car_that_has_looped_still_makes_car_behind_slow_down():\n car1 = Car()\n car2 = Car()\n car1.speed = 25\n car2.speed = 27\n car1.location = 2\n car2.location = 980\n assert car2.calculate_slowdown(car1) == True\n\n\ndef test_car_that_has_looped_does_not_make_car_behind_slow_down():\n car1 = Car()\n car2 = Car()\n car1.speed = 25\n car2.speed = 27\n car1.location = 15\n car2.location = 980\n assert car2.calculate_slowdown(car1) == False\n\n\n\n\n\n\n\n\n","sub_path":"hard_test_cars.py","file_name":"hard_test_cars.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"634609310","text":"\n\n#calss header\nclass _PARASITE():\n\tdef __init__(self,): \n\t\tself.name = \"PARASITE\"\n\t\tself.definitions = [u'an animal or plant that lives on or in another animal or plant of a different type and feeds from it: ', u'a person who is lazy and lives by other people working, giving them money, etc.: ']\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/_parasite.py","file_name":"_parasite.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"516404813","text":"import random\nimport sqlite3\ncon=sqlite3.connect('test1.db')\nc=con.execute(\"select * from students\")\nprint(\"records inserted are :\")\n#con.execute(\"Create table guesses(user text not null,student text not null,department text not null,choice integer not null);\")\ndict1={}\nfor i in c:\n dict1[i[0]]=i[1]\nkey = list(dict1.keys())\ntemp = dict1.values()\nval = list(temp)\nstud=\"\"\nchoice1=[]\nchoice2=[]\nchoice3=[]\nchoice4=[]\nchoice5=[]\nchoice6=[]\nchoice7=[]\nchoice8=[]\ndef pick():\n global stud\n stud = random.choice(key)\n print(\"Guess your friend \" + stud + \"'s department:\")\ndef guess():\n guess1 = input()\n return guess1\ntotal=1\nn=int(input(\"enter the total plays : \"))\nprint(\"here the game starts\")\nwhile total None:\n \"\"\"Main function\"\"\"\n string = \"The Daily Byte\"\n\n for index, char in enumerate(reversed(string)):\n if char in WHITESPACE:\n print(index)\n break\n else:\n print(len(string))\n\n # Alternative\n print(len(string) - re.search(r'\\b\\w+$', string).start()) # type: ignore\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"p125_word_length.py","file_name":"p125_word_length.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"544744644","text":"# This file is used to download the XEP list and convert it to JSON\nimport sys\nimport os\nimport json\nimport requests\nimport xml.etree.ElementTree as ET\n\n\ndef status_ok(status_code):\n # Status codes ranging from 200 (OK) to 300 (redirects) are okay\n if status_code >= 200 and status_code < 400:\n return True\n return False\n\n\nxeplist_request = requests.get(\"https://xmpp.org/extensions/xeplist.xml\")\nif not status_ok(xeplist_request.status_code):\n quit(f'Error while downloading xeplist.xml ({xeplist_request.status_code}')\n\ntry:\n root = ET.fromstring(xeplist_request.content)\nexcept Exception:\n quit('Error while parsing xeplist.xml')\n\ndef fix_status(status):\n if status == 'Draft':\n return 'Stable'\n return status\n\nxeps = []\nfor xep in root.findall(\"xep\"):\n if xep.get(\"accepted\") == \"true\":\n xeps.append(\n {\n \"title\": xep.find(\"title\").text,\n \"status\": fix_status(xep.find(\"status\").text),\n \"number\": int(xep.find(\"number\").text),\n \"last_updated\": xep.find(\"last-revision\").find(\"date\").text,\n \"type\": xep.find(\"type\").text,\n }\n )\n\nbase_path = os.path.dirname(os.path.abspath(sys.argv[0]))\n\nwith open(f'{base_path}/../data/xeplist.json', 'w') as json_file:\n json.dump(xeps, json_file, indent=4)\nprint('XEP List prepared successfully')\n","sub_path":"tools/prepare_xep_list.py","file_name":"prepare_xep_list.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"139279809","text":"import os\nimport sublime\nimport sublime_plugin\nfrom ..utils import *\n\n\ndef getInfo(text):\n\trelative = True\n\tif text.startswith(\"~\"):\n\t\ttext = text[1:]\n\t\trelative = False\n\n\tif not isProject() and not isFile():\n\t\tsublime.error_message(\"Unknown package location\")\n\t\treturn\n\tif not isPackage(text):\n\t\tsublime.error_message(\"Invalid package naming\")\n\t\treturn\n\n\tpackage = normalizePackage(getCurrentPackage(not relative) + \".\" + getPackagePath(text))\n\tclassName = getClassName(text)\n\n\ttarget_dir = makePackage(getPackageRootDir(), packageAsDirectory(package), True)\n\ttarget_dir = normalizePath(target_dir)\n\tpackage = toPackage(target_dir)\n\tfile = getPath(\"join\", getPackageRootDir(), getPath(\"join\", packageAsDirectory(package), className + \".java\"))\n\treturn {\"file\": file, \"package\": package, \"class\": className, \"relative\": relative}\n\n\ndef getFileContents(classType, info):\n\tdata = getSnippet(classType)\n\tif data is None:\n\t\tsublime.error_message(\"Snippet \\\"\" + classType + \"\\\" is not found\")\n\t\treturn None\n\tif info[\"package\"] != \"\":\n\t\tdata = data.replace(\"%package%\", \"package \" + info[\"package\"] + \";\")\n\telse:\n\t\tdata = data.replace(\"%package%\", \"\")\n\n\tdata = data.replace(\"%class%\", info[\"class\"])\n\tdata = data.replace(\"%file%\", info[\"file\"])\n\tdata = data.replace(\"%file_name%\", getPath(\"name\", info[\"file\"]))\n\tdata = data.replace(\"%package_path%\", getCurrentPackage())\n\treturn data\n\n\ndef insertAndSave(view, contents):\n\tview.run_command(\"insert_snippet\", {\"contents\": contents})\n\tview.run_command(\"save\")\n\n\ndef createClassFile(file, contents, msg):\n\tif contents is None:\n\t\treturn\n\tif os.path.exists(file):\n\t\tsublime.error_message(msg)\n\t\treturn\n\topen(file, \"w\")\n\tview = sublime.active_window().open_file(file)\n\tview.set_syntax_file(\"Packages/Java/Java.tmLanguage\")\n\tsublime.set_timeout(lambda: insertAndSave(view, contents), 100)\n\n\nclass JavatarCreateCommand(sublime_plugin.WindowCommand):\n\tdef run(self, text=\"\", type=\"\"):\n\t\tgetAction().addAction(\"javatar.command.create.run\", \"Create [type=\" + type + \"]\")\n\t\tif type != \"\":\n\t\t\tself.showInput(-1, type)\n\t\t\treturn\n\t\tif text != \"\":\n\t\t\tinfo = getInfo(text)\n\t\t\tgetAction().addAction(\"javatar.command.create.run\", \"Create [info=\" + str(info) + \"]\")\n\t\t\tcreateClassFile(info[\"file\"], getFileContents(self.type, info), self.type + \"\\\"\" + info[\"class\"] + \"\\\" already exists\")\n\t\t\tsublime.set_timeout(lambda: showStatus(self.type + \" \\\"\" + info[\"class\"] + \"\\\" is created within package \\\"\" + toReadablePackage(info[\"package\"], True) + \"\\\"\"), 500)\n\n\tdef showInput(self, index, type=\"\"):\n\t\tif type != \"\" or index >= 0:\n\t\t\tif type != \"\":\n\t\t\t\tself.type = type\n\t\t\telse:\n\t\t\t\tself.type = getSnippetName(index)\n\t\t\tsublime.active_window().show_input_panel(self.type + \" Name:\", \"\", self.run, \"\", \"\")\n","sub_path":"commands/javatar_class.py","file_name":"javatar_class.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"160517080","text":"import re\nimport collections\n\n\ndef get_nums(file,patt):\n cpatt=re.compile(patt)\n counter=collections.Counter()\n with open(file) as fobj:\n for item in fobj:\n p=cpatt.search(item)\n if p:\n counter.update([p.group()])\n # counter.most_common(3)\n return counter\n\ndef main():\n file='/opt/ktz/py02/2019071012.log'\n ip='(\\d+.){3}\\d+'\n result=get_nums(file,ip)\n # result=result.most_common(3)\n br_patt = \"Firefox|MSIE|Chrome\"\n brs=get_nums(file,br_patt)\n for item in brs:\n print(item,brs[item])\n for item in result:\n print(item,result[item])\n\n\n\nif __name__ == '__main__':\n main()\n # os , sys , subprocess , getpass , string , time , datetime , shutil , functools , re , collections , random","sub_path":"ktz/py02/d3weblog.py","file_name":"d3weblog.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"548522063","text":"import time\nimport enum\nfrom datetime import datetime\nimport image_processing.image_sleep as image_sleep\nimport dataCenter\n\nclass status(enum.Enum):\n standing = 0\n lying = 1\n falldown = 2\n \nglobal blue_color, red_color, green_color\nblue_color = (255,0,0)\nred_color = (0,0,255)\ngreen_color = (0,255,0)\n\nglobal standingTime, lyingTime, falldownTime\nstandingTime = time.time()\nlyingTime = time.time()\nfalldownTime = time.time()\n\nglobal hasPrinted\nhasPrinted = False\n\nglobal sleeptime, sleep_check, wake_check\nsleeptime = 0\nsleep_check = 0\nwake_check = 0\n\nglobal flag, userHeight, beforeH\nflag = False\nuserHeight = 163\nbeforeH = 1\n\nglobal realFallDown\nrealFallDown = False\n\ndef status_detected(status):\n global blue_color, red_color, green_color\n global standingTime, lyingTime, falldownTime\n global realFallDown\n nowStatus = status.standing\n color = blue_color\n if status == status.standing: # standing\n standingTime = time.time()\n nowStatus = status.standing\n color = blue_color\n elif status == status.lying: # lying\n lyingTime = time.time()\n nowStatus = status.lying\n color = green_color\n realFallDown = False\n elif status == status.falldown: # falldown\n falldownTime = time.time()\n nowStatus = status.falldown\n color = red_color\n realFallDown = False\n return nowStatus, color\n\ndef standing_process(beforeStatus, personPoint):\n global flag, beforeH\n global sleeptime, wake_check\n nowStatus, color = status_detected(status.standing)\n\n standingMinX = personPoint[0]\n standingMaxX = personPoint[1]\n standingMinY = personPoint[2]\n standingMaxY = personPoint[3]\n beforeH = standingMaxY - standingMinY\n flag = False\n\n if sleeptime >= 60:\n wake_check = image_sleep.day_wake_time(wake_check, sleeptime)\n sleeptime = 0\n\n standingPoint = [standingMinX, standingMaxX, standingMinY, standingMaxY]\n return nowStatus, color, standingPoint\n\ndef lying_process(beforeStatus, personPoint, standingPoint):\n global sleeptime, sleep_check\n nowStatus, color = status_detected(status.lying)\n\n lyingMinX = personPoint[0]\n lyingMaxX = personPoint[1]\n lyingMinY = personPoint[2]\n lyingMaxY = personPoint[3]\n\n centerPointX = int((lyingMinX + lyingMaxX)/2)\n centerPointY = int((lyingMinY + lyingMaxY)/2)\n\n standingMinX = standingPoint[0]\n standingMaxX = standingPoint[1]\n standingMinY = standingPoint[2]\n standingMaxY = standingPoint[3]\n\n # calculate head point\n headPointX = lyingMinX if abs(lyingMaxX - standingMaxX) < abs(lyingMinX - standingMinX) else lyingMaxX\n headPointY = centerPointY\n\n # calculate sleeping time\n sleeptime = sleeptime+1\n print(sleeptime)\n if sleeptime >= 10:\n sleep_check = image_sleep.day_sleep_time(sleep_check)\n headPoint = [headPointX, headPointY]\n return nowStatus, color, headPoint\n\ndef falldown_process(beforeStatus, personPoint, standingPoint, beforeCenterPoint):\n global flag, userHeight, beforeH\n global realFallDown\n global standingTime\n\n fallMinX = personPoint[0]\n fallMaxX = personPoint[1]\n fallMinY = personPoint[2]\n fallMaxY = personPoint[3]\n\n standingMinX = standingPoint[0]\n standingMaxX = standingPoint[1]\n standingMinY = standingPoint[2]\n standingMaxY = standingPoint[3]\n\n centerPointX = int((fallMinX + fallMaxX)/2)\n centerPointY = int((fallMinY + fallMaxY)/2)\n\n # calculate head point\n headPointX = centerPointX # CenterPointX\n headPointY = personPoint[2] # fallMinY\n\n now_time = time.time()\n diff_time = now_time - standingTime\n if diff_time <= 1:\n nowStatus, color, headPoint = status_detected(status.falldown)\n\n beforeCenterPointX = beforeCenterPoint[0]\n beforeCenterPointY = beforeCenterPoint[1] \n\n # calculate head point\n headPointX = fallMinX if abs(fallMaxX - standingMaxX) < abs(fallMinX - standingMinX) else fallMaxX\n headPointY = centerPointY\n # footPointX = fallMinX if headPointX == fallMaxX else fallMaxX\n # footPointY = centerPointY\n\n distance = math.sqrt( (beforeCenterPointX - headPointX)**2 + (standingMinY - headPointY)**2 ) # calculate distance\n realDist = userHeight * distance / beforeH # calculate real distance based user height\n if (time.time() - standingTime) != 0:\n v = realDist / (time.time() - standingTime) # calculate speed\n if flag is False:\n print(str(nowStatus)[7:])\n print(v/100)\n #print(\"HP : {},{}\".format(HeadPointX,HeadPointY))\n #print(\"CP : {},{}\".format(CenterPointX,CenterPointY))\n # request for falldown \n data = {'user_id' : dataCenter.user_id, 'sensor_id': dataCenter.fall_down, 'num' : v, 'day': 'sunday'}\n requests.post(dataCenter.URL, json=data)\n flag = True\n realFallDown = True\n print(\"fall down 111\")\n elif beforeStatus == status.falldown and realFallDown is True:\n if diff_time >= 5 and diff_time < 10:\n nowStatus, color = status_detected(status.falldown)\n if hasPrinted == False:\n print(\"fall down 222\")\n hasPrinted2 = True\n elif diff_time >= 10:\n nowStatus, color = status_detected(status.falldown)\n print(\"fall down 333\")\n else: # lying\n nowStatus, color, headPoint = lying_process(beforeStatus, personPoint, standingPoint)\n\n beforeCenterPointX = beforeCenterPoint[0]\n beforeCenterPointY = beforeCenterPoint[1]\n\n # calculate head point\n headPointX = fallMinX if abs(fallMaxX - standingMaxX) < abs(fallMinX - standingMinX) else fallMaxX\n headPointY = centerPointY\n # footPointX = fallMinX if headPointX == fallMaxX else fallMaxX\n # footPointY = centerPointY\n\n distance = math.sqrt( (beforeCenterPointX - headPointX)**2 + (standingMinY - headPointY)**2 )\n realDist = userHeight * distance / beforeH\n if (time.time() - standingTime) != 0:\n v = realDist / (time.time() - standingTime)\n if flag is False:\n print(str(nowStatus)[7:])\n print(v/100)\n #print(\"HP : {},{}\".format(HeadPointX,HeadPointY))\n #print(\"CP : {},{}\".format(CenterPointX,CenterPointY))\n flag = True\n headPoint = [headPointX, headPointY]\n return nowStatus, color, headPoint\n\n","sub_path":"robot109/image_processing/image_falldown.py","file_name":"image_falldown.py","file_ext":"py","file_size_in_byte":6521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"373000303","text":"from typing import Optional, Set\n\nfrom helpers.graph_classes.graph_node import GraphNode\nfrom helpers.testing.graph_search_tester import GraphSearchTester\n\n\ndef depth_first_search(\n root: Optional[GraphNode],\n identifier: int,\n visited: Optional[Set[GraphNode]] = None\n) -> Optional[GraphNode]:\n if root is None or root.get_id() == identifier:\n return root\n\n if visited is None:\n visited = set()\n\n visited.add(root)\n\n n = None\n\n for child in root.get_children():\n if child not in visited:\n n = depth_first_search(\n child, identifier, visited\n )\n\n if n is not None:\n break\n\n return n\n\n\nGraphSearchTester(depth_first_search)\n","sub_path":"python/dailies/1_nov_22/dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"181997736","text":"# -*- coding: utf-8 -*-\n\n# \"THE BARBECUE-WARE LICENSE\" (Revision 1):\n#\n# wrote this file. As long as you retain this notice you\n# can do whatever you want with this stuff. If we meet some day, and you think\n# this stuff is worth it, you can make me a brazilian barbecue, including beers\n# and caipirinha in return to Paulo Leonardo Benatto.\n#\n# The quality of the barbecue depends on the amount of beer that has been\n# purchased.\n\n\nimport os\n\nimport lxc\n\nfrom . import utils\n\n\n__all__ = ['pocker_create', 'pocker_start', 'pocker_list', 'pocker_stop',\n 'pocker_console', 'pocker_destroy']\n\nMIN_REQUIRED_FREE_SPACE = 1\n\nPOCKER_CONTAINER_PATH = os.environ.get('POCKER_CONTAINER_PATH',\n '/var/lib/lxc/')\n\nDEFAULT_CONTAINER = {\n \"arch\": \"amd64\",\n \"dist\": \"ubuntu\",\n \"release\": \"trusty\"\n}\n\n\ndef _fix_path(cname):\n\n if POCKER_CONTAINER_PATH[-1] != '/':\n path = POCKER_CONTAINER_PATH + '/' + cname\n else:\n path = POCKER_CONTAINER_PATH + cname\n\n return path\n\n\ndef has_container(cname):\n \"\"\"Verify if the container exists.\"\"\"\n\n return os.path.isdir(_fix_path(cname))\n\n\ndef _has_freespace():\n \"\"\"Check free disk space. \"\"\"\n\n st = os.statvfs('/')\n freespace = ((st.f_bsize * st.f_bavail)/(1024 * 1024 * 1024))\n\n return freespace > MIN_REQUIRED_FREE_SPACE\n\n\n@utils.superuser\ndef pocker_create(cname, options=DEFAULT_CONTAINER):\n \"\"\"Creating a new container.\n\n Args:\n cname (str): Container name.\n options (dict of str: str): Container options.\n\n Returns:\n bool: True if successful, False otherwise.\n\n \"\"\"\n\n if not _has_freespace():\n print(\"%s[ERROR]%s No space left.\" % (utils.RED, utils.NORMAL))\n return False\n\n if has_container(cname):\n print(\"%s[ERROR]%s Container exist, try to start it.\" %\n (utils.RED, utils.NORMAL))\n return False\n\n print (\"%s[OK]%s Creating container: %s...\" %\n (utils.GREEN, utils.NORMAL, cname))\n\n container = lxc.Container(cname)\n #if container.create(\"download\", 0, options):\n if container.create(\"ubuntu\"):\n print (\"%s[OK]%s Container %s created.\" %\n (utils.GREEN, utils.NORMAL, cname))\n else:\n print (\"%s[ERRO]%s Container %s not created.\" %\n (utils.RED, utils.NORMAL, cname))\n\n\ndef _is_pocker_running(cname):\n\n if not has_container(cname):\n print (\"%s[ERRO]%s Container does not exist.\" %\n (utils.RED, utils.NORMAL))\n return False\n\n if pocker_status(cname) != \"RUNNING\":\n return False\n\n return True\n\n\ndef pocker_status(cname):\n \"\"\" Container Status.\n\n Args:\n cname (str): Container name.\n\n Return:\n str: Container status.\n\n \"\"\"\n\n if not has_container(cname):\n print (\"%s[ERRO]%s Container does not exist.\" %\n (utils.RED, utils.NORMAL))\n return False\n\n return lxc.Container(cname).state\n\n\n@utils.superuser\ndef pocker_destroy(cname):\n \"\"\" Destroy the conainter.\n\n Args:\n cname (str): Container name.\n\n Returns:\n bool: True if successful, False otherwise.\n\n \"\"\"\n\n if not has_container(cname):\n print (\"%s[ERRO]%s Container does not exist.\" %\n (utils.RED, utils.NORMAL))\n return False\n\n if _is_pocker_running(cname):\n print (\"%s[ERRO]%s Pocker is RUNNING, stop it first.\" %\n (utils.RED, utils.NORMAL))\n return False\n\n if lxc.Container(cname).destroy():\n print (\"%s[OK]%s Booowwwwww!!!.\" % (utils.GREEN, utils.NORMAL))\n else:\n print (\"%s[ERRO]%s Container is indestructible.\" %\n (utils.RED, utils.NORMAL))\n\n\n@utils.superuser\ndef pocker_start(cname):\n \"\"\"Start the conainter.\n\n Args:\n cname (str): Container name.\n\n Returns:\n bool: True if successful, False otherwise.\n\n \"\"\"\n\n if not has_container(cname):\n print(\"%s[ERRO]%s Container does not exist.\" % (utils.RED, utils.NORMAL))\n return False\n\n if _is_pocker_running(cname):\n print(\"%s[ERRO]%s Pocker is RUNNING.\" %\n (utils.RED, utils.NORMAL))\n return False\n\n cont = lxc.Container(cname)\n if cont.start():\n print(\"%s[OK]%s Container started.\" % (utils.GREEN, utils.NORMAL))\n return True\n \n print (\"%s[ERROR]%s Container not started.\" % (utils.RED, utils.NORMAL))\n\n return False\n\n\n@utils.superuser\ndef pocker_stop(cname):\n \"\"\"Stop the conainter.\n\n Args:\n cname (str): Container name.\n\n Returns:\n bool: True if successful, False otherwise.\n\n \"\"\"\n\n if not has_container(cname):\n print(\"%s[ERRO]%s Container does not exist.\" % (utils.RED, utils.NORMAL))\n return False\n\n if not _is_pocker_running(cname):\n print(\"%s[ERRO]%s Pocker is not RUNNING.\" %\n (utils.RED, utils.NORMAL))\n return False\n\n cont = lxc.Container(cname)\n if cont.stop():\n print(\"%s[OK]%s Container stopped.\" % (utils.GREEN, utils.NORMAL))\n return True\n \n print (\"%s[ERROR]%s Container not stopped.\" % (utils.RED, utils.NORMAL))\n\n return False\n\n\ndef pocker_list():\n \"\"\"List all conainters.\n \"\"\"\n\n print (\"%s NAME \\t STATUS %s\" % (utils.CYAN, utils.NORMAL))\n dirs = os.listdir(POCKER_CONTAINER_PATH)\n for container in dirs:\n print (\" %s \\t %s\" % (container, pocker_status(container)))\n\n\ndef pocker_console(cname):\n \"\"\"Open a console to the conainter.\n\n Args:\n cname (str): Container name.\n\n Returns:\n bool: True if successful, False otherwise.\n\n \"\"\"\n\n if not has_container(cname):\n print(\"%s[ERRO]%s Container does not exist.\" % (utils.RED, utils.NORMAL))\n return False\n\n if not _is_pocker_running(cname):\n print(\"%s[ERRO]%s Pocker is not RUNNING.\" %\n (utils.RED, utils.NORMAL))\n return False\n\n cont = lxc.Container(cname)\n if cont.console():\n print(\"%s[OK]%s Container console.\" % (utils.GREEN, utils.NORMAL))\n return True\n \n print (\"%s[ERROR]%s Error openning a console.\" % (utils.RED, utils.NORMAL))\n\n return False\n\n\nif __name__ == \"__main__\":\n print(\"This module isn't intended to be run directly.\")\n","sub_path":"pocker/pocker.py","file_name":"pocker.py","file_ext":"py","file_size_in_byte":6235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"406413099","text":"from mmimproc.qt1.naming import qt1filepath\nfrom copy import copy\nimport nibabel, numpy\n\n\ndef matchImages(images, query):\n return [i for i in images if set(query.items()).issubset(set(i.items()))]\n\ndef createSpgrTseirCorrespondenceImages(t1images, projectdir):\n provenance = ProvenanceWrapper()\n spgrQuery = {'method':'orig_spgr_mag', 'b1corr':True}\n spgrImages = matchImages(t1images, spgrQuery)\n for i, spgrImage in enumerate(spgrImages):\n msg = 'Creating SPGR / TSEIR corresp image {0} of {1}'\n print(msg.format(i+1, len(spgrImages)))\n tseirQuery = {'date': spgrImage['date'], 'method':'tseir_mag', \n 'b1corr':False}\n tseirImages = matchImages(t1images, tseirQuery)\n assert len(tseirImages) == 1\n tseirImage = tseirImages[0]\n correspImage = copy(spgrImage)\n correspImage['method'] = 'spgrbytseir'\n spgr = qt1filepath(spgrImage, projectdir, 'BIDS')\n tseir = qt1filepath(tseirImage, projectdir, 'BIDS')\n versus = qt1filepath(correspImage, projectdir, 'BIDS')\n spgrImg = nibabel.load(spgr)\n tseirImg = nibabel.load(tseir)\n correspondence = spgrImg.get_data()/tseirImg.get_data()\n ## get rid of divide-by-zero nans\n correspondence = numpy.nan_to_num(correspondence)\n newImg = nibabel.Nifti1Image(correspondence, spgrImg.get_affine())\n nibabel.save(newImg, versus)\n provenance.log(versus, 'SPGR vs TSEIR ratio', [spgr, tseir])\n t1images.append(correspImage)\n\n\n\n\n\n\n\n\n\n","sub_path":"mmimproc/qt1/correspondence_phantoms.py","file_name":"correspondence_phantoms.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"217522150","text":"import atexit\nimport collections\nimport logging\nimport os\nimport threading\nimport time\nimport datetime\nimport multiprocessing\n\ntry:\n import ujson as json\nexcept:\n import json\nimport pyjq\nfrom kafka import KafkaConsumer, KafkaProducer\n\nfrom .trigger import Functions\n\n\nlogging.basicConfig(level=logging.DEBUG)\nlog = logging.getLogger(__name__)\n\n\n#class OpenFaasKafkaConsumer(threading.Thread):\nclass OpenFaasKafkaConsumer(multiprocessing.Process):\n def __init__(self, thread_id, config, functions, topic_name, partition_no):\n #threading.Thread.__init__(self)\n multiprocessing.Process.__init__(self)\n #self.setDaemon(True)\n self.thread_id = thread_id\n # instantiate functions\n self.functions = Functions(name='kafka')\n self.functions.refresh_interval=10\n self.topic_name = topic_name\n self.partition_no = partition_no\n # Reset the config \n self.config = {\n 'bootstrap.servers': os.getenv('KAFKA_BOOTSTRAP_SERVERS', 'kafka:9092'),\n 'group.id': 'group' + topic_name,\n 'auto.offset.reset': os.getenv('AUTO_OFFSET_RESET', 'latest'),\n 'auto.commit.interval.ms': os.getenv('AUTO_COMMIT_INTERVAL_MS', 5000),\n 'fetch.wait.max.ms': os.getenv('FETCH_MAX_WAIT_MS', 10)\n }\n # fetch.wait.max.ms: maximum amount of time in milliseconds the server will block before answering the fetch request\n # if there isn’t sufficient data to immediately satisfy the requirement given by fetch_min_bytes (default:1 byte)\n # auto.offset.reset: A policy for resetting offsets on OffsetOutOfRange errors: ‘earliest’ will move to the oldest available message,\n # ‘latest’ will move to the most recent.\n \n log.debug('Instantiating thread: ' + self.thread_id)\n log.info('Instantiating thread: ' + self.thread_id)\n \n def function_data(self, function, topic, key, value):\n data_opt = self.functions.arguments(function).get('data', 'key')\n\n if data_opt == 'key-value':\n return json.dumps({'key': key, 'value': value})\n else:\n return key\n \n def run(self):\n consumer = KafkaConsumer(str(self.topic_name), bootstrap_servers=self.config['bootstrap.servers'],\n auto_offset_reset=self.config['auto.offset.reset'],\n fetch_max_wait_ms=int(self.config['fetch.wait.max.ms']), # must be set to a low value\n group_id=self.config['group.id'])\n \n log.debug('bootstrap_servers: ' + self.config['bootstrap.servers'] + ' auto_offset_reset: ' + self.config['auto.offset.reset'])\n log.debug('fetch_max_wait_ms: ' + str(self.config['fetch.wait.max.ms']) + ' group_id: ' + self.config['group.id'])\n # if we want to manually assign parition to a consume, enable this line\n #consumer.assign([TopicPartition(self.topic_name, self.partition_no)])\n #consumer.subscribe([str(self.topic_name)])\n \n log.debug('Executing a consumer with ID: ' + self.thread_id)\n log.info('Executing a consumer with ID: ' + self.thread_id)\n \n callbacks = collections.defaultdict(list)\n functions = self.functions\n\n def close():\n log.info('Closing consumer in thread: ' + self.thread_id)\n consumer.close()\n atexit.register(close)\n \n poll_time_out = int(os.getenv('POLL_TIME_OUT', 1000)) # milliseconds spent waiting in poll if data is not available in the buffer\n poll_max_records = int(os.getenv('MAX_POLL_RECORDS', 10000)) # maximum number of records returned in a single call to poll()\n \n while True:\n add, update, remove = functions.refresh()\n if add or remove:\n for f in add:\n if f not in callbacks[self.topic_name]:\n callbacks[self.topic_name].append(f)\n \n for f in remove:\n if f in callbacks[self.topic_name]:\n callbacks[self.topic_name].remove(f)\n\n \n consumer.poll(timeout_ms=poll_time_out, max_records=poll_max_records)\n \n for message in consumer:\n log.debug('Processing a message in thread: ' + self.thread_id)\n\n if not message:\n log.debug('Empty message received')\n pass\n else:\n topic, key, value = message.topic, \\\n message.key, \\\n message.value\n\n\n log.debug('Processing topic: ' + str(topic) + ' : in thread: ' + self.thread_id)\n try:\n key = message.key.decode('utf-8')\n log.debug('Processing Key: ' + str(key) + ' : in thread: ' + self.thread_id)\n except:\n log.debug('Key could not be decoded in thread: ' + self.thread_id )\n pass\n try:\n value = json.loads(value)\n log.debug('Processing value: ' + str(value) + ' : in thread: ' + self.thread_id)\n except:\n log.debug('Value could not be decoded in thread: ' + self.thread_id )\n pass\n\n\n for function in callbacks[topic]:\n jq_filter = functions.arguments(function).get('filter')\n try:\n if jq_filter and not pyjq.first(jq_filter, value):\n continue\n except:\n log.error(f'Could not filter message value with {jq_filter}')\n\n data = self.function_data(function, topic, key, value)\n log.debug('In thread:' + self.thread_id + ' : Function: ' + f'/function/{function[\"name\"]}' + ' Data:' + data )\n #log.info('In thread:' + self.thread_id + ' : Function: ' + f'/function/{function[\"name\"]}' + ' Data:' + data )\n\n functions.gateway.post(functions._gateway_base + f'/function/{function[\"name\"]}', data=data)\n\nclass KafkaTrigger(object):\n\n def __init__(self, label='ftrigger', name='kafka', refresh_interval=5,\n kafka='kafka:9092'):\n self.functions = Functions(name='kafka')\n self.functions.refresh_interval=10\n self.config = {\n 'bootstrap.servers': os.getenv('KAFKA_BOOTSTRAP_SERVERS', 'kafka:9092'),\n 'group.id': 'ConsumerGroup',\n 'auto.offset.reset': os.getenv('AUTO_OFFSET_RESET', 'latest'),\n 'auto.commit.interval.ms': os.getenv('AUTO_COMMIT_INTERVAL_MS', 5000),\n 'fetch.wait.max.ms': os.getenv('FETCH_MAX_WAIT_MS', 10)\n }\n \n def run(self):\n \n topic_list_with_consumers = []\n no_of_paritions = os.getenv('NUMBER_OF_CONSUMERS_PER_TOPIC', 5)\n no_of_paritions = int(no_of_paritions) \n log.debug('Number of Consumers:' + str(no_of_paritions)) \n\n callbacks = collections.defaultdict(list)\n functions = self.functions\n \n \n while True:\n add, update, remove = functions.refresh()\n existing_topics = set(callbacks.keys())\n new_candidate_topics = []\n consumer_threads = []\n \n for topic in existing_topics:\n if topic not in topic_list_with_consumers:\n new_candidate_topics.append(topic)\n \n # if new functions added\n if add:\n for f in add:\n if functions.arguments(f).get('topic') not in topic_list_with_consumers:\n new_candidate_topics.append(functions.arguments(f).get('topic'))\n \n new_candidate_topics = set(new_candidate_topics)\n for topic_name in new_candidate_topics:\n for partition_no in range(no_of_paritions): \n con_thread = OpenFaasKafkaConsumer(topic_name + '-' + str(partition_no), self.config, self.functions, topic_name, partition_no)\n consumer_threads.append(con_thread)\n \n topic_list_with_consumers.append(topic_name)\n print(topic_list_with_consumers)\n \n \n \n for t in consumer_threads:\n t.start()\n\ndef main():\n trigger = KafkaTrigger()\n trigger.run()\n","sub_path":"ftrigger/kafka-python-working-back.py","file_name":"kafka-python-working-back.py","file_ext":"py","file_size_in_byte":8750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"461508762","text":"\nprint(\"How many dollars do you have?\")\ninput1 = input()\namount = float(input1)\n\n\n\nif amount > 100.0:\n print(\"You have a lot of money.\")\nelif amount > 5.0:\n print(\"You have a decent amount of money.\")\nelse:\n print(\"Your wallet is almost empty.\")\n\n\n\ninput(\"Press Enter to continue:\")\n\n","sub_path":"Lesson03/File04/File04-01.py","file_name":"File04-01.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"163375862","text":"\"\"\"\nexample.py: Provides an example script to run BLUES and\nbenchmark the run on a given platform\n\nAuthors: Samuel C. Gill\nContributors: Nathan M. Lim, David L. Mobley\n\n* Benchmarking related code adapted from:\nhttps://github.com/pandegroup/openmm/blob/master/examples/benchmark.py\n(Authors: Peter Eastman)\n\"\"\"\n\nfrom __future__ import print_function\nfrom blues.moves import RandomLigandRotationMove\nfrom blues.engine import MoveEngine\nfrom blues.moves import SideChainMove\nfrom blues import utils\nfrom blues.simulation import Simulation, SimulationFactory\nimport parmed\nfrom simtk import openmm\nfrom optparse import OptionParser\nimport mdtraj as md\nimport numpy as np\n\ndef runNCMC(platform_name, relaxstepsNC, themdsteps):\n #Define some options\n\n opt = { 'temperature' : 300.0, 'friction' : 1, 'dt' : 0.002,\n 'nIter' : 100, 'nstepsNC' : relaxstepsNC, 'nstepsMD' : themdsteps,\n 'nonbondedMethod' : 'PME', 'nonbondedCutoff': 10, 'constraints': 'HBonds',\n 'trajectory_interval' : 2, 'reporter_interval' : 2,\n 'platform' : platform_name,\n 'verbose' : False,\n 'write_ncmc' : 1\n }\n\n #Generate the ParmEd Structure\n #prmtop = utils.get_data_filename('blues', 'tests/data/eqToluene.prmtop')#\n #inpcrd = utils.get_data_filename('blues', 'tests/data/eqToluene.inpcrd')\n prmtop = '/home/burleyk/projects/sidechain/inputs/watDivaline.prmtop'\n inpcrd = '/home/burleyk/projects/sidechain/inputs/watDivaline.inpcrd'\n struct = parmed.load_file(prmtop, xyz=inpcrd)\n\n #Define the 'model' object we are perturbing here.\n # Calculate particle masses of object to be moved\n\n ligand = SideChainMove(struct, [1])\n\n ligand.atom_indices = ligand.rot_bond_atoms\n # Initialize object that proposes moves.\n ligand_mover = MoveEngine(ligand)\n\n # Generate the MD, NCMC, ALCHEMICAL Simulation objects\n simulations = SimulationFactory(struct, ligand_mover, **opt)\n simulations.createSimulationSet()\n\n blues = Simulation(simulations, ligand_mover, **opt)\n #add the reporter here\n blues.md_sim.reporters.append(openmm.app.dcdreporter.DCDReporter('accept.dcd', 1000))\n blues.runNCMC()\n\n\nmdstep = 1000\nrepeats = [1]\ntheseNCsteps = [5000]\n\n\nfor relaxstepsNC in theseNCsteps:\n for repeat in repeats:\n print('Running blues with %i NC steps. \\nRepeat # %i: ' %(relaxstepsNC, repeat))\n '''runNCMC(platform_name, relaxstepsNC, mdstep):'''\n\n parser = OptionParser()\n parser.add_option('-f', '--force', action='store_true', default=False,\n help='run BLUES example without GPU platform')\n (options, args) = parser.parse_args()\n\n platformNames = [openmm.Platform.getPlatform(i).getName() for i in range(openmm.Platform.getNumPlatforms())]\n\n if 'CUDA' in platformNames:\n runNCMC('CUDA', relaxstepsNC, mdstep)\n else:\n if options.force:\n runNCMC('CPU', relaxstepsNC, mdstep)\n else:\n print('WARNING: Could not find a valid CUDA/OpenCL platform. BLUES is not recommended on CPUs.')\n print(\"To run on CPU: 'python blues/example.py -f'\")\n\n di_dataFN = \"dihedrals%iNC_gp%i_MD1000step.txt\" %(relaxstepsNC, repeat)\n traj = md.load_dcd('accept.dcd', top = 'protein.pdb')\n indicies = np.array([[0, 4, 6, 8]])\n dihedraldata = md.compute_dihedrals(traj, indicies)\n datafile = open(di_dataFN,'w')\n for value in dihedraldata:\n datafile.write(\"%s\\n\" % str(value)[1:-1])\n\n datafile.close()\n\n di_dataFN2 = \"nonblues_dihedrals%iNC_gp%i_MD1000step.txt\" %(relaxstepsNC, repeat)\n traj2 = md.load_dcd('accept.dcd', top = 'protein.pdb')\n indicies2 = np.array([[18, 20, 22, 24]])\n dihedraldata2 = md.compute_dihedrals(traj2, indicies2)\n datafile2 = open(di_dataFN2,'w')\n for value in dihedraldata2:\n datafile2.write(\"%s\\n\" % str(value)[1:-1])\n\n datafile2.close()\n# script to pull out acceptance ratio\n","sub_path":"trsh_test.py","file_name":"trsh_test.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"132436699","text":"from cereal import car\nfrom common.realtime import DT_CTRL\nfrom selfdrive.car import apply_std_steer_torque_limits\nfrom selfdrive.car.hyundai.hyundaican import create_lkas11, create_clu11, create_lfahda_mfc\nfrom selfdrive.car.hyundai.values import Buttons, CarControllerParams, CAR\nfrom opendbc.can.packer import CANPacker\n\nVisualAlert = car.CarControl.HUDControl.VisualAlert\n\n\ndef process_hud_alert(enabled, fingerprint, visual_alert, left_lane,\n right_lane, left_lane_depart, right_lane_depart):\n sys_warning = (visual_alert == VisualAlert.steerRequired)\n\n # initialize to no line visible\n sys_state = 1\n if left_lane and right_lane or sys_warning: # HUD alert only display when LKAS status is active\n sys_state = 3 if enabled or sys_warning else 4\n elif left_lane:\n sys_state = 5\n elif right_lane:\n sys_state = 6\n\n # initialize to no warnings\n left_lane_warning = 0\n right_lane_warning = 0\n if left_lane_depart:\n left_lane_warning = 1 if fingerprint in [CAR.GENESIS_G90, CAR.GENESIS_G80] else 2\n if right_lane_depart:\n right_lane_warning = 1 if fingerprint in [CAR.GENESIS_G90, CAR.GENESIS_G80] else 2\n\n return sys_warning, sys_state, left_lane_warning, right_lane_warning\n\n\nclass CarController():\n def __init__(self, dbc_name, CP, VM):\n self.p = CarControllerParams(CP)\n self.packer = CANPacker(dbc_name)\n\n self.apply_steer_last = 0\n self.car_fingerprint = CP.carFingerprint\n self.steer_rate_limited = False\n self.last_resume_frame = 0\n\n def update(self, enabled, CS, frame, actuators, pcm_cancel_cmd, visual_alert,\n left_lane, right_lane, left_lane_depart, right_lane_depart):\n # Steering Torque\n new_steer = actuators.steer * self.p.STEER_MAX\n apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, self.p)\n self.steer_rate_limited = new_steer != apply_steer\n\n # disable if steer angle reach 90 deg, otherwise mdps fault in some models\n lkas_active = enabled and abs(CS.out.steeringAngleDeg) < CS.CP.maxSteeringAngleDeg\n\n # fix for Genesis hard fault at low speed\n if CS.out.vEgo < 16.7 and self.car_fingerprint == CAR.HYUNDAI_GENESIS:\n lkas_active = False\n\n if not lkas_active:\n apply_steer = 0\n\n self.apply_steer_last = apply_steer\n\n sys_warning, sys_state, left_lane_warning, right_lane_warning = \\\n process_hud_alert(enabled, self.car_fingerprint, visual_alert,\n left_lane, right_lane, left_lane_depart, right_lane_depart)\n\n can_sends = []\n can_sends.append(create_lkas11(self.packer, frame, self.car_fingerprint, apply_steer, lkas_active,\n CS.lkas11, sys_warning, sys_state, enabled,\n left_lane, right_lane,\n left_lane_warning, right_lane_warning))\n\n if pcm_cancel_cmd:\n can_sends.append(create_clu11(self.packer, frame, CS.clu11, Buttons.CANCEL))\n elif CS.out.cruiseState.standstill:\n # send resume at a max freq of 10Hz\n if (frame - self.last_resume_frame)*DT_CTRL > 0.1:\n # send 25 messages at a time to increases the likelihood of resume being accepted\n can_sends.extend([create_clu11(self.packer, frame, CS.clu11, Buttons.RES_ACCEL)] * 25)\n self.last_resume_frame = frame\n\n # 20 Hz LFA MFA message\n if frame % 5 == 0 and self.car_fingerprint in [CAR.SONATA, CAR.PALISADE, CAR.IONIQ, CAR.KIA_NIRO_EV, CAR.IONIQ_EV_2020]:\n can_sends.append(create_lfahda_mfc(self.packer, enabled))\n\n return can_sends\n","sub_path":"selfdrive/car/hyundai/carcontroller.py","file_name":"carcontroller.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"445689980","text":"import numpy as np\n\n\ndef energyband(k, n, m):\n # n refers to the model we want to use\n # m is the band in this model (0 is upper valence band, 1 is first cb and so on)\n # k is the vector at this point\n\n # Output is: Energy in this k-point at the m'th band in the n model.\n\n if n == 0: # This is from Prb 99 064302\n\n E_band = np.zeros(k.shape[0])\n # print(k[0])\n if m == 0: # Valence band\n alphax = np.array([-0.0928, 0.0705, 0.0200, -0.0012, 0.0029, 0.0006])\n alphay = np.array([-0.0307, 0.0307])\n alphaz = np.array([-0.0059, 0.0059])\n a = np.array([5.32, 6.14, 9.38])\n\n E_band[0] = (alphax[0] + alphax[1] * np.cos(k[0] * a[0]) + alphax[2] *\n np.cos(2 * k[0] * a[0]) + alphax[3] * np.cos(3 * k[0] * a[0]) + alphax[4] *\n np.cos(4 * k[0] * a[0]) + alphax[5] * np.cos(5 * k[0] * a[0]))\n E_band[1] = alphay[0] + alphay[1] * np.cos(k[1] * a[1])\n E_band[2] = alphaz[0] + alphaz[1] * np.cos(k[2] * a[2])\n E_band = np.sum(E_band)\n\n\n elif m == 1: # Conduction band\n alphax = np.array([0.0898, -0.0814, -0.0024, -0.0048, -0.0003, -0.0009])\n alphay = np.array([0.1114, -0.1114])\n alphaz = np.array([0.0435, -0.0435])\n a = np.array([5.32, 6.14, 9.38])\n E_band[0] = (0.1213 + alphax[0] + alphax[1] * np.cos(k[0] * a[0]) + alphax[2] *\n np.cos(2 * k[0] * a[0]) + alphax[3] * np.cos(3 * k[0] * a[0]) + alphax[4] *\n np.cos(4 * k[0] * a[0]) + alphax[5] * np.cos(5 * k[0] * a[0]))\n E_band[1] = alphay[0] + alphay[1] * np.cos(k[1] * a[1])\n E_band[2] = alphaz[0] + alphaz[1] * np.cos(k[2] * a[2])\n E_band = np.sum(E_band)\n\n elif n == 1: # This is for ZnO according to PRB 99 014304 (taken from Mads)\n if m == 0: # Valence band\n # Constants in atomic units\n t = 2.38\n tp = -0.0020\n u = 27.1\n p = -7.406\n q = 4.0\n a0z = -0.0059\n a1z = 0.0059\n ax = 5.32\n ay = 6.14\n az = 9.83\n\n # Geometry\n kx = k[0]\n ky = k[1]\n kz = k[2]\n\n def f(kx, ky):\n return (2 * np.cos(np.sqrt(3) * ky * ay) + 4 * np.cos(np.sqrt(3) / 2 * ky * ay)\n * np.cos(np.sqrt(3) * kx * ax))\n\n # Energy\n E_bandxy = (t * np.sqrt(f(kx, ky) + q) + tp * f(kx, ky) + p) / u\n E_bandz = a0z + a1z * np.cos(kz * az)\n E_band = E_bandxy\n\n\n elif m == 1: # Conduction band\n t = -2.38\n tp = -0.0020\n u = 27.1\n p = 10.670\n q = 3.3\n a0z = -0.0435\n a1z = 0.0435\n ax = 5.32\n ay = 6.14\n az = 9.83\n\n # Geometry\n kx = k[0]\n ky = k[1]\n kz = k[2]\n\n def f(kx, ky):\n return (2 * np.cos(np.sqrt(3) * ky * ay) + 4 * np.cos(np.sqrt(3) / 2 * ky * ay)\n * np.cos(np.sqrt(3) * kx * ax))\n\n # Energy\n E_bandxy = (t * np.sqrt(f(kx, ky) + q) + tp * f(kx, ky) + p) / u\n E_bandz = a0z + a1z * np.cos(kz * az)\n E_band = E_bandxy\n\n return E_band ## Why do we sum with 2 here?\n","sub_path":"energyband.py","file_name":"energyband.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"286134395","text":"import datetime\n\n\nCHECKMARK = \"fas fa-check-square\"\nRED_X = \"❌\"\n\n\nclass Table:\n def __init__(self, name, ts):\n self.name = name\n self.ts = ts\n\n # compare ts of the table vs today\n if ts < datetime.date.today().strftime(\"%Y-%m-%d 00:00:00\"):\n # table was not updated today\n self.good_to_go = False\n else:\n self.good_to_go = True\n\n\nclass Workflow:\n def __init__(self, name, updated_tf):\n self.name = name\n # updated_tf comes through as a string from redcap, convert too bool\n if updated_tf == \"True\":\n self.good_to_go = True\n else:\n self.good_to_go = False\n","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"142503519","text":"#!/usr/bin/python\n\n# NB python 3\n#https://docs.python.org/3/library/http.server.html\n\nimport http.server\nimport socketserver\n\nPORT = 6789\n\nHandler = http.server.SimpleHTTPRequestHandler\n\nwith socketserver.TCPServer((\"\", PORT), Handler) as httpd:\n print(\"Python : serving at port\", PORT)\n httpd.serve_forever()\n","sub_path":"local_repo/httpserv.py","file_name":"httpserv.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"209454884","text":"from __future__ import annotations\nimport copy\nimport sys\nimport time\nimport typing as t\n\n\nclass VectorClock:\n def __init__(self):\n self.clock: t.Dict[t.Any, int] = {}\n\n def update(self, node, counter: int) -> VectorClock:\n if node in self.clock and counter <= self.clock[node]:\n raise Exception(f'Node {node} has gone backwards from {self.clock[node]} to {counter}')\n self.clock[node] = counter\n return self\n\n def __str__(self):\n return '{0}'.format(', '.join(['{0}:{1}'.format(node, self.clock[node])\n for node in sorted(self.clock.keys())]))\n\n def __eq__(self, other):\n return self.clock == other.clock\n\n def __lt__(self, other):\n for node in self.clock:\n if node not in other.clock:\n return False\n elif self.clock[node] > other.clock[node]:\n return False\n return True\n\n def __ne__(self, other):\n return not (self == other)\n\n def __le__(self, other):\n return (self == other) or (self < other)\n\n def __gt__(self, other):\n return (other < self)\n\n def __ge__(self, other):\n return (self == other) or (self > other)\n\n def __key(self):\n return tuple(sorted(self.clock.items()))\n\n def __hash__(self):\n return hash(self.__key())\n\n @classmethod\n def coalesce(cls, vcs: t.List[VectorClock]) -> t.List[VectorClock]:\n results = []\n for vc in vcs:\n subsumed = False\n for i, result in enumerate(results):\n if vc <= result:\n subsumed = True\n break\n if result < vc:\n results[i] = copy.deepcopy(vc)\n subsumed = True\n break\n if not subsumed:\n results.append(copy.deepcopy(vc))\n return results\n\n @classmethod\n def coverage(cls, vcs: t.List[VectorClock]) -> VectorClock:\n result = cls()\n for vc in vcs:\n if vc is None:\n continue\n for node, counter in vc.clock.items():\n if node in result.clock:\n if result.clock[node] < counter:\n result.clock[node] = counter\n else:\n result.clock[node] = counter\n return result\n\n\nclass VectorClockTimestamp(VectorClock):\n NODE_LIMIT = 10\n\n def __init__(self):\n super(VectorClockTimestamp, self).__init__()\n self.clock_time = {}\n\n def _maybe_truncate(self):\n if len(self.clock_time) < VectorClockTimestamp.NODE_LIMIT:\n return\n\n oldest_node = None\n oldest_time = sys.maxint\n for node, when in self.clock_time.items():\n if when < oldest_time:\n oldest_node = node\n oldest_time = when\n del self.clock_time[oldest_node]\n del self.clock[oldest_node]\n\n def update(self, node, counter: int) -> VectorClockTimestamp:\n VectorClock.update(self, node, counter)\n self.clock_time[node] = time.time()\n self._maybe_truncate()\n return self\n\n","sub_path":"url_shortener/src/dynamo/vectorclock.py","file_name":"vectorclock.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"238212008","text":"import json\nfrom collections import defaultdict\nimport logging\n\nfrom six import string_types\n\nimport networkx as nx\nimport numpy as np\n\nfrom catpy.client import CatmaidClientApplication, make_url, CoordinateTransformer\nfrom catpy.export import ExportWidget\n\nfrom skeleton_synapses.dto import NodeInfo\n\nNEUROCEAN_CONSTANTS = {\n 'skel_id': 11524047,\n 'project_id': 1,\n 'image_stack_id': 1\n}\n\nDEV_CONSTANTS = {\n 'skel_id': 18383770,\n 'project_id': 4,\n 'image_stack_id': 4\n}\n\nlogger = logging.getLogger(__name__)\napi_logger = logging.getLogger(__name__ + '.api')\n\n\ndef get_consecutive(lst):\n \"\"\"\n Given an iterable of unique integers, return a list of lists where the elements of the inner lists are all\n consecutive and in ascending order.\n\n >>> get_consecutive([2, 4, 1, 5])\n [[1, 2], [4, 5]]\n \"\"\"\n sorted_lst = sorted(lst)\n ret_lst = [[sorted_lst.pop(0)]]\n while sorted_lst:\n if sorted_lst[0] == ret_lst[-1][-1] + 1:\n ret_lst[-1].append(sorted_lst.pop(0))\n else:\n ret_lst.append([sorted_lst.pop(0)])\n\n return ret_lst\n\n\ndef extend_slices(broken_slices):\n \"\"\"\n Given a dict whose keys are z-indexes of missing slices (as reported by stack_info), return a slice extension\n schema as required by ilastik's stack description json.\n\n Note: not sure what the value of the input dict should mean, so an assertion error is thrown if it is not 1.\n\n >>> extend_slices({'349': 1, '350': 1, '351': 1, '99': 1})\n [[98, [99]], [348, [349, 350]], [352, [351]]]\n \"\"\"\n assert all(value == 1 for value in broken_slices.values()), 'Not sure what to do with broken_slice values != 1'\n d = defaultdict(list)\n for broken_block in get_consecutive(int(item) for item in broken_slices):\n pre, post = min(broken_block) - 1, max(broken_block) + 1\n idxs = list(broken_block)\n while idxs:\n d[pre].append(idxs.pop(0))\n if idxs:\n d[post].append(idxs.pop())\n\n return [[key, value] for key, value in sorted(d.items(), key=lambda x: x[0])]\n\n\ndef make_tile_url_template(image_base):\n \"\"\"\n May not be correct for all bases\n \"\"\"\n return make_url(image_base, \"{z_index}/0/{y_index}_{x_index}.jpg\")\n\n\ndef to_iterable(arg):\n if isinstance(arg, string_types):\n return [arg]\n try:\n return list(arg)\n except TypeError as e:\n if \"is not iterable\" in str(e):\n return [arg]\n raise e\n\n\ndef get_nodes_between(graph, root=None, leaves=None):\n \"\"\"\n Find all nodes both downstream of the given root and upstream of any of the given leaves.\n\n Parameters\n ----------\n graph\n root\n If None, find the root of the tree\n leaves\n If None, find all leaves of the tree\n\n Returns\n -------\n\n \"\"\"\n assert nx.is_directed_acyclic_graph(graph)\n\n if root is None:\n for node, degree in graph.in_degree_iter():\n if degree == 0:\n root = node\n break\n\n if leaves is None:\n leaves = [node for node, degree in graph.out_degree_iter() if degree == 0]\n\n output_set = set(leaves)\n for leaf in leaves:\n leaf_ancestors = nx.ancestors(graph, leaf)\n if root in leaf_ancestors:\n output_set.update(leaf_ancestors)\n\n return output_set - nx.ancestors(graph, root)\n\n\ndef get_subarbor_node_infos(tnid_parentid, coords_xyz, root=None, leaves=None):\n \"\"\"\n\n\n Parameters\n ----------\n tnid_parentid : list of tuple\n List of pairs of (treenode_id, parent_id)\n coords_xyz : list of tuple\n List of (x, y, z) tuples\n root\n Most basal node to return\n leaves\n Most distal nodes to return\n\n Returns\n -------\n list of NodeInfo\n \"\"\"\n node_infos = []\n if root is None and leaves is None:\n for (node_id, parent_id), (x, y, z) in zip(tnid_parentid, coords_xyz):\n node_infos.append(NodeInfo(int(node_id), x, y, z, None if parent_id is None else int(parent_id)))\n return node_infos\n\n g = nx.DiGraph()\n for (node_id, parent_id), (x, y, z) in zip(tnid_parentid, coords_xyz):\n node_id = int(node_id)\n g.add_node(node_id, node_info=NodeInfo(node_id, x, y, z, None if parent_id is None else int(parent_id)))\n if not parent_id:\n root = root or node_id\n else:\n g.add_edge(int(parent_id), node_id)\n\n for node_id in get_nodes_between(g, root, leaves):\n node_infos.append(g.node[node_id]['node_info'])\n\n return node_infos\n\n\nclass CatmaidSynapseSuggestionAPI(CatmaidClientApplication):\n def __init__(self, catmaid_client, stack_id_or_title=None):\n super(CatmaidSynapseSuggestionAPI, self).__init__(catmaid_client)\n self.export_widget = ExportWidget(catmaid_client)\n self.stack_id = self._get_stack_id(stack_id_or_title)\n\n def _get_stack_id(self, stack_id_or_title):\n try:\n return int(stack_id_or_title)\n except TypeError:\n if stack_id_or_title is None:\n return None\n stacks = self.get((self.project_id, 'stacks'))\n for stack in stacks:\n if stack['title'] == stack_id_or_title:\n return stack['id']\n raise ValueError('Stack {} not found for project with ID {}'.format(repr(stack_id_or_title), self.project_id))\n\n def get_stack_description(self, stack_id_or_title, include_offset=True, cache_tiles=False):\n \"\"\"\n Generate sufficient information for ilastik to read images from CATMAID.\n\n Parameters\n ----------\n stack_id_or_title : int or str\n Integer ID or string title of the image stack in CATMAID\n include_offset : bool, optional\n Whether to include the stack offset from the project. Including the offset makes it easier to align the\n skeleton geometry with the CATMAID images, but not including it makes it easier to align the ilastik and\n CATMAID images for debugging purposes. Defaults to True.\n cache_tiles : bool, optional\n Whether to cache the tiles (makes viewing them for debugging easier)\n\n Returns\n -------\n dict\n Information required by ilastik for getting images from CATMAID\n \"\"\"\n stack_info = self.get_stack_info(stack_id_or_title)\n stack_mirror = stack_info['mirrors'][0]\n\n return {\n \"_schema_name\": \"tiled-volume-description\",\n \"_schema_version\": 1.0,\n\n \"name\": stack_info['stitle'],\n \"format\": stack_mirror['file_extension'], # works for jpg\n \"dtype\": \"uint8\", # not defined in stack_info\n \"bounds_zyx\": [stack_info['dimension'][axis] for axis in 'zyx'],\n\n # skeleton files do not necessarily use the same coordinates as the CATMAID viewer/tiles, there may be an\n # offset, encoded here. May not be correct, please check. Using this offset makes the ilastik and catmaid\n # z-coordinates not line up, but the skeleton file does.\n \"view_origin_zyx\": [\n -int(stack_info['translation'][axis]/stack_info['resolution'][axis]) * include_offset for axis in 'zyx'\n ],\n\n \"resolution_zyx\": [stack_info['resolution'][axis] for axis in 'zyx'],\n \"tile_shape_2d_yx\": [stack_mirror['tile_height'], stack_mirror['tile_width']],\n\n \"tile_url_format\": make_tile_url_template(stack_mirror['image_base']), # may not be correct for all bases\n\n \"output_axes\": \"xyz\", # DO NOT TOUCH\n\n \"cache_tiles\": cache_tiles, # useful for debug viewing\n\n \"extend_slices\": extend_slices(stack_info['broken_slices'])\n }\n\n def get_project_title(self, stack_id_or_title):\n stack_info = self.get_stack_info(stack_id_or_title)\n\n return stack_info['ptitle']\n\n def _get_user_id(self, user_id_or_name):\n try:\n return int(user_id_or_name)\n except ValueError:\n users = self.get('user-list')\n for user in users:\n if user_id_or_name in [user['login'], user['full_name']]:\n return user['id']\n raise ValueError('User {} not found.'.format(repr(user_id_or_name)))\n\n def get_connectors(self, user_id_or_name, date_from, date_to):\n \"\"\"\n\n Parameters\n ----------\n user_id_or_name\n date_from : datetime.datetime\n date_to : datetime.datetime\n\n Returns\n -------\n dict\n Keys are connector IDs, values are coordinate dicts in project space\n \"\"\"\n params = dict()\n\n if user_id_or_name:\n params['completed_by'] = self._get_user_id(user_id_or_name)\n if date_from:\n params['from'] = date_from.strftime('%Y%m%d')\n if date_to:\n params['to'] = date_to.strftime('%Y%m%d')\n\n output = dict()\n\n for row in self.get((self.project_id, 'connector/list/completed'), params):\n output[row[0]] = {dim: val for dim, val in zip('xyz', row[1])}\n\n return output\n\n def get_stack_info(self, stack_id_or_title):\n stack_id = self._get_stack_id(stack_id_or_title)\n return self.get((self.project_id, 'stack', stack_id, 'info'))\n\n def get_coord_transformer(self, stack_id_or_title=None):\n if stack_id_or_title is None:\n return CoordinateTransformer()\n else:\n stack_id = self._get_stack_id(stack_id_or_title)\n return CoordinateTransformer.from_catmaid(self._catmaid, stack_id)\n\n def get_transformed_treenode_and_connector_geometry(self, stack_id_or_title, *skeleton_ids):\n data = self.export_widget.get_treenode_and_connector_geometry(*skeleton_ids)\n if stack_id_or_title is None:\n return data\n\n transformer = self.get_coord_transformer(stack_id_or_title)\n\n for skid, skel_data in data['skeletons'].items():\n for treenode_id, treenode_data in skel_data['treenodes'].items():\n treenode_data['location'] = tuple(transformer.project_to_stack_array(treenode_data['location']))\n\n for connector_id, connector_data in skel_data['connectors'].items():\n connector_data['location'] = tuple(transformer.project_to_stack_array(connector_data['location']))\n\n return data\n\n def get_workflow_id(self, stack_id, detection_hash, tile_size=512, detection_notes=None):\n params = {'stack_id': stack_id, 'detection_hash': detection_hash, 'tile_size': tile_size}\n if detection_notes:\n params['algo_notes'] = detection_notes\n return self.get(('ext/synapsesuggestor/synapse-detection/workflow'), params)['workflow_id']\n\n def get_project_workflow_id(self, workflow_id, association_hash, association_notes=None):\n params = {'workflow_id': workflow_id, 'association_hash': association_hash}\n if association_notes:\n params['algo_notes'] = association_notes\n return self.get(\n ('ext/synapsesuggestor/treenode-association', self.project_id, 'workflow'), params\n )['project_workflow_id']\n\n def get_node_infos(self, skeleton_ids, stack_id_or_title=None, root=None, leaves=None):\n \"\"\"\n Get locations of treenodes as xyz coordinates. If a stack id or title is given, transform the coordinates into\n stack coords.\n\n Parameters\n ----------\n skeleton_ids : int or str or iterable\n stack_id_or_title : int or str\n\n Returns\n -------\n tuple of (array-like, array-like)\n An M-length array of node IDs and an M*3 array of XYZ coordinates, for M nodes\n \"\"\"\n transformer = self.get_coord_transformer(stack_id_or_title)\n coord_type = int if stack_id_or_title is not None else float\n skeleton_ids = set(to_iterable(skeleton_ids))\n\n node_infos = []\n for skeleton_id in skeleton_ids:\n treenodes = self.get((self.project_id, 'skeletons', skeleton_id, 'compact-detail'))[0]\n treenodes_arr = np.array(treenodes)\n coords = transformer.project_to_stack_array(treenodes_arr[:, 3:6].astype(float))\n node_infos.extend(get_subarbor_node_infos(treenodes_arr[:, :2], coords.astype(coord_type), root, leaves))\n\n return node_infos\n\n def get_detected_tiles(self, workflow_id):\n \"\"\"\n xyz\n\n Parameters\n ----------\n workflow_id\n\n Returns\n -------\n set of tuple\n Tuples of tile indices in XYZ order\n \"\"\"\n data = self.get('ext/synapsesuggestor/synapse-detection/tiles/detected', {'workflow_id': workflow_id})\n return {tuple(item) for item in data}\n\n def add_synapse_slices_to_tile(self, workflow_id, synapse_slices, tile_idx):\n \"\"\"\n\n\n Parameters\n ----------\n workflow_id\n synapse_slices : dict\n Properties are id, wkt_str, size_px, xs_centroid, ys_centroid, uncertainty\n tile_idx : tuple\n Tile index in ZYX order\n\n Returns\n -------\n\n \"\"\"\n data = {\n 'workflow_id': workflow_id,\n 'synapse_slices': [json.dumps(synapse_slice) for synapse_slice in synapse_slices],\n 'z_idx': tile_idx[0],\n 'y_idx': tile_idx[1],\n 'x_idx': tile_idx[2]\n }\n\n url = 'ext/synapsesuggestor/synapse-detection/tiles/insert-synapse-slices'\n api_logger.debug('POST to {}\\n{}'.format(url, data))\n response_data = self.post(url, data)\n api_logger.debug('Returned\\n{}'.format(response_data))\n\n return {int(key): value for key, value in response_data.items()}\n\n def agglomerate_synapses(self, synapse_slice_ids):\n return self.post(\n 'ext/synapsesuggestor/synapse-detection/slices/agglomerate',\n {'synapse_slices': list(synapse_slice_ids)}\n )\n\n def add_synapse_treenode_associations(self, associations, project_workflow_id=None):\n \"\"\"\n\n Parameters\n ----------\n associations : list of tuples\n [(synapse_slice_id, treenode_id, contact_px), ...]\n project_workflow_id\n\n Returns\n -------\n\n \"\"\"\n data = {'associations': [json.dumps(association) for association in associations]}\n if project_workflow_id is not None:\n data['project_workflow_id'] = project_workflow_id\n return self.post(('ext/synapsesuggestor/treenode-association', self.project_id, 'add'), data)\n\n def get_treenode_synapse_associations(self, skeleton_id, project_workflow_id=None):\n params = {'skid': skeleton_id}\n if project_workflow_id is not None:\n params['project_workflow_id'] = project_workflow_id\n\n return self.get(('ext/synapsesuggestor/treenode-association', self.project_id, 'get'), params)\n\n def get_synapse_bounds(self, synapse_ids, z_padding=1, xy_padding=10):\n params = {'synapse_object_ids': list(synapse_ids), 'z_padding': int(z_padding), 'xy_padding': int(xy_padding)}\n\n return self.get('ext/synapsesuggestor/analysis/synapse-extents', params)\n\n def sample_treenodes(self, count=None, seed=None):\n params = dict()\n if count:\n params['count'] = count\n if seed is not None:\n params['seed'] = seed\n\n return self.get(('ext/synapsesuggestor/training-data', self.project_id, 'treenodes/sample'), params)\n\n def treenodes_by_tag(self, *tags):\n return self.get(('ext/synapsesuggestor/training-data', self.project_id, 'treenodes/label'), {'tags': tags})\n\n def get_synapses_near_skeletons(self, skeleton_ids, project_workflow_id=None, distance=600):\n skids = to_iterable(skeleton_ids)\n\n output = []\n for skid in skids:\n params = {'skid': skid, 'distance': distance}\n if project_workflow_id is not None:\n params['project_workflow_id'] = project_workflow_id\n\n response = self.get(('ext/synapsesuggestor/treenode-association', self.project_id, 'get-distance'), params)\n output.extend(dict(zip(response['columns'], row)) for row in response['data'])\n\n return output\n\n def get_nodes_in_roi(self, roi_xyz, stack_id_or_title=None):\n \"\"\"\n Get the nodes in the ROI with their coordinates relative to the top-left corner of the ROI.\n\n Parameters\n ----------\n roi_xyz : np.array\n [[xmin, ymin, zmin],[xmax, ymax, zmax]] in stack space\n stack_id_or_title\n\n Returns\n -------\n\n \"\"\"\n transformer = self.get_coord_transformer(stack_id_or_title)\n # convert a half-closed [xyz, xyz) ROI for slice indexing into closed [xyz, xyz] for geometric intersection\n intersection_roi = roi_xyz - np.array([[0, 0, 0], [1, 1, 1]])\n roi_xyz_p = transformer.stack_to_project_array(intersection_roi)\n data = {\n 'left': roi_xyz_p[0, 0],\n 'top': roi_xyz_p[0, 1],\n 'z1': roi_xyz_p[0, 2],\n 'right': roi_xyz_p[1, 0],\n 'bottom': roi_xyz_p[1, 1],\n 'z2': roi_xyz_p[1, 2]\n }\n response = self.post((self.project_id, '/node/list'), data)\n treenodes = dict()\n for treenode_row in response[0]:\n tnid, _, x, y, z, _, _, skid, _, _ = treenode_row\n if not in_roi(roi_xyz_p, [x, y, z]):\n # API returns treenodes which are out of ROI if they have an edge which passes through the ROI\n continue\n\n treenodes[tnid] = {\n 'coords': {\n 'x': int(transformer.project_to_stack_coord('x', x) - roi_xyz[0, 0]),\n 'y': int(transformer.project_to_stack_coord('y', y) - roi_xyz[0, 1]),\n 'z': int(transformer.project_to_stack_coord('z', z) - roi_xyz[0, 2])\n },\n 'skeleton_id': skid,\n 'treenode_id': tnid\n }\n\n return treenodes\n\n\ndef in_roi(roi_xyz, coords_xyz):\n \"\"\"Closed interval: use intersection_roi\"\"\"\n x, y, z = coords_xyz\n return all([\n roi_xyz[0, 0] <= x <= roi_xyz[1, 0],\n roi_xyz[0, 1] <= y <= roi_xyz[1, 1],\n roi_xyz[0, 2] <= z <= roi_xyz[1, 2]\n ])\n","sub_path":"skeleton_synapses/catmaid_interface.py","file_name":"catmaid_interface.py","file_ext":"py","file_size_in_byte":18315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"220240489","text":"# -*- coding: UTF-8 -*-\nimport os\n\nimport sentencepiece as spm\nimport tensorflow.compat.v1 as tf\n\nimport sys\nsys.path.append(\"./\")\n\n\nif __name__ == \"__main__\":\n # STORAGE_BUCKET = \"gs://sbt0\"\n # input_dir_gs = os.path.join(\n # STORAGE_BUCKET,\n # \"data/corpus/char_lower/zhwiki-latest-pages-articles_char_lower.txt\"\n # )\n # input_dir_local = \"./zhwiki-latest-pages-articles_char_lower.txt\"\n # tf.gfile.Copy(input_dir_gs, input_dir_local, overwrite=True)\n #\n #\n # for vocab_size in [15000]:\n #\n # spm.SentencePieceTrainer.train('--input=zhwiki-latest-pages-articles_char_lower.txt --model_prefix=./resources/tokenizer/char-%d-clean --vocab_size=%d --pad_id=0 --unk_id=1 --eos_id=-1 --bos_id=-1 --control_symbols=[CLS],[SEP],[MASK] --user_defined_symbols=(,),”,-,.,–,£,€ --shuffle_input_sentence=true --input_sentence_size=30000000 --character_coverage=0.99995 --model_type=bpe --num_threads=32' % (vocab_size, vocab_size))\n\n # vocab_sizes = [5000, 10000, 15000, 20000, 25000, 30000]\n vocab_sizes = [21128, 5282, 1321]\n prefixes = [\n # \"char_spaced_lower\",\n # \"char_no_space_lower\",\n # \"subchar_no_space_lower\",\n \"subchar_spaced_lower\",\n \"subchar_segmented_lower\",\n ]\n\n STORAGE_BUCKET = \"gs://sbt0\"\n\n for prefix in prefixes:\n input_dir_gs = os.path.join(\n STORAGE_BUCKET,\n \"data/corpus/%s/zhwiki-latest-pages-articles_%s.txt\" % (prefix, prefix)\n )\n input_dir_local = \"./zhwiki-latest-pages-articles_%s.txt\" % prefix\n tf.gfile.Copy(input_dir_gs, input_dir_local, overwrite=True)\n\n\n for vocab_size in vocab_sizes:\n for prefix in prefixes:\n try:\n spm.SentencePieceTrainer.train(\n '--input=./zhwiki-latest-pages-articles_%s.txt --model_prefix=./data_proc/tokenizers/sentencepiece/%s-%d-clean --vocab_size=%d --pad_id=0 --unk_id=1 --eos_id=-1 --bos_id=-1 --control_symbols=[CLS],[SEP],[MASK] --user_defined_symbols=(,),”,-,.,–,£,€ --shuffle_input_sentence=true --input_sentence_size=15000000 --model_type=bpe --num_threads=16' % (\n prefix, prefix, vocab_size, vocab_size)\n )\n\n except Exception as e:\n print(e)\n\n\n","sub_path":"data_proc/build_spm.py","file_name":"build_spm.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"171796304","text":"# -*- coding: UTF-8 -*-\nfrom . import db\nfrom datetime import datetime\nfrom . import login_manager\nfrom flask.ext.login import UserMixin, AnonymousUserMixin, current_user\nfrom sqlalchemy import and_, event\nfrom collections import OrderedDict\nfrom functools import wraps\n\n\n\n\nclass Permission:\n \"\"\"对权限的细分\n \"\"\"\n SET_FIRST_GRADE = 0x01 # 添加第一个grade\n SET_NEW_GRADE = 0x02 # 添加非第一个grade\n LOOK_LAST_GRADE = 0x04 # 查看最后一个grade\n LOOK_ALL_GRADE = 0x08 # 查看全部的grade\n UPDATE_STUDENT = 0x10 # 更新学生信息\n DELETE_LOG = 0x20 # 删除grade的能力\n\n LOOK_LOG = 0x40\n LOOK_ADMIN_LOG = 0x80\n\n SET_ENTRYER_OR_TUTOR = 0x100\n SET_ADMIN = 0x200\n\n SET_ROLE = 'SET_ROLE'\n # 能把前一组中的角色设置给后一个组中的角色\n authorize_dict = {\n SET_ADMIN: (['Entryer', 'Tutor', 'Admin', 'Tourist'], ['Admin', 'Tourist']),\n SET_ENTRYER_OR_TUTOR: (['Entryer', 'Tutor', 'Tourist'], ['Entryer', 'Tutor', 'Tourist'])\n }\n\n\n def print_return(func, *args, **kwargs):\n @wraps(func)\n def wraper(*args, **kwargs):\n print(args, kwargs)\n print(func(*args, **kwargs))\n return func(*args, **kwargs)\n return wraper\n\n @staticmethod\n # @print_return\n def is_licensable(permissions, old, new):\n \"\"\"判断 permissions权限 能否进行将 old角色 转变为 new角色\n\n 一个转化可能需要复数个权限\n\n Args:\n permissions: 拥有的权限\n old: 旧的角色名称\n new: 新的角色名称\n \"\"\"\n\n all = []\n for per, v in Permission.authorize_dict.items():\n if per & permissions == per:\n all.append([set(v[0]), set(v[1])])\n\n\n\n inp = set([old, ])\n mark = True\n while all and mark:\n mark = False\n for x in all:\n if inp & x[0]:\n if new in x[1]:\n return True\n else:\n inp.update(x[1])\n all.remove(x)\n mark = True\n return False\n\n ADMIN = 0x400\n SUPER_ADMIN = 0x800\n\n\nclass Role(db.Model):\n \"\"\"权限\"\"\"\n __tablename__ = 'roles'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String)\n permissions = db.Column(db.Integer)\n\n users = db.relationship('User', lazy='dynamic', backref='role')\n\n @staticmethod\n def get_default_role_name():\n \"\"\"返回注册时默认权限\"\"\"\n return 'Tourist'\n\n @staticmethod\n def insert_roles():\n roles = {\n 'Tourist': 0x00,\n 'Entryer': (Permission.SET_FIRST_GRADE |\n Permission.SET_NEW_GRADE |\n Permission.LOOK_LAST_GRADE),\n 'Tutor': (Permission.SET_NEW_GRADE |\n Permission.LOOK_LAST_GRADE |\n Permission.LOOK_ALL_GRADE |\n Permission.UPDATE_STUDENT),\n 'Admin': (Permission.SET_NEW_GRADE |\n Permission.LOOK_LAST_GRADE |\n Permission.LOOK_ALL_GRADE |\n Permission.DELETE_LOG |\n Permission.LOOK_LOG |\n Permission.SET_ENTRYER_OR_TUTOR |\n Permission.UPDATE_STUDENT |\n Permission.ADMIN),\n 'SuperAdmin': 0xfff,\n }\n for r in roles:\n role = Role.query.filter_by(name=r).first()\n if role is None:\n role = Role(name=r)\n role.permissions = roles[r]\n db.session.add(role)\n db.session.commit()\n\n def __repr__(self):\n return '' % self.name\n\n\nclass Student(db.Model):\n \"\"\"对象与xlsx表格对应\n *************原始xlsx格式********************************\n 学号 \n 姓名 \n 民族代码 \n 性别 1 和 2\n 出生日期 看不懂的格式\n 学生来源 数字编号\n 身份证号 \n 家庭住址 \n \"\"\"\n __tablename__ = 'students'\n\n id = db.Column(db.Integer, primary_key=True)\n student_id = db.Column(db.String, index=True, unique=True, nullable=False)\n name = db.Column(db.String, nullable=False)\n national_code = db.Column(db.String)\n sex = db.Column(db.Boolean)\n birth_date = db.Column(db.String)\n sources = db.Column(db.String)\n identity = db.Column(db.String)\n address = db.Column(db.String)\n\n iserror = db.Column(db.Boolean, default=False)\n\n clase_id = db.Column(db.Integer, db.ForeignKey('clases.id'))\n grades = db.relationship('GradeLog', backref='student', lazy='select')\n\n @property\n def grade(self):\n return self.grades[-1] if self.grades else None\n\n def get_bill(self):\n d = OrderedDict()\n d[\"学号\"] = self.student_id\n d[\"姓名\"] = self.name\n d[\"民族代码\"] = self.national_code\n d[\"性别\"] = self.sex\n d[\"出生日期\"] = self.birth_date\n d[\"学生来源\"] = self.sources\n d[\"身份证号\"] = self.identity\n d[\"家庭住址\"] = self.address\n return d\n\n\nclass Clase(db.Model):\n \"\"\"班级对象\n xlsx 类型:\n 年级编号 41\n 班级编号 41090\n 班级名称 自动化1302\n \"\"\"\n __tablename__ = 'clases'\n\n id = db.Column(db.Integer, primary_key=True)\n clase_id = db.Column(db.String, unique=True, nullable=False)\n age_id = db.Column(db.String)\n name = db.Column(db.String, index=True, unique=True, nullable=False)\n\n # 大概试了了一下,通过班级查找学生时, lazy=select 比 lazy=dynamic 快10倍左右, 然而反应在网页上的速度没有明显变换\n students = db.relationship('Student', backref='clase', lazy='select')\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n\n def __repr__(self):\n return '' % self.name\n\n\nclass GradeLog(db.Model):\n \"\"\"记录每一次修改的grade\n ****成绩日志对象*****************************************\n 身高\n 体重\n 肺活量\n 跑50米\n 立定跳远\n 坐位体前屈\n 跑800米/跑1000米\n 一分钟仰卧起坐/引体向上\n 左眼视力\n 右眼视力\n \"\"\"\n __tablename__ = 'grade_logs'\n\n id = db.Column(db.Integer, primary_key=True)\n\n height = db.Column(db.Float)\n weight = db.Column(db.Float)\n fvc = db.Column(db.Float)\n fifty_ran = db.Column(db.Float)\n standing_jump = db.Column(db.Float)\n sit_reach = db.Column(db.Float)\n run800 = db.Column(db.Float)\n run1000 = db.Column(db.Float)\n push_up = db.Column(db.Float)\n chin_up = db.Column(db.Float)\n left_sight = db.Column(db.Float)\n right_sight = db.Column(db.Float)\n\n student_sex = db.Column(db.Boolean)\n student_id = db.Column(db.Integer, db.ForeignKey('students.id'))\n inittime = db.Column(db.DateTime, index=True, default=datetime.utcnow)\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n\n @staticmethod\n def insert_sex():\n for g in GradeLog.query.all():\n g.student_sex = g.student.sex\n db.session.add(g)\n db.session.commit()\n\n @staticmethod\n def set_student_sex(target, value, oldvalue, initiator):\n target.student_sex = target.student.sex\n\n def get_bill(self):\n \"\"\"获得成绩单中 各类成绩 在类中的 属性名 和其中文名字\n \"\"\"\n d = OrderedDict()\n d[\"身高\"] = self.height\n d[\"体重\"] = self.weight\n d[\"肺活量\"] = self.fvc\n d[\"跑50米\"] = self.fifty_ran\n d[\"立定跳远\"] = self.standing_jump\n d[\"坐位体前屈\"] = self.sit_reach\n if self.student_sex:\n d[\"跑1000米\"] = self.run1000\n d[\"引体向上\"] = self.chin_up\n else:\n d[\"跑800米\"] = self.run800\n d[\"一分钟仰卧起坐\"] = self.push_up\n d[\"左眼视力\"] = self.left_sight\n d[\"右眼视力\"] = self.right_sight\n return d\n\n @staticmethod\n def add(user, student,\n height, weight, fvc, fifty_ran, standing_jump, sit_reach, run, xxx_up, left_sight, right_sight):\n \"\"\"添加user对象给予student更新成绩的记录\n\n 并不对权限进行检测\n\n :return\n 0: 提交的记录和原来的记录重复\n 1: 成功\n \"\"\"\n\n grade = student.grade\n if grade and all([\n grade.height == height,\n grade.weight == weight, grade.fvc == fvc,\n grade.fifty_ran == fifty_ran,\n grade.standing_jump == standing_jump,\n grade.sit_reach == sit_reach,\n (grade.run1000 if student.sex else grade.run800) == run,\n (grade.chin_up if student.sex else grade.push_up) == xxx_up,\n grade.left_sight == left_sight,\n grade.right_sight == right_sight]):\n return 0\n\n new_grade = GradeLog(user=user, student=student)\n new_grade.height = height\n new_grade.weight = weight\n new_grade.fvc = fvc\n new_grade.fifty_ran = fifty_ran\n new_grade.standing_jump = standing_jump\n new_grade.sit_reach = sit_reach\n if student.sex:\n new_grade.run1000 = run\n new_grade.chin_up = xxx_up\n else:\n new_grade.run800 = run\n new_grade.push_up = xxx_up\n new_grade.left_sight = left_sight\n new_grade.right_sight = right_sight\n\n db.session.add(new_grade)\n db.session.commit()\n return 1\n\n def __repr__(self):\n return '' % self.id\n\n\nevent.listen(GradeLog.student_id, 'set', GradeLog.set_student_sex)\n\n\nclass ManageLog(db.Model):\n \"\"\"纪录每次role的变化\"\"\"\n __tablename__ = 'manage_logs'\n id = db.Column(db.Integer, primary_key=True)\n manager_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n managed_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n inittime = db.Column(db.DateTime, default=datetime.utcnow)\n old_power = db.Column(db.String)\n new_power = db.Column(db.String)\n\n def __repr__(self):\n return '' % self.id\n\n\nclass User(UserMixin, db.Model):\n \"\"\"系统的使用者\n\n User 中所有的实例方法都要求默认进行权利检查\n \"\"\"\n __tablename__ = 'users'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String, unique=True)\n user = db.Column(db.String, unique=True, index=True)\n # TODO: 使用散列储存更好\n password = db.Column(db.String)\n inittime = db.Column(db.DateTime, index=True, default=datetime.utcnow)\n\n role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))\n grade_logs = db.relationship('GradeLog', backref='user', lazy='dynamic')\n clases = db.relationship('Clase', backref='teacher', lazy='dynamic')\n\n managed_logs = db.relationship('ManageLog',\n foreign_keys=[ManageLog.manager_id],\n backref=db.backref('manager', lazy='joined'),\n lazy='dynamic')\n manager_logs = db.relationship('ManageLog',\n foreign_keys=[ManageLog.managed_id],\n backref=db.backref('managed', lazy='joined'),\n lazy='dynamic')\n\n def __init__(self, **kwargs):\n super(User, self).__init__(**kwargs)\n self.role = Role.query.filter_by(name=Role.get_default_role_name()).first()\n\n def can(self, permission, *args):\n \"\"\"是否具备permission的权利\"\"\"\n if permission is Permission.SET_ROLE:\n assert(len(args) == 2)\n old, new = args\n return Permission.is_licensable(self.role.permissions, old, new)\n\n return self.role is not None \\\n and (self.role.permissions & permission) == permission\n\n def is_admin(self):\n return self.can(Permission.ADMIN)\n\n def is_superadmin(self):\n return self.can(Permission.SUPER_ADMIN)\n\n def give_role(self, given_user, new_role_name):\n \"\"\"修改user对象自身的权限, 并写入日志,\n\n Args:\n given_user: 给予的User对象\n new_role_name: 新权限的名称\n \"\"\"\n log = ManageLog()\n log.managed = given_user\n log.manager = self\n log.old_power = given_user.role.name\n log.new_power = new_role_name\n\n new_role = Role.query.filter_by(name=new_role_name).first()\n given_user.role = new_role\n\n db.session.add(log)\n db.session.add(given_user)\n db.session.commit()\n\n\n # TODO: 这个方法耦合性太强了, 我在GradeLog 中写了一个静态的add方法, 实际中也使用的是后者版本。\n def set_grade(self, student, *args):\n \"\"\"给学生添加成绩,\n Args:\n student: 学生对象\n args: 身高 体重 肺活量 跑50米 立定跳远 坐位体前屈 跑800米/跑1000米 一分钟仰卧起坐/引体向上 左眼视力 右眼视力\n \"\"\"\n if student.grade:\n last_log_bill = student.grade.get_bill()\n assert len(args) == len(last_log_bill)\n\n if list(last_log_bill.values()) == args:\n return False\n\n\n height, weight, fvc, fifty_ran, standing_jump, sit_reach, runx, x_up, left_sight, right_sight = args\n log = GradeLog()\n log.student = student\n log.user = self\n log.height = height\n log.weight = weight\n log.fvc = fvc\n log.fifty_ran = fifty_ran\n log.standing_jump = standing_jump\n log.sit_reach = sit_reach\n if student.sex:\n log.run1000 = runx\n log.chin_up = x_up\n else:\n log.run800 = runx\n log.push_up = x_up\n log.left_sight = left_sight\n log.right_sight = right_sight\n\n db.session.add(log)\n db.session.commit()\n return True\n\n def verify_password(self, password):\n \"\"\"验证密码\"\"\"\n return self.password == password\n\n def __repr__(self):\n return '' % self.name\n\n\nclass AnonymousUser(AnonymousUserMixin):\n def can(self):\n \"\"\"使未登录用户具有与登陆用户一样的行为\"\"\"\n return False\n\n def is_admin(self):\n \"\"\"使未登录用户具有与登陆用户一样的行为\"\"\"\n return False\n\n\nlogin_manager.anonymous_user = AnonymousUser\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n return User.query.get(int(user_id))\n","sub_path":"app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":14896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"20999650","text":"class Solution:\n def rob(self, nums: List[int]) -> int:\n # 如果从下标为n的房子(即第n + 1)开始抢,那么肯定是抢不到钱的,直接返回0\n if not nums: return 0\n\n n = len(nums)\n if n == 1: return nums[0]\n\n dp = [0] * n\n dp[0] = nums[0]\n dp[1] = max(nums[0], nums[1])\n for i in range(2, n):\n dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])\n\n return dp[n - 1]\n\n def rob1(self, nums: List[int]) -> int:\n if not nums: return 0\n\n n = len(nums)\n if n == 1: return nums[0]\n\n pre, now = nums[0], max(nums[0], nums[1])\n for i in range(2, n):\n pre, now = now, max(pre + nums[i], now)\n\n return now","sub_path":"Week_06/house-robber.py","file_name":"house-robber.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"131700327","text":"import unittest\nimport copy\nimport datetime\nfrom anchore_engine.db import ImagePackageVulnerability\n\n\nclass TestImagePackageVulnerabilityHashing(unittest.TestCase):\n def test_cmp(self):\n c1 = ImagePackageVulnerability()\n c1.pkg_name = 'testpkg1'\n c1.pkg_version = '1.0'\n c1.pkg_arch = 'x86'\n c1.pkg_type = 'rpm'\n c1.pkg_image_id = 'image123'\n c1.pkg_user_id = '0'\n c1.vulnerability_namespace_name = 'centos:6'\n c1.vulnerability_id = 'CVE-2016-123'\n c1.created_at = datetime.datetime.utcnow()\n\n c2 = copy.deepcopy(c1)\n self.assertEqual(c1, c2)\n c3 = copy.deepcopy(c1)\n self.assertEqual(c1, c3)\n c4 = copy.deepcopy(c1)\n self.assertEqual(c1, c4)\n\n c3.pkg_version = '1.1'\n c4.pkg_user_id = '1'\n\n self.assertEqual(c1, c2)\n self.assertNotEqual(c1, c4)\n self.assertNotEqual(c1, c3)\n self.assertListEqual(list({c1, c2, c3}), list({c1, c3}))\n\n print(('Set: {}'.format({c1, c2, c3})))\n\nif __name__ == '__main__':\n t = TestImagePackageVulnerabilityHashing()\n t.run()","sub_path":"legacy_test/services/policy_engine/db/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"81423573","text":"import sys\nimport pygame\nfrom bullet import Bullet\nfrom alien import Alien\nfrom time import sleep\n\ndef check_events(ai_settings,screen,stats,sb,play_button,ship,aliens,bullets):\n # Watch for keyboard and mouse events.\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n check_keydown_events(event,ai_settings,screen,ship,bullets)\n elif event.type == pygame.KEYUP:\n check_keyup_events(event,ship)\n elif event.type == pygame.MOUSEBUTTONDOWN:\n mouse_x,mouse_y = pygame.mouse.get_pos()\n check_play_button(ai_settings,screen,stats,sb,play_button,\n ship,aliens,bullets,mouse_x,mouse_y)\n\ndef check_play_button(ai_settings,screen,stats,sb,play_button,ship,aliens,\n bullets,mouse_x,mouse_y):\n \"\"\"Start a new game when player clicks Play\"\"\"\n if play_button.rect.collidepoint(mouse_x,mouse_y) and not stats.game_active:\n #Reset te game settings\n ai_settings.intialize_dynamic_settings()\n #Hide the mouse cursor\n pygame.mouse.set_visible(False)\n #Reset the game stats\n stats.reset_stats()\n stats.game_active = True\n\n sb.prep_score()\n sb.prep_high_score()\n sb.prep_level()\n sb.prep_ships()\n\n #Empty thye list of aliens and bullets\n aliens.empty()\n bullets.empty()\n\n #Create a newfleest and centre the ship\n create_fleet(ai_settings,screen,ship,aliens)\n ship.center_ship()\n\n\n\ndef check_keydown_events(event,ai_settings,screen,ship,bullets):\n if 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(ai_settings,screen,ship,bullets)\n elif event.key == pygame.K_q:\n sys.exit()\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\n \n\ndef update_screen(ai_settings,screen,stats,sb,ship,aliens,bullets,play_button):\n #Redraw the screen on each pass through the loop\n screen.fill(ai_settings.bg_color)\n # Redraw all bullets behind ship and aliens\n for bullet in bullets.sprites():\n bullet.draw_bullet() \n\n ship.blitme()\n aliens.draw(screen)\n #Draw the score info\n sb.show_score()\n\n # Draw the play button if the game is inactive\n if not stats.game_active:\n play_button.draw_button()\n\n # Make the most recently drawn screen visible.\n pygame.display.flip()\n\ndef update_bullets(ai_settings,screen,stats,sb,ship,aliens,bullets):\n \"\"\"Update the position of bullets and get rid of old bullets\"\"\"\n bullets.update()\n \n #Get rid of old bullets \n for bullet in bullets.copy():\n if bullet.rect.bottom <= 0:\n bullets.remove(bullet)\n \n check_bullets_alien_collisions(ai_settings,screen,stats,sb,ship,aliens,bullets)\n\n\ndef check_bullets_alien_collisions(ai_settings,screen,stats,sb,ship,aliens,bullets):\n # Check for any bullets that have hit aliens\n #If so get rid of the bullet and the alien\n collisions = pygame.sprite.groupcollide(bullets,aliens,True,True)\n if collisions:\n for aliens in collisions.values():\n stats.score += ai_settings.alien_points * len(aliens)\n sb.prep_score()\n check_high_score(stats,sb)\n if len(aliens) == 0:\n #Destroy existing bullets and create new fleet.\n bullets.empty()\n ai_settings.increase_speed()\n stats.level += 1\n sb.prep_level() \n create_fleet(ai_settings,screen,ship,aliens)\n\ndef check_high_score(stats,sb):\n \"\"\"Check to see thers a new highscore\"\"\"\n if stats.score > stats.high_score:\n stats.high_score = stats.score\n sb.prep_high_score()\n\ndef fire_bullet(ai_settings,screen,ship,bullets):\n #Create a bullet and add it to the group\n if len(bullets) < ai_settings.bullets_allowed :\n new_bullet = Bullet(ai_settings,screen,ship)\n bullets.add(new_bullet)\n\n\ndef get_number_aliens_x(ai_settings,alien_width):\n \"\"\"Determine the number of alien's that fit in a row\"\"\"\n available_space_x = ai_settings.screen_width - 2 * alien_width\n number_aliens_x = int(available_space_x/(2*alien_width))\n return number_aliens_x\n\n\ndef get_number_rows(ai_settings,ship_height,alien_height):\n \"\"\"Determine the number of rows of aliens fleet on the screen\"\"\"\n available_space_y = (ai_settings.screen_height - \n 3*alien_height - ship_height)\n number_rows = int(available_space_y/(2*alien_height))\n return number_rows\n\ndef create_alien(ai_settings,screen,aliens,alien_number,row_number):\n #Create an alien and place it in arow\n alien = Alien(ai_settings,screen)\n alien_width = alien.rect.width\n alien.x = alien_width + 2 * alien_width * alien_number\n alien.rect.x = alien.x\n alien.rect.y = alien.rect.height + 2*alien.rect.height * row_number\n aliens.add(alien)\n\n\ndef create_fleet(ai_settings,screen,ship,aliens):\n \"\"\"Create a full fleet of aliens\"\"\"\n #Create a alien and find the number of aliens in a row\n #Spacing between aliens is one alien width\n alien = Alien(ai_settings,screen)\n number_aliens_x = get_number_aliens_x(ai_settings,alien.rect.width)\n number_rows = get_number_rows(ai_settings, ship.rect.height,\n alien.rect.height)\n\n #Create a fleets row of aliens\n for row_number in range(number_rows):\n for alien_number in range(number_aliens_x):\n create_alien(ai_settings,screen,aliens,alien_number,row_number)\n \ndef check_fleet_edges(ai_settings,aliens):\n \"\"\"Respond appropriatley if any aliens have reached a edge\"\"\"\n for alien in aliens:\n if alien.check_edges():\n change_fleet_direction(ai_settings,aliens)\n break\n\ndef change_fleet_direction(ai_settings,aliens):\n \"\"\"Drop the entire fleet and change the fleet direction\"\"\"\n for alien in aliens.sprites():\n alien.rect.y += ai_settings.fleet_drop_speed\n ai_settings.fleet_direction *= -1\n\ndef ship_hit(ai_settings,stats,screen,sb,ship,aliens,bullets):\n \"\"\"Respond to ship being hit by alien\"\"\"\n #Decrement ships_left\n if stats.ships_left > 0:\n stats.ships_left -= 1\n\n #Empty the list of aliens and bullets\n aliens.empty()\n bullets.empty()\n sb.prep_ships()\n\n #Crete a new fleet and ship\n create_fleet(ai_settings,screen,ship,aliens)\n ship.center_ship() \n\n #Pause\n sleep(0.5)\n \n else:\n stats.game_active = False\n pygame.mouse.set_visible(True)\n\ndef update_aliens(ai_settings,stats,screen,sb,ship,aliens,bullets):\n \"\"\"Update all aliens\"\"\"\n check_fleet_edges(ai_settings,aliens)\n aliens.update()\n\n #Look for alien - ship collisions\n if pygame.sprite.spritecollideany(ship,aliens):\n ship_hit(ai_settings,stats,screen,sb,ship,aliens,bullets)\n \n #Look for laien hititng the bottom of screen\n check_aliens_bottom(ai_settings,stats,screen,sb,ship,aliens,bullets)\n\ndef check_aliens_bottom(ai_settings,stats,screen,sb,ship,aliens,bullets):\n \"\"\"Check if any aliens have reached th ebottom of the screen\"\"\"\n screen_rect = screen.get_rect()\n for alien in aliens.sprites():\n if alien.rect.bottom >= screen_rect.bottom :\n #Treat this as ship got hit by alien\n ship_hit(ai_settings,stats,screen,sb,ship,aliens,bullets)\n break\n\n ","sub_path":"game_function.py","file_name":"game_function.py","file_ext":"py","file_size_in_byte":7666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"295812854","text":"from django.http import HttpResponse\nfrom django.shortcuts import redirect, get_object_or_404\n\nfrom cloud.models import Post, Comment\nfrom cloud.views.authentication import sign_in\n\n\ndef create_comment(request, post_pk):\n if not request.user.is_authenticated:\n return sign_in(request, msg=\"Пожалуйста, авторизуйтесь для добавления комментариев.\")\n\n if request.method != \"POST\":\n return HttpResponse(status=404)\n\n text = request.POST.get(\"comment_text\", None)\n\n if text is not None:\n post = Post.objects.get(pk=post_pk)\n new_comment = Comment(author=request.user, post=post, text=text)\n new_comment.save()\n\n return redirect('post_detail', pk=post_pk)\n\n\ndef delete_comment(request, comment_pk):\n if not request.user.is_authenticated:\n return sign_in(request, msg=\"Пожалуйста, авторизуйтесь для удаления комментариев.\")\n\n comment = get_object_or_404(Comment, pk=comment_pk)\n post_pk = comment.post.pk\n if request.user.is_staff or request.user == comment.author or request.user.is_superuser:\n comment.delete()\n\n return redirect('post_detail', pk=post_pk)\n\n\ndef get_comments(request, comment_pk):\n comments = Comment.objects.filter(pk=comment_pk)\n if comments.count() == 1:\n return redirect('post_detail', pk=comments.first.pk)\n else:\n return redirect('feed')\n","sub_path":"cloud/views/comment.py","file_name":"comment.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"123367133","text":"# Copyright 2017 Giorgia Fenoglio\n#\n# This file is part of NNsTaxonomicResponding.\n#\n# NNsTaxonomicResponding 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# NNsTaxonomicResponding 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 NNsTaxonomicResponding. If not, see .\n\nimport matplotlib\n#matplotlib.use('Agg')\n#from matplotlib import pyplot as plt\nimport numpy as np\nfrom colour import Color\nfrom .SOM import SOM\nimport os\nimport math\nimport random\nfrom numpy.linalg import norm\nfrom utils.constants import Constants\n\n\ndimN = 20\ndimM = 30\nnumIterations = 400\nN = 1000\nNxClass = 100\n\ndef restoreSOM(checkpoint_dir,lenExamples):\n \"\"\"\n restore the som which model is in the checkpoint_dir\n \"\"\"\n som = SOM(dimN, dimM, lenExamples, checkpoint_dir= checkpoint_dir, n_iterations=numIterations)\n\n loaded = som.restore_trained()\n if not loaded:\n raise ValueError(\"SOM in \"+checkpoint_dir+\" not trained yet\")\n\n return som\n\ndef getInputClass(className,fileInput):\n \"\"\"\n Read the input file and extract the names of the classes used\n \"\"\"\n f = open(fileInput,'r')\n inputC = None\n for l in f:\n lSplit = l.split(',')\n if className in lSplit[0]:\n print(lSplit[0])\n inputC = np.array(lSplit[1:]).astype(float)\n break\n return inputC\n\n\ndef getRandomInputClass(className,fileInput):\n \"\"\"\n Return a random input from the class className\n \"\"\"\n f = open(fileInput,'r')\n inputC = None\n for l in f:\n v = np.random.randint(4)\n if v == 3:\n lSplit = l.split(',')\n if className in lSplit[0]:\n print (lSplit[0])\n inputC = np.array(lSplit[1:]).astype(float)\n break\n f.close()\n return inputC\n\ndef getAllInputClass(className,fileInput):\n \"\"\"\n Return all the input of the class className\n \"\"\"\n f = open(fileInput,'r')\n inputC = []\n for l in f:\n lSplit = l.split(',')\n if str(className) in lSplit[0]:\n inputC.append(np.array(lSplit[1:]).astype(float))\n f.close()\n return inputC\n\ndef getAllInputClassAudio(className, file_path):\n f = open(file_path,'r')\n inputC = None\n for l in f:\n lSplit = l.split(',')\n if str(className) in lSplit[-1]:\n inputC = np.array(lSplit[1:-1]).astype(float)\n return inputC\n\ndef showSomActivations(activations,posActivations,count,title):\n \"\"\"\n Shows the SOM with its activations\n \"\"\"\n image_grid = np.zeros(shape=(dimN,dimM,3))\n plt.figure(count)\n plt.title(title)\n plt.imshow(image_grid)\n\n #normalization of the values of the activations\n maxA = max(activations)\n print(maxA)\n\n minA = min(activations)\n print(minA)\n\n a = 0\n b = 1\n\n for i in range(len(activations)):\n t = ((b-a)*(activations[i]-minA))/(maxA-minA) + a\n ## suppression:\n #if t < 0.6:\n # t = 0.0\n print(i)\n plt.text(posActivations[i][1], posActivations[i][0], '..', ha='center', va='center',\n bbox=dict(facecolor=str(t), alpha=1, lw=0))\n\n plt.draw()\n plt.show()\n return plt\n\ndef getAllInputs(fInput,lenExample):\n \"\"\"\n Read all the inputs from a file\n \"\"\"\n inputs = np.zeros(shape=(N,lenExample))\n nameInputs = list()\n\n with open(fInput, 'r') as inp:\n i = 0\n for line in inp:\n if len(line)>2:\n inputs[i] = (np.array(line.split(',')[1:])).astype(np.float)\n nameInputs.append((line.split(',')[0]).split('/')[5])\n i = i+1\n #nameInputs.sort()\n return [inputs,nameInputs]\n\ndef showSom(som,inputs,nameInputs,count,title):\n \"\"\"\n Shows the SOM highlighting the BMU of each input\n \"\"\"\n print('costruzione mappa '+title)\n mapped = som.map_vects(inputs)\n image_grid = np.zeros(shape=(20,30,3))\n plt.figure(count)\n plt.imshow(image_grid)\n plt.title(title)\n inputClass = nameInputs[0]\n\n #color generation\n # classColor = list()\n # for i in range(10):\n # c = Color(rgb=(random.random(), random.random(), random.random()))\n # classColor.append(str(c))\n classColor = ['white','red','blue','cyan','yellow','green','gray','brown','orange','magenta']\n\n iColor = 0\n\n lenExample = len(inputs[0])\n print(lenExample)\n prototipi = classPrototype(inputs,nameInputs)\n\n print(inputClass+' -- '+classColor[iColor])\n\n for i, m in enumerate(mapped):\n if nameInputs[i] != inputClass:\n inputClass = nameInputs[i]\n iColor = iColor + 1\n print(inputClass+' -- '+classColor[iColor])\n\n\n plt.text(m[1], m[0], '....', ha='center', va='center',\n bbox=dict(facecolor=classColor[iColor], alpha=0.5, lw=0))\n\n # for k in prototipi.keys():\n # [BMUi, BMUpos] = som.get_BMU(prototipi[k])\n # plt.text(BMUpos[1], BMUpos[0], str(k), ha='center', va='center',\n # bbox=dict(facecolor='white', alpha=0.9, lw=0))\n plt.draw()\n\n return plt\n\ndef printToFileCSV(prototipi,file):\n \"\"\"\n print the prototypes in a csv file\n \"\"\"\n\n f = open(file,'w')\n\n # stampa su file\n for k in prototipi.keys():\n st = k+','\n for v in prototipi[k]:\n st += str(v)+','\n st = st[0:-1]\n f.write(st+'\\n')\n\n f.close()\n\ndef classPrototype(inputs,nameInputs):\n \"\"\"\n extract for each class the prototype staring from the inputs of that class\n \"\"\"\n protClass = dict()\n nameS = list(set(nameInputs))\n nameS = np.sort(nameS)\n print(nameS)\n\n temp = np.array(inputs)\n\n i = 0\n for name in nameS:\n protClass[name] = np.mean(temp[i:i+NxClass][:],axis=0)\n i = i + NxClass\n\n #printToFileCSV(protClass,'./prototipiVisivi.csv')\n return protClass\n\ndef updatesynapses(S,classes,SOMU,SOMV,INPUTV,INPUTU,ite,maxIter):\n \"\"\"\n update all the synpases between the SOMU (auditory) and the SOMV (visual)\n based on the activation produced by the inputs INPUTV (visual) and INPUTU (auditory)\n \"\"\"\n print('updating synapses')\n # initializations of the synapses\n # S: matrix of size numberOfAuditoryNeurons X numberOfVisualNeurons\n\n if S == None:\n m = 1/math.sqrt(dimN*dimM*dimN*dimM)\n sd = 1/(1000*math.sqrt(dimN*dimM*dimN*dimM))\n S = np.random.normal(m,sd,(dimN*dimM,dimN*dimM))\n\n ATTIVAZIONIV = dict()\n ATTIVAZIONIU = dict()\n posAttivazioniU = dict()\n posAttivazioniV = dict()\n\n lambdaP = 5.0\n\n #normalization of the values\n\n a = 0.0\n b = 10.0\n\n count = 0\n\n for c in classes:\n print('updating for class '+str(c))\n\n print('generating visual activation')\n [ATTIVAZIONIV[c],posAttivazioniV[c]] = SOMV.get_activations(INPUTV[c])\n\n\n print('suppresion low values')\n maxA = np.amax(np.amax(ATTIVAZIONIV[c]))\n minA = np.amin(np.amin(ATTIVAZIONIV[c]))\n\n for i in range(len(ATTIVAZIONIV[c])):\n #print(type(ATTIVAZIONIV[c][i]))\n #float(10.0 * (ATTIVAZIONIV[c][i]-minA))\n #float(maxA-minA)\n ATTIVAZIONIV[c][i] = (float(10.0 * (ATTIVAZIONIV[c][i]-minA))/float(maxA-minA))\n\n #soppressione valori bassi\n #print(type(ATTIVAZIONIV[c][i]))\n\n if ATTIVAZIONIV[c][i] < 6.0:\n ATTIVAZIONIV[c][i] = 0.0\n\n #showSomActivations(ATTIVAZIONIV[c],posAttivazioniV[c],count,'visive per classe'+c)\n\n count += 1\n #uditiva\n print('generating auditory activation')\n [ATTIVAZIONIU[c],posAttivazioniU[c]] = SOMU.get_activations(INPUTU[c])\n\n print('suppresion low values')\n maxA = np.amax(np.amax(ATTIVAZIONIU[c]))\n minA = np.amin(np.amin(ATTIVAZIONIU[c]))\n for i in range(len(ATTIVAZIONIU[c])):\n ATTIVAZIONIU[c][i] = (float(10.0 * (ATTIVAZIONIU[c][i]-minA))/float(maxA-minA))\n #soppressione valori bassi\n if ATTIVAZIONIU[c][i] < 6.0:\n ATTIVAZIONIU[c][i] = 0.0\n #showSomActivations(ATTIVAZIONIU[c],posAttivazioniU[c],count,'uditive per classe'+c)\n\n count += 1\n\n print('updating synapses')\n for i in range(len(ATTIVAZIONIU[c])):\n #for j in range(len(ATTIVAZIONIV[c])):\n # S[i][j] = S[i][j] + 1 - math.exp(-lambdaP * ATTIVAZIONIU[c][i]*ATTIVAZIONIV[c][j])\n a = np.asarray(ATTIVAZIONIV[c], dtype=np.float32)\n S[i] = S[i] + np.ones(dimN*dimM) - np.exp(- lambdaP * ATTIVAZIONIU[c][i]*a)\n\n\n count = count + 3\n\n print('maxS ---->>> '+str(np.amax(np.amax(S))))\n print('minS ---->>> '+str(np.amin(np.amin(S))))\n\n if (ite == (maxIter-1)):\n tot = np.sum(np.sum(S))\n print('normalization')\n for i in range(len(S)):\n for j in range(len(S[i])):\n S[i][j] = S[i][j]/tot\n\n print('maxS ---->>> '+str(np.amax(np.amax(S))))\n print('minS ---->>> '+str(np.amin(np.amin(S))))\n plt.show()\n return S\n\n\ndef updatesynapsesPreLoad(S,classes,SOMU,SOMV,INPUTV,INPUTU,ite,maxIter):\n \"\"\"\n update all the synpases between the SOMU (auditory) and the SOMV (visual)\n based on the activation produced by the inputs INPUTV (visual) and INPUTU (auditory)\n The activations are already calculated\n \"\"\"\n print('updating synapses')\n # initializations of the synapses\n # S: matrix of size numberOfAuditoryNeurons X numberOfVisualNeurons\n\n if np.all(S == 0):\n m = 1/math.sqrt(dimN*dimM*dimN*dimM)\n sd = 1/(1000*math.sqrt(dimN*dimM*dimN*dimM))\n S = np.random.normal(m,sd,(dimN*dimM,dimN*dimM))\n\n lambdaP = 5.0\n\n # normalization\n\n a = 0.0\n b = 10.0\n\n count = 0\n\n for c in classes:\n\n # updating synapses\n for i in range(len(INPUTU[c])):\n #for j in range(len(INPUTV[c])):\n # S[i][j] = S[i][j] + 1 - math.exp(-lambdaP * ATTIVAZIONIU[c][i]*INPUTV[c][j])\n a = np.asarray(INPUTV[c], dtype=np.float32)\n S[i] = S[i] + np.ones(dimN*dimM) - np.exp(- lambdaP * INPUTU[c][i]*a)\n\n\n #print('maxS ---->>> '+str(np.amax(np.amax(S))))\n #print('minS ---->>> '+str(np.amin(np.amin(S))))\n\n tot = np.sum(np.sum(S))\n #print('normalization')\n if ite == maxIter:\n S = S/tot\n\n #print('maxS ---->>> '+str(np.amax(np.amax(S))))\n #print('minS ---->>> '+str(np.amin(np.amin(S))))\n\n return S\n\ndef savesynapses(S,outputFile):\n \"\"\"\n save the synapses on the outputFile\n \"\"\"\n output = open(outputFile,'w')\n\n for i in range(len(S)):\n for j in range(len(S[i])):\n output.write(str(S[i][j])+',')\n output.write(';\\n')\n\n output.close()\n\ndef restoresynapses():\n \"\"\"\n restore the synapses from a specific file\n \"\"\"\n outputFile = './sinapses.csv'\n try:\n output = open(outputFile,'r')\n except:\n return None\n\n m = 1/math.sqrt(dimN*dimM*dimN*dimM)\n sd = 1/(1000*math.sqrt(dimN*dimM*dimN*dimM))\n S = np.random.normal(m,sd,(dimN*dimM,dimN*dimM))\n i = 0\n for l in output:\n j = 0\n lSplit = l.split(',')\n for v in lSplit:\n if (len(v)>0) and (not ';' in v):\n S[i][j] = float(v)\n j = j+1\n i = i+1\n\n return S\n\ndef propagateActivations(UV,bmu1,S):\n \"\"\"\n propagate the activations of the bmus from a SOM to the other\n \"\"\"\n # locAct = list()\n # for i in range(0,dimN-1):\n # for j in range(0,dimM-1):\n # locAct.append([i,j])\n\n act = list()\n locAct = list()\n m = 0\n for i in range(0,dimN-1):\n for j in range(0,dimM-1):\n if UV == 'U':\n act.append(S[bmu1][dimM*i+j])\n locAct.append([i,j])\n if S[bmu1][dimM*i+j] > S[bmu1][m]:\n m = dimM*i+j\n else:\n act.append(S[dimM*i+j][bmu1])\n locAct.append([i,j])\n if S[dimM*i+j][bmu1] > S[m][bmu1]:\n m = dimM*i+j\n\n #showSomActivations(act,locAct,100,'attivazione propagata')\n return m\n\ndef propagateActivationsAll(UV,act2,S):\n \"\"\"\n propagate the activations of all the neurons from a SOM to the other\n \"\"\"\n # locAct = list()\n # for i in range(dimN):\n # for j in range(dimM):\n # locAct.append([i,j])\n\n act = list()\n #locAct = list()\n #m = 0\n\n #act = sum(S[:][:] * act2)\n #print(len(t))\n\n act = np.dot(act2,S)\n\n # for i in range(dimM*dimN):\n # t = sum(S[i][:] * act2)\n # act.append(t)\n\n\n # locAct.append([i,j])\n\n # for i in range(0,dimN-1):\n # for j in range(0,dimM-1):\n # if UV == 'U':\n # t = 0\n # for i2 in range(0,dimN-1):\n # for j2 in range(0,dimM-1):\n # t += S[dimM*i2+j2][dimM*i+j]*act2[dimM*i2+j2]\n # act.append(t)\n # locAct.append([i,j])\n\n # else:\n # ## medium old\n # # t = 0\n # # for k in range(dimN*dimM):\n # # t += S[dimM*i+j][k] * act2[k]\n\n # ## new\n # t = sum(S[dimM*i+j][:] * act2)\n\n # ## old\n # # for i2 in range(0,dimN-1):\n # # for j2 in range(0,dimM-1):\n # # t += S[dimM*i+j][dimM*i2+j2]*act2[dimM*i2+j2]\n\n # act.append(t)\n # locAct.append([i,j])\n\n m = np.argmax(act)\n #m = act.index(ml)\n #showSomActivations(act,locAct,100,'attivazione propagata')\n\n return m\n\ndef showActivationsS(c,S,count):\n \"\"\"\n propagate the activation and show the consequent som\n \"\"\"\n locAct = list()\n for i in range(0,dimN-1):\n for j in range(0,dimM-1):\n locAct.append([i,j])\n\n #print(locAct)\n\n act = list()\n for i in range(0,dimN-1):\n for j in range(0,dimM-1):\n act.append(S[dimM*i+j])\n print(act)\n\n showSomActivations(act,locAct,count,'activations propagated with class '+c)\n\n\ndef distanceIntraClass(SOM, inputs, nameInputs):\n \"\"\"\n calculate the intra-cluster and inter-cluster distances based on a specific som and a set of inputs;\n the clusters are the set of bmus that belong to the same class of objects\n \"\"\"\n print('- extraction bmus -')\n mapped = SOM.map_vects(inputs)\n\n positions = dict()\n for i, m in enumerate(mapped):\n if nameInputs[i] in positions:\n positions[nameInputs[i]].append([m[1],m[0]])\n else:\n positions[nameInputs[i]] = [[m[1],m[0]]]\n\n\n distancesIntra = dict()\n print('- intra-cluster distance - ')\n posKey = positions.keys()\n posKey.sort()\n for c in posKey:\n d = 0\n count = 0\n for i in positions[c]:\n i1 = positions[c].index(i)\n for j in positions[c][i1+1:]:\n d += math.sqrt(( (j[0]-i[0])**2 ) + ((j[1]-i[1])**2 ))\n count += 1\n\n distancesIntra[c] = d / count\n\n print('--- '+c+' -> '+str(distancesIntra[c]))\n\n\n allPositions = []\n print('- inter-cluster distance :')\n for c in posKey:\n for p in positions[c]:\n allPositions.append(p)\n d = 0\n count = 0\n for i in allPositions:\n i1 = allPositions.index(i)\n for j in allPositions[i1+1:]:\n d += math.sqrt(( (j[0]-i[0])**2 ) + ((j[1]-i[1])**2 ))\n count += 1\n\n distancesExtra = d / count\n\n\n print('- ratio between the intra and inter cluster distances')\n for c in posKey:\n print(str(c) + ';' + str(distancesIntra[c]/distancesExtra))\n\n\n\n\n\ndef getBMUUPositions(som_path):\n \"\"\"\n get the positions of the BMU in a som starting from a set of inputs\n \"\"\"\n classes = list(range(0,10))\n\n inputs = []\n for c in classes:\n inputs.append(getRandomInputClass(c,os.path.join(Constants.DATA_FOLDER, 'input10classes', 'auditoryInput.csv')))\n\n SOMU = restoreSOM(som_path,10)\n\n mapped = SOMU.map_vects(inputs)\n\n out = np.zeros(shape=(10,2))\n\n for i, m in enumerate(mapped):\n out[i] = [m[0],m[1]]\n\n return out\n\ndef getActivationsOnce(SOMV,SOMU,inputsV,inputsU):\n \"\"\"\n calculate the activations on the two soms starting from two sets of inputs\n \"\"\"\n activations = dict()\n activations['U'] = dict()\n activations['V'] = dict()\n for c in inputsU.keys():\n j = 0\n activations['U'][c] = dict()\n for u in inputsU[c]:\n activations['U'][c][j] = SOMU.get_activations(u)\n maxA = np.amax(np.amax(activations['U'][c][j][0]))\n minA = np.amin(np.amin(activations['U'][c][j][0]))\n for i in range(len(activations['U'][c][j][0])):\n activations['U'][c][j][0][i] = (float(10.0 * (activations['U'][c][j][0][i]-minA))/float(maxA-minA))\n if activations['U'][c][j][0][i] < 6.0:\n activations['U'][c][j][0][i] = 0.0\n j += 1\n for c in inputsV.keys():\n j = 0\n activations['V'][c] = dict()\n for v in inputsV[c]:\n activations['V'][c][j] = SOMV.get_activations(v)\n maxA = np.amax(np.amax(activations['V'][c][j][0]))\n minA = np.amin(np.amin(activations['V'][c][j][0]))\n for i in range(len(activations['V'][c][j][0])):\n activations['V'][c][j][0][i] = (float(10.0 * (activations['V'][c][j][0][i]-minA))/float(maxA-minA))\n if activations['V'][c][j][0][i] < 6.0:\n activations['V'][c][j][0][i] = 0.0\n j += 1\n\n return activations\n\ndef getBMUonce(SOMV,inputsV):\n \"\"\"\n calculate the bmus on the a SOM starting from a set of inputs\n \"\"\"\n print('recupero bmus')\n bmus = dict()\n for c in inputsV.keys():\n print('classe '+str(c))\n bmus[c] = dict()\n for i in range(len(inputsV[c])):\n bmus[c][i] = SOMV.get_BMU(inputsV[c][i])[0]\n\n return bmus\n\n\ndef iterativeTraining(img_som_path, audio_som_path):\n \"\"\"\n calculate the taxonomic factor increasing the number of couples\n used for the training of the hebbian connections\n \"\"\"\n classes = list(range(0,10))\n\n SOMV = restoreSOM(img_som_path,2048)\n SOMU = restoreSOM(audio_som_path,1000)\n\n INPUTV = dict()\n INPUTU = dict()\n tinputU = dict()\n tinputV = dict()\n\n for c in classes:\n INPUTV[c] = getAllInputClass(c, os.path.join(Constants.DATA_FOLDER, '10classes', 'VisualInputTestSet.csv'))\n INPUTU[c] = getAllInputClassAudio(c, os.path.join(Constants.DATA_FOLDER, '10classes', 'audio_prototypes.csv'))\n\n print('getActivationsOnce')\n activations = getActivationsOnce(SOMV,SOMU,INPUTV,INPUTU)\n\n print('getBMUonce')\n bmus = getBMUonce(SOMV,INPUTV)\n\n print('getBMUUPositions')\n # commenting this out because it does not seem to be used further in this function\n #posClassesU = getBMUUPositions()\n\n niterRes = []\n for ni in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]:\n corrects = []\n niter = ni\n\n for k in range(1000):\n #use 1000 random training set for each number of couples\n print('iteration -> '+str(k))\n S = np.zeros((10, 60))\n for i in range(niter):\n i0 = np.random.randint(100)\n tinputV[classes[0]] = activations['V'][classes[0]][i0][0]\n i1 = np.random.randint(100)\n tinputV[classes[1]] = activations['V'][classes[1]][i1][0]\n i2 = np.random.randint(100)\n tinputV[classes[2]] = activations['V'][classes[2]][i2][0]\n i3 = np.random.randint(100)\n tinputV[classes[3]] = activations['V'][classes[3]][i3][0]\n i4 = np.random.randint(100)\n tinputV[classes[4]] = activations['V'][classes[4]][i4][0]\n i5 = np.random.randint(100)\n tinputV[classes[5]] = activations['V'][classes[5]][i5][0]\n i6 = np.random.randint(100)\n tinputV[classes[6]] = activations['V'][classes[6]][i6][0]\n i7 = np.random.randint(100)\n tinputV[classes[7]] = activations['V'][classes[7]][i7][0]\n i8 = np.random.randint(100)\n tinputV[classes[8]] = activations['V'][classes[8]][i8][0]\n i9 = np.random.randint(100)\n tinputV[classes[9]] = activations['V'][classes[9]][i9][0]\n for c in classes:\n random_sample = np.random.randint(len(list(INPUTU)))\n tinputU[c] = activations['U'][c][random_sample][0]\n\n S = updatesynapsesPreLoad(S,classes,SOMU,SOMV,tinputV,tinputU,i,niter-1)\n\n #print(str(i0)+'--'+str(i1)+'--'+str(i2)+'--'+str(i3)+'--'+str(i4)+'--'+\n # str(i5)+'--'+str(i6)+'--'+str(i7)+'--'+str(i8)+'--'+str(i9)+'--')\n\n S = np.matrix.transpose(S)\n correct = 0\n #given the synapses built, I evaluate the performance of the model propagating the activation\n # of each visual input to the auditory SOM, finding the BMU and the nearer auditory prototype BMU.\n print('test ...')\n for cl in classes:\n #print('test with class '+cl)\n for j in range(100):\n #bmuV = bmus[cl][j]\n\n #bmuU = propagateActivations('V',bmuV,S)\n\n act2 = activations['V'][cl][j]\n #print(act2)\n\n bmuU = propagateActivationsAll('V',act2[0],S)\n\n # correct if: the nearer auditory prototype is associate to the input\n\n # r = bmuU/dimM\n # c = bmuU%dimM\n\n # dist = np.array([])\n # for i in range(10):\n # dist = np.append(dist,math.hypot(posClassesU[i][0] - r, posClassesU[i][1] - c ))\n\n # #print(dist)\n\n # if cl == classes[np.argmin(dist)]:\n # correct += 1\n\n #correct if: the bmu of the propagated activation fall into an area associated with the class of the input\n\n actTU = np.array([])\n for cu in classes:\n actTU = np.append(actTU,activations['U'][cu][0][0][bmuU])\n\n if cl == classes[np.argmax(actTU)]:\n correct += 1\n\n\n corrects.append(correct)\n #print(corrects)\n\n print(corrects)\n print(sum(corrects) / float(len(corrects)))\n niterRes.append(sum(corrects) / float(len(corrects)))\n print('--------')\n print(niterRes)\n\n\n\n\n\ndef testWordLearning():\n \"\"\"\n Test the taxonomic factor of the model increasing the number of couples used for each class.\n \"\"\"\n classesIn = open('./utility/labels10classes.txt','r')\n classes = []\n for c in classesIn:\n classes.append(c[:-1])\n\n classes.sort()\n\n modelDirSomV = './VisualModel10classes/'\n modelDirSomU = './AuditoryModel10classes/'\n\n SOMV = restoreSOM(modelDirSomV,2048)\n SOMU = restoreSOM(modelDirSomU,10)\n\n\n\n S = restoresynapses()\n maxIter = 10\n if S == None:\n for i in range(0,maxIter):\n INPUTV = dict()\n INPUTU = dict()\n for c in classes:\n INPUTV[c] = getRandomInputClass(c,'./input10classes/VisualInputTestSet.csv')\n INPUTU[c] = getRandomInputClass(c,'./input10classes/auditoryInput.csv')\n\n S = updatesynapses(S,classes,SOMU,SOMV,INPUTV,INPUTU,i,maxIter)\n print('------- '+str(i)+'--------'+str(maxIter))\n\n savesynapses(S,'./sinapses.csv')\n\n ###################################\n # TEST\n ###################################\n\n # print('Production test')\n # inputTestU = getRandomInputClass('fishes','./input10classes/auditoryInput.csv')\n\n # [actU,locActU] = SOMU.get_activations(inputTestU)\n\n # [bmuU,locBmuU] = SOMU.get_BMU(inputTestU)\n\n # bmuV = propagateActivations('U',bmuU,S)\n\n # #bmuV = np.where(S[bmuU,:] == max(S[bmuU,:]))\n # #bmuV = bmuV[0][0]\n\n # for r in range(dimN):\n # Fbreak = False\n # for c in range(dimM):\n # if dimM*r + c == bmuV:\n # Fbreak = True\n # break\n # if Fbreak == True:\n # break\n\n # print(r,c)\n\n # # visualization\n # [iVall,iVallName] = getAllInputs('input10classes/VisualInputTestSet',2048)\n # [iUall,iUallName] = getAllInputs('input10classes/auditoryInput.csv',N/NxClass)\n # pltU = showSom(SOMU,iUall,iUallName,20,'Uditiva')\n\n # pltU.text(locBmuU[1], locBmuU[0], 'UUU', ha='center', va='center',\n # bbox=dict(facecolor='white', alpha=1, lw=0))\n\n # pluV = showSom(SOMV,iVall,iVallName,21,'Visiva')\n\n # pluV.text(c, r, 'VVV', ha='center', va='center',\n # bbox=dict(facecolor='white', alpha=1, lw=0))\n\n\n # pluV.show()\n # pluV.show()\n # plt.show()\n\n ###################################\n # TEST\n ###################################\n\n print('Comprehension test of the class bird')\n inputTestV = getRandomInputClass('birds','./input10classes/VisualInputTestSet.csv')\n\n [bmuV,locBmuV] = SOMV.get_BMU(inputTestV)\n\n bmuU = propagateActivations('V',bmuV,S)\n\n for r in range(dimN):\n Fbreak = False\n for c in range(dimM):\n if dimM*r + c == bmuU:\n Fbreak = True\n break\n if Fbreak == True:\n break\n\n print(r,c)\n\n # visualization\n print('get visive inputs')\n [iVall,iVallName] = getAllInputs('./input10classes/VisualInputTestSet.csv',2048)\n print('get auditory inputs')\n [iUall,iUallName] = getAllInputs('./input10classes/auditoryInput.csv',10)\n pltU = showSom(SOMU,iUall,iUallName,20,'Uditiva')\n\n pltU.text(c, r, 'UUU', ha='center', va='center',\n bbox=dict(facecolor='white', alpha=1, lw=0))\n\n pluV = showSom(SOMV,iVall,iVallName,21,'Visiva')\n\n pluV.text(locBmuV[1], locBmuV[0], 'VVV', ha='center', va='center',\n bbox=dict(facecolor='white', alpha=1, lw=0))\n\n pltU.show()\n pluV.show()\n\n plt.show()\n\n\n\nif __name__ == '__main__':\n\n iterativeTraining()\n","sub_path":"models/som/wordLearningTest.py","file_name":"wordLearningTest.py","file_ext":"py","file_size_in_byte":26629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"568833588","text":"from bs4 import BeautifulSoup\n\n\ndef text_results(ResultSet):\n text_list =[]\n for el in ResultSet:\n text_list.append(el.text.strip())\n return text_list\n\nclass DocketEvent(object):\n def __init__(self):\n pass\n\n\ndef docket(oscn_html):\n events = []\n soup = BeautifulSoup(oscn_html, 'html.parser')\n docket_table = soup.find('table', 'docketlist')\n thead = docket_table.find('thead').find_all('th')\n rows = docket_table.find('tbody').find_all('tr')\n headings = text_results(thead)\n\n for row in rows:\n cells=row.find_all('td')\n values = text_results(cells)\n event = DocketEvent()\n\n for idx, value in enumerate(values):\n setattr(event, headings[idx], value)\n events.append(event)\n # clean up blank dates\n current_date = events[0].Date\n for e in events:\n if e.Date:\n current_date = e.Date\n else:\n e.Date = current_date\n\n return events\n","sub_path":"oscn/parse/docket.py","file_name":"docket.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"155710896","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport behavior_tree\n\n# 要最適化\n\n\nclass SampleEnemy(object):\n\n def __init__(self):\n self.behavior_tree = behavior_tree.BehaviorTree()\n\n def enemy_conflict_act(self):\n action_list = self.behavior_tree.get_conflict_behavior()\n print(\"conflict\", action_list)\n # return\n\n def enemy_effort_act(self):\n action_list = self.behavior_tree.get_effort_behavior()\n print(\"effort\", action_list)\n\n\nif __name__ == \"__main__\":\n enemy = SampleEnemy()\n for i in range(1, 10):\n enemy.enemy_conflict_act()\n enemy.enemy_effort_act()\n","sub_path":"behavior/sample_enemy.py","file_name":"sample_enemy.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"609637799","text":"from bs4 import BeautifulSoup\nfrom pandas.core.algorithms import mode\nimport requests \nimport pandas as pd\nimport os\n\n#subject : KISA에서 IP 주소 대역 제공되는 국가 크롤링\n#2021-07-26\n\n#한국인터넷 정보센터(KISA)\ntarget_url = \"https://xn--3e0bx5euxnjje69i70af08bea817g.xn--3e0b707e/jsp/statboard/IPAS/ovrse/natal/IPaddrBandCurrent.jsp\"\n\ndef get_nation_list():\n \n html = requests.get(target_url)\n html_bs = BeautifulSoup(html.text, 'html.parser')\n\n selector = html_bs.find('select', id='nationCode')\n tags = selector.find_all('option')\n nation_list = []\n\n for tag in tags:\n name = tag.get_text()\n code= tag['value']\n nation_list.append(name)\n export_ip_list(code)\n return nation_list\n\ndef get_ip_list(code):\n url = target_url +\"?nationCode1=\"+code\n html = requests.get(url)\n html_bs = BeautifulSoup(html.text, 'html.parser')\n selector = html_bs.find('table')\n tags = selector.find('tbody').find_all('tr')\n ip_list = []\n for tag in tags:\n name = tag.get_text()\n ip_list.append(name)\n return ip_list\n\ndef export_ip_list(code):\n #title = \"global_ip_list.xlsx\"\n url = target_url +\"?nationCode1=\"+code\n #table = pd.read_html(url)[0]\n print(pd.read_html(url)[0])\n #db = pd.DataFrame(table);\n #if not os.path.exists(title):\n # with pd.ExcelWriter(title, mode='w', engine='openpyxl') as writer:\n # db.to_excel(writer, index=False)\n #else:\n # with pd.ExcelWriter(title, mode='a', engine='openpyxl') as writer:\n # db.to_excel(writer, index=False, header=False)\n\n \n\n\nif __name__ == \"__main__\":\n get_nation_list() ","sub_path":"python/practice-crawling/kisa_ip01.py","file_name":"kisa_ip01.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"220266665","text":"from collections import Counter\nimport itertools\n\ndef main():\n\n #All Words\n infile = open(\"ulysses.txt\",\"r\")\n outfileA = open(\"allwords.txt\", \"w\")\n wordList = []\n for line in infile:\n line.strip()\n str1 = \"\"\n for character in line:\n if character.isalpha()==False:\n if ord(character) == 32:\n str1 += character\n else:\n continue\n else:\n str1 += character.lower()\n tempList = str1.split()\n wordList += tempList\n for word in wordList:\n outfileA.write(word + \"\\n\")\n outfileA.close()\n\n #Unique Words\n outfileA = open('allwords.txt', 'r')\n outfileU = open('uniquewords.txt', 'w')\n wordlist = []\n for word in outfileA:\n if word not in wordlist:\n wordlist.append(word)\n for word in wordlist:\n outfileU.write(word)\n outfileA.close()\n\n #Word Freq\n outfileA = open('allwords.txt', 'r')\n outfileF = open(\"frequency.txt\", \"w\")\n WordList = []\n for word in outfileA:\n word.strip('\\n')\n WordList.append(word)\n dict1 = Counter(WordList)\n dict2 = [(k, len(list(v))) for k, v in itertools.groupby(sorted(dict1.values()))]\n string = str(dict2)\n for ch in ['[', ']', '(', ')', ',',]:\n if ch in string:\n string = string.replace(ch, '')\n\n string = string.split(' ')\n string = \"\\n\".join([\":\".join(string[i:i+2]) for i in range(0,len(string),2)])\n\n for line in string:\n outfileF.write(line)\n\n infile.close()\n outfileA.close()\n outfileU.close()\n outfileF.close()\n\nmain()\n","sub_path":"extract_words.py","file_name":"extract_words.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"121481993","text":"#เช็คราคาจาก bX bitCoin\n#Copy from : https://github.com/line/line-bot-sdk-python/blob/master/examples/flask-echo/app_with_handler.py\n#ตัวนี้เป็น File starter\nimport os\nimport sys\nfrom argparse import ArgumentParser\n\nfrom flask import Flask, request, abort\nfrom linebot import (\n LineBotApi, WebhookHandler\n)\nfrom linebot.exceptions import (\n InvalidSignatureError\n)\nfrom linebot.models import * ####( MessageEvent, TextMessage, TextSendMessage)\n\napp = Flask(__name__)\n\n# get channel_secret and channel_access_token from your environment variable\nchannel_secret = 'e9300087d149c94cb509ff65b7e3dd33' ##get from line console\nchannel_access_token = 'bQ2oBx3p0GQEB0FkLr1aitV22EdUieOwFvs5RDTNJB9cYGc0/q9U2LYcFfhYHpLt6HCNUqFRtwBBTneG1GAQQjyVgaeCbs2wI3oopKazBGdVbnG3imnlH6CAM/eDvTuRppJ5IY8qvRPhPX3EdWSLggdB04t89/1O/w1cDnyilFU='\n\nline_bot_api = LineBotApi(channel_access_token) #ตัวส่ง api \nhandler = WebhookHandler(channel_secret)\n\n###แก้ route +channel-secret +access-toker \n@app.route(\"/webhook\", methods=['POST']) ###old code ==> (\"/callback\", methods=['POST'])\ndef callback():\n # get X-Line-Signature header value\n signature = request.headers['X-Line-Signature'] #บ่งบอกว่า มาจาก line จริงป่ะ \n\n # get request body as text\n body = request.get_data(as_text=True) \n app.logger.info(\"Request body: \" + body)\n\n # handle webhook body\n try:\n handler.handle(body, signature) #body ที่ line ส่งมา เราจะสร้าง specialist ให้รู้ว่ามันเป็น text,audio,sticker หรืออะไร\n except InvalidSignatureError:\n abort(400)\n\n return 'OK'\n\n@handler.add(MessageEvent,message=TextMessage)\ndef message_text(event): #event คือได้กลับมาจาก handler\n ## Function reply_token \n\n print(event.reply_token)\n print(event.message.text)\n\n\n Reply_token = event.reply_token ##Reply token\n text_fromUser = event.message.text ##ข้อความจาก user \n\n if 'เช็คราคา' in text_fromUser:\n ##from Resource.bxAPI import GetBxPrice\n from bxAPI import GetBxPrice\n \n from random import randint\n num = randint(1,10)\n data = GetBxPrice(num) #เก็บ จำนวนข้อมูล ที่จะ display\n \n from flexmessage import setbubble , setCarousel \n\n flex = setCarousel(data) #type dictionary ครือออ flex ที่มี carousel=1 /bubble=5\n\n from reply import SetMenuMessage_Object ,send_flex\n\n flex = SetMenuMessage_Object(flex)\n send_flex(Reply_token ,file_data = flex ,bot_access_key = channel_access_token)\n\n else:\n text_list = [\n 'ฉันไม่เข้าใจที่คุณพูดค่ะ กรุณาลองถามใหม่ค่ะ',\n 'ไม่เข้าใจจริงๆๆๆ ลองใหม่นะ',\n 'ขอโทษอ่ะ โทรคุยละกัน งงจริงๆ'\n ]\n\n from random import choice\n\n text_data = choice(text_list)\n\n text = TextSendMessage(text=text_data)\n\n line_bot_api.reply_message(Reply_token,text)\n\n\n\n\n@handler.add(FollowEvent)\ndef RegisRichmenu(event):\n userid = event.source.user_id\n disname = line_bot_api.get_profile(user_id=userid).display_name\n\n button1 = QuickReplyButton(action=MessageAction(label='เช็คราคา',text='เช็คราคา'))\n button2 = QuickReplyButton(action=MessageAction(label='เช็คข่าวสาร',text='เช็คข่าวสาร'))\n qbtn = QuickReply(items={button1,button2})\n #text message object\n text = TextSendMessage(text='ยินดีที่ได้รู้จัก {} แชทบอทเอง'.format(disname))\n text2 = TextSendMessage(text='กรุณาเลือกเมนูที่ท่านต้องการ ',quick_reply=qbtn )\n ### link richmenu\n line_bot_api.link_rich_menu_to_user(userid,'richmenu-422bbc07f5bf346303652863de5d0d5d') #*********>>>>>>เอา result จากการ run richmenu.py \n #####reply message wien user follow \n line_bot_api.reply_message(event.reply_token,messages={text,text2})\n\n#if __name__ == \"__main__\":\n# app.run(port=200)\n\n","sub_path":"app_ver2.py","file_name":"app_ver2.py","file_ext":"py","file_size_in_byte":4463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"328731921","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n'''\n Author: kun.wang\n Create: 2013-01-21\n'''\nimport os, sys, string\nimport socket\nimport json\n\n\nclass MBridge:\n \"\"\"\n you need to open maya command port.\n import maya.cmds as mc\n mc.commandPort(n = \"localhost:18810\", stp = \"python\")\n \"\"\"\n server = \"localhost\"\n port = 18810\n connection = None\n connected = False\n\n @staticmethod\n def setServer(server, port):\n MBridge.server = server\n MBridge.port = port\n\n @staticmethod\n def send(command):\n MBridge.connection.send(command)\n date = MBridge.connection.recv(4096)\n return date\n\n @staticmethod\n def connect():\n try:\n MBridge.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n MBridge.connection.connect((MBridge.server, MBridge.port))\n MBridge.connected = True\n return True\n except:\n MBridge.connection = None\n MBridge.connected = True\n return False\n\n @staticmethod\n def disConnect():\n MBridge.connection.close()\n MBridge.connection = None\n MBridge.connected = False\n\n @staticmethod\n def isConnect():\n if MBridge.connected:\n return True\n else:\n return False","sub_path":"cgPipeline/old/Mango0.3/mtools.py","file_name":"mtools.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"558602728","text":"def solution(A):\n if len(A) <= 1:\n return 0\n\n result = 1\n ordered = sorted(A)\n\n iterations = 0\n\n for i in ordered:\n if iterations > 0:\n if i - 1 != ordered[iterations - 1]:\n result = 0\n\n iterations = iterations + 1 \n\n return result\n\n#solution([4, 1, 3, 2])\n#solution([4, 1, 3])\nsolution([3])","sub_path":"4 - permcheck.py","file_name":"4 - permcheck.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"278462756","text":"import numpy as np\nimport perfplot\nimport gc\n\n# OpenAI/Baselines: https://github.com/openai/baselines\n# Requires TensorFlow 1.14 instead of 2\nfrom baselines.deepq.replay_buffer import (ReplayBuffer as bRB,\n PrioritizedReplayBuffer as bPRB)\n\n# Ray/RLlib: https://github.com/ray-project/ray\n# Requires Pandas, even though wich is not in `install_requires`\nfrom ray.rllib.optimizers.replay_buffer import (ReplayBuffer as rRB,\n PrioritizedReplayBuffer as rPRB)\n\n# Chainer/ChainerRL: https://github.com/chainer/chainerrl\nfrom chainerrl.replay_buffers import (ReplayBuffer as cRB,\n PrioritizedReplayBuffer as cPRB)\n\nfrom cpprb import (ReplayBuffer as RB,\n PrioritizedReplayBuffer as PRB)\n\n\n# Configulation\nbuffer_size = 2**12\n\nobs_shape = 15\nact_shape = 3\n\nalpha = 0.4\nbeta = 0.4\n\nenv_dict = {\"obs\": {\"shape\": obs_shape},\n \"act\": {\"shape\": act_shape},\n \"next_obs\": {\"shape\": obs_shape},\n \"rew\": {},\n \"done\": {}}\n\n\n# Initialize Replay Buffer\nbrb = bRB(buffer_size)\nrrb = rRB(buffer_size)\ncrb = cRB(buffer_size)\nrb = RB(buffer_size,env_dict)\n\n\n# Initialize Prioritized Replay Buffer\nbprb = bPRB(buffer_size,alpha=alpha)\nrprb = rPRB(buffer_size,alpha=alpha)\ncprb = cPRB(buffer_size,alpha=alpha,beta0=beta,betasteps=None)\nprb = PRB(buffer_size,env_dict,alpha=alpha)\n\n\n\n# Helper Function\ndef env(n):\n e = {\"obs\": np.ones((n,obs_shape)),\n \"act\": np.zeros((n,act_shape)),\n \"next_obs\": np.ones((n,obs_shape)),\n \"rew\": np.zeros(n),\n \"done\": np.zeros(n)}\n return e\n\ndef add_b(_rb):\n \"\"\" Add for Baselines\n \"\"\"\n def add(e):\n for i in range(e[\"obs\"].shape[0]):\n _rb.add(obs_t=e[\"obs\"][i],\n action=e[\"act\"][i],\n reward=e[\"rew\"][i],\n obs_tp1=e[\"next_obs\"][i],\n done=e[\"done\"][i])\n return add\n\ndef add_r(_rb):\n \"\"\" Add for RLlib\n\n Notes\n -----\n Even `ReplayBuffer` requires `weight` parameter (but don't use it).\n \"\"\"\n def add(e):\n for i in range(e[\"obs\"].shape[0]):\n _rb.add(obs_t=e[\"obs\"][i],\n action=e[\"act\"][i],\n reward=e[\"rew\"][i],\n obs_tp1=e[\"next_obs\"][i],\n done=e[\"done\"][i],\n weight=0.5)\n return add\n\ndef add_c(_rb):\n \"\"\" Add for ChainerRL\n \"\"\"\n def add(e):\n for i in range(e[\"obs\"].shape[0]):\n _rb.append(state=e[\"obs\"][i],\n action=e[\"act\"][i],\n reward=e[\"rew\"][i],\n next_state=e[\"next_obs\"][i],\n is_state_terminal=e[\"done\"][i])\n return add\n\ndef sample_c(_rb):\n \"\"\" Force sample from ChainerRL PrioritizedReplayBuffer\n \"\"\"\n def sample(n):\n _rb.memory.wait_priority_after_sampling = False\n return _rb.sample(n)\n\n return sample\n\n\n# ReplayBuffer.add\nperfplot.save(filename=\"ReplayBuffer_add.png\",\n setup = env,\n time_unit=\"ms\",\n kernels = [add_b(brb),\n add_r(rrb),\n add_c(crb),\n lambda e: rb.add(**e)],\n labels = [\"OpenAI/Baselines\",\"Ray/RLlib\",\"Chainer/ChainerRL\",\"cpprb\"],\n n_range = [n for n in range(1,102,10)],\n xlabel = \"Step size added at once\",\n title = \"Replay Buffer Add Speed\",\n logx = False,\n logy = False,\n equality_check = None)\n\n\n# Fill Buffers\nfor _ in range(buffer_size):\n o = np.random.rand(obs_shape) # [0,1)\n a = np.random.rand(act_shape)\n r = np.random.rand(1)\n d = np.random.randint(2) # [0,2) == 0 or 1\n brb.add(obs_t=o,action=a,reward=r,obs_tp1=o,done=d)\n rrb.add(obs_t=o,action=a,reward=r,obs_tp1=o,done=d,weight=0.5)\n crb.append(state=o,action=a,reward=r,next_state=o,is_state_terminal=d)\n rb.add(obs=o,act=a,rew=r,next_obs=o,done=d)\n\n\n# ReplayBuffer.sample\nperfplot.save(filename=\"ReplayBuffer_sample.png\",\n setup = lambda n: n,\n time_unit=\"ms\",\n kernels = [brb.sample,\n rrb.sample,\n crb.sample,\n rb.sample],\n labels = [\"OpenAI/Baselines\",\n \"Ray/RLlib\",\n \"Chainer/ChainerRL\",\n \"cpprb\"],\n n_range = [2**n for n in range(1,8)],\n xlabel = \"Batch size\",\n title = \"Replay Buffer Sample Speed\",\n logx = False,\n logy = False,\n equality_check=None)\n\n\n# PrioritizedReplayBuffer.add\nperfplot.save(filename=\"PrioritizedReplayBuffer_add.png\",\n time_unit=\"ms\",\n setup = env,\n kernels = [add_b(bprb),\n add_r(rprb),\n add_c(cprb),\n lambda e: prb.add(**e)],\n labels = [\"OpenAI/Baselines\",\n \"Ray/RLlib\",\n \"Chainer/ChainerRL\",\n \"cpprb\"],\n n_range = [n for n in range(1,102,10)],\n xlabel = \"Step size added at once\",\n title = \"Prioritized Replay Buffer Add Speed\",\n logx = False,\n logy = False,\n equality_check=None)\n\n\n# Fill Buffers\nfor _ in range(buffer_size):\n o = np.random.rand(obs_shape) # [0,1)\n a = np.random.rand(act_shape)\n r = np.random.rand(1)\n d = np.random.randint(2) # [0,2) == 0 or 1\n p = np.random.rand(1)\n\n # OpenAI/Baselines cannot set priority together.\n idx = bprb._next_idx\n bprb.add(obs_t=o,action=a,reward=r,obs_tp1=o,done=d)\n bprb.update_priorities([idx],[p])\n\n rprb.add(obs_t=o,action=a,reward=r,obs_tp1=o,done=d,weight=p)\n\n # Directly access internal PrioritizedBuffer,\n # since ChainerRL/PrioritizedReplayBuffer has no API to set priority.\n cprb.memory.append([{\"state\":o,\n \"action\":a,\n \"reward\":r,\n \"next_state\":o,\n \"is_state_terminal\":d}],\n priority=p)\n\n prb.add(obs=o,act=a,rew=r,next_obs=o,done=d,priority=p)\n\n\nperfplot.save(filename=\"PrioritizedReplayBuffer_sample.png\",\n time_unit=\"ms\",\n setup = lambda n: n,\n kernels = [lambda n: bprb.sample(n,beta=beta),\n lambda n: rprb.sample(n,beta=beta),\n sample_c(cprb),\n lambda n: prb.sample(n,beta=beta)],\n labels = [\"OpenAI/Baselines\",\n \"Ray/RLlib\",\n \"Chainer/ChainerRL\",\n \"cpprb\"],\n n_range = [2**n for n in range(1,9)],\n xlabel = \"Batch size\",\n title = \"Prioritized Replay Buffer Sample Speed\",\n logx=False,\n logy=False,\n equality_check=None)\n","sub_path":"benchmark/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":7125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"148405968","text":"# The Grinder 3.0-beta33\n# HTTP script recorded by TCPProxy at Apr 21, 2007 10:22:59 PM\n\nfrom net.grinder.script import Test\nfrom net.grinder.script.Grinder import grinder\nfrom net.grinder.plugin.http import HTTPPluginControl, HTTPRequest\nfrom HTTPClient import NVPair\nconnectionDefaults = HTTPPluginControl.getConnectionDefaults()\nhttpUtilities = HTTPPluginControl.getHTTPUtilities()\n\n# To use a proxy server, uncomment the next line and set the host and port.\n# connectionDefaults.setProxyServer(\"localhost\", 8001)\n\n# These definitions at the top level of the file are evaluated once,\n# when the worker process is started.\n\nconnectionDefaults.defaultHeaders = \\\n ( NVPair('User-Agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.3) Gecko/20070325 Firefox/2.0.0.3'),\n NVPair('Accept-Encoding', 'gzip,deflate'),\n NVPair('Accept-Language', 'en-us,en;q=0.5'),\n NVPair('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'), )\n\nheaders0= \\\n ( NVPair('Accept', 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'), )\n\nheaders1= \\\n ( NVPair('Accept', 'text/css,*/*;q=0.1'),\n NVPair('Referer', 'http://localhost:8080/richa/formsample.jsp'), )\n\nurl0 = 'http://localhost:8080'\n\n# Create an HTTPRequest for each request, then replace the\n# reference to the HTTPRequest with an instrumented version.\n# You can access the unadorned instance using request101.__target__.\nrequest101 = HTTPRequest(url=url0, headers=headers0)\nrequest101 = Test(101, 'GET formsample.jsp').wrap(request101)\n\nclass TestRunner:\n \"\"\"A TestRunner instance is created for each worker thread.\"\"\"\n\n # A method for each recorded page.\n def page1(self):\n \"\"\"GET formsample.html (requests 101-102).\"\"\"\n result = request101.GET('/richa/formsample.jsp')\n\n grinder.sleep(300)\n\n return result\n\n def __call__(self):\n \"\"\"This method is called for every run performed by the worker thread.\"\"\"\n self.page1() # GET formsample.html (requests 101-102)\n\n\ndef instrumentMethod(test, method_name, c=TestRunner):\n \"\"\"Instrument a method with the given Test.\"\"\"\n unadorned = getattr(c, method_name)\n import new\n method = new.instancemethod(test.wrap(unadorned), None, c)\n setattr(c, method_name, method)\n\n# Replace each method with an instrumented version.\n# You can call the unadorned method using self.page1.__target__().\ninstrumentMethod(Test(100, 'Page 1'), 'page1')\n","sub_path":"Richa/grinder/jsp.py","file_name":"jsp.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"81938578","text":"# python 3\nimport os # to get files names from a directory\nimport sys # for python script arguments\nimport datetime # date in file name for versioning\n\ndef find_imports(file_name, path_files=\"./\", verbose=True):\n \"\"\"Find imported packages from a .go file\"\"\"\n result = []\n with open(path_files+file_name) as fp: # open file\n read_in_next_line = False\n for line in fp:\n if read_in_next_line: # \"import (\" was detected, read until \")\"\n if \")\\n\" in line: # \")\" end of import\n read_in_next_line = False\n if read_in_next_line:\n sub_details = line.split(\"\\\"\") # split on \"\n if verbose:\n print(\"//\",sub_details[1], \" in \", file_name)\n result.append(sub_details[1])\n details = line.split(\" \")\n if \"import\" in details: # look for \"import\" or \"import (\"\n if \"(\\n\" in details:\n read_in_next_line = True\n else:\n sub_details = details[1].split(\"\\\"\")\n if verbose:\n print(\"//\",sub_details[1], \"in\", file_name)\n result.append(sub_details[1])\n return result\n\ndef find_all_imports(files_names, path_files=\"./\", verbose=True):\n \"\"\"List of imported lib from a list of files names\"\"\"\n result = []\n for name in files_names:\n if \".go\" in name:\n result.extend(find_imports(name, path_files=path_files, verbose=verbose))\n return list(set(result))\n\ndef file_with_main(files_names, path_files=\"./\"):\n \"\"\" Detect file with \"func main()\" \"\"\"\n for name in files_names: # for each file name\n with open(path_files+name) as fp: # open file\n for line in fp:\n if \"main()\" in line: # if line contains \"main()\"\n return name\n print(\"//main() was not found\")\n return \"\"\n\ndef extract_lines_no_imports(file):\n \"\"\" Extract lines from a file, except imports and package\"\"\"\n skip_next = False\n lines = []\n for line in file:\n if skip_next: # skip the imports\n skip_next = line != \")\\n\"\n else:\n details = line.split(\" \")\n if \"package\" in details: # skip package declaration\n pass\n elif \"import\" in details:\n if \"(\\n\" in details: # if imports are declared all together - skip until \")\"\n skip_next = True\n else: # if \"import \"stuff\"\" skip\n pass\n else:\n lines.append(line)\n return lines\n\ndef glue_in_one_list(files, imports, file_main, path_files):\n \"\"\" Create a list with every lines contained in the files\"\"\"\n blob = []\n blob.append(\"package main\") # package main\n blob.append(\"\")\n if len(imports) > 0: # imports if any\n blob.append(\"import (\")\n for impopo in imports:\n blob.append(\"\\\"\"+impopo+\"\\\"\")\n blob.append(\")\")\n\n for i in range(len(blob)): # add \"\\n\" to package & imports\n blob[i] += \"\\n\"\n\n [blob.append(line) for line in extract_lines_no_imports(open(path_files+file_main))] # file with main() goes first (arbitrary choice)\n for name in files:\n [blob.append(line) for line in extract_lines_no_imports(open(path_files+name)) if name != file_main] # the other files\n\n return blob\n\ndef list_to_file(lines, path_output=\"./\", file_output=\"defaultName.go\"):\n \"\"\" Write a list to a file\"\"\"\n f = open(path_output+file_output,'w+')\n [f.write(line) for line in lines]\n f.close()\n\ndef go_files_list(path):\n \"\"\" List go files in a directory\"\"\"\n files = []\n for (dirpath, dirnames, filenames) in os.walk(path):\n files.extend(filenames)\n return [name for name in files if \".go\" in name]\n\nif __name__ == '__main__':\n if len(sys.argv) == 3:\n path_to_files = sys.argv[0]\n path_output = sys.argv[1]\n file_output = sys.argv[2]\n else:\n path_to_files = \"/home/user/stuff/\"\n path_output = \"/home/user/stuff/versions/\"\n d = datetime.datetime.now()\n file_output = \"codeBlob_\"+d.strftime('%Y-%m-%d_%H-%M')+\".go\"\n print(\"//path_to_files:\", path_to_files)\n print(\"//path_output: \", path_output)\n print(\"//file_output: \", file_output)\n print(\"\")\n\n files = go_files_list(path_to_files)\n imports = find_all_imports(files, path_files=path_to_files, verbose=False)\n #print(\"//imports:\", imports)\n file_main = file_with_main(files, path_files=path_to_files)\n #print(\"//main() in:\", file_main)\n all_lines = glue_in_one_list(files, imports=imports, path_output=path_output, file_main=file_main, path_files=path_to_files)\n list_to_file(all_lines, file_output=file_output)\n\n [print(line) for line in all_lines]\n# myscript.py | xsel -b\n","sub_path":"Go_concatenator.py","file_name":"Go_concatenator.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"620474868","text":"from gtk import Window, Button, Combo, VBox, HBox\nfrom gtk import ScrolledWindow, Entry, Label, Calendar\n\nfrom gtk import TRUE, FALSE\nfrom simple import HandleToolbar, SimpleMenuBar, SimpleMenu\nfrom simple import RadioMenu\nfrom middle import TwinCList, CommandBox\nfrom helpers import HasMenuBar, HasMenuDialog\nmush = '/usr/share/pixmaps/gnome-gmush.png'\n\nclass TwinListCndWin(Window):\n def __init__(self):\n Window.__init__(self)\n self.vbox = VBox()\n self.button_box = HBox()\n self.listbox = TwinCList()\n\n self.vbox.add(self.listbox)\n self.add(self.vbox)\n self.vbox.show()\n self.show()\n self.set_size_request(300, 200)\n self.listbox.set_position(140)\n\n\nclass CommandBoxWindow(Window, HasMenuBar):\n def __init__(self, cbox=None, name='CommandWindow'):\n Window.__init__(self)\n self.set_name(name)\n self.vbox = cbox\n if cbox is None:\n self.vbox = CommandBox()\n self.add(self.vbox)\n self.tbar = self.vbox.tbar\n self.menubar = self.vbox.menubar\n self.show()\n \nclass MenuWindowOrig(Window):\n def __init__(self, name='MenuVBoxWindow'):\n Window.__init__(self)\n self.set_name(name)\n self.vbox = VBox()\n self.add(self.vbox)\n self.menubar = SimpleMenuBar()\n self.vbox.pack_start(self.menubar, FALSE, FALSE, 0)\n self.vbox.show()\n self.show()\n\n def add_menu(self, commands, name, function, radio=False):\n if radio:\n new_menu = RadioMenu(commands, function)\n else:\n new_menu = SimpleMenu()\n for command in commands:\n new_menu.add(command, function)\n self.menubar.append(new_menu, name)\n\nclass MenuWindow(Window, HasMenuDialog):\n def __init__(self, name='MenuVBoxWindow'):\n Window.__init__(self)\n self.set_name(name)\n self.vbox = VBox()\n self.add(self.vbox)\n self.menubar = SimpleMenuBar()\n self.vbox.pack_start(self.menubar, FALSE, FALSE, 0)\n self.vbox.show()\n self.show()\n \n\n \n \n \n \n","sub_path":"tags/withsqlgen/src/paella/gtk/windows.py","file_name":"windows.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"40199657","text":"#coding=utf-8\nimport random\n\nif __name__ == '__main__':\n s = \"INSERT INTO duty_groups (for_station) VALUES ('{name}');\"\n\n names = ['Небо-У', 'Гамма-С1Е', 'Противник-ГЕ', '5Н84А Оборона-14']\n\n for i in range(10):\n print(s.format(name=random.choice(names)))\n","sub_path":"helpers/generate_duty_groups.py","file_name":"generate_duty_groups.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"281010528","text":"from astropy.cosmology import FlatLambdaCDM\nfrom params import get_params\n\n\nparams = get_params()\n\ncosmo = FlatLambdaCDM(H0=100.*params['h_100'], Om0=params['om_m'], Ob0=params['om_b'])\n\nif __name__ == '__main__':\n print('\\n\\nWelcome to a cosmo instance generator.\\n\\n')\n\n print(1.e6 * cosmo.luminosity_distance([1.0]).value) \n\n print('\\n\\nDone.\\n\\n')\n","sub_path":"BEAST/gal_maker/py/cosmo.py","file_name":"cosmo.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"188156223","text":"def top3(products, amounts, prices):\n listOfProducts=list()\n listOfAmounts=list()\n for i in range(0,len(products)):\n listOfAmounts.append([amounts[i]*prices[i],i])\n\n listOfAmounts.sort(key = sortFirst, reverse=True) \n for i in range(0,len(products)):\n listOfProducts.append(products[listOfAmounts[i][1]])\n return listOfProducts[:3]\n\ndef sortFirst(val): \n return val[0]\n\nprint(top3([\"Computer\", \"Cell Phones\", \"Vacuum Cleaner\"], [3,24,8], [199,299,399]))# [\"Cell Phones\", \"Vacuum Cleaner\", \"Computer\"]\nprint(top3([\"Cell Phones\", \"Vacuum Cleaner\", \"Computer\", \"Autos\", \"Gold\", \"Fishing Rods\", \"Lego\", \" Speakers\"], [5, 25, 2, 7, 10, 3, 2, 24], [51, 225, 22, 47, 510, 83, 82, 124]))# ['Vacuum Cleaner', 'Gold', ' Speakers']\nprint(top3([\"Cell Phones\", \"Vacuum Cleaner\", \"Computer\", \"Autos\", \"Gold\", \"Fishing Rods\", \"Lego\", \" Speakers\"], [0, 12, 24, 17, 19, 23, 120, 8], [9, 24, 29, 31, 51, 8, 120, 14]))# ['Lego', 'Gold', 'Computer']","sub_path":"MostSales/MostSales.py","file_name":"MostSales.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"501872001","text":"from django import forms\nfrom product.models import Product\nfrom fcuser.models import Fcuser\nfrom .models import Order\nfrom django.db import transaction\n\n\nclass RegisterForm(forms.Form):\n def __init__(self, request, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.request = request\n\n quantity = forms.IntegerField(\n error_messages={\n \"required\": \"수량을 입력해 주세요\",\n },\n label=\"수량\",\n )\n product = forms.IntegerField(\n error_messages={\n \"required\": \"상품내용을 입력해 주세요\",\n },\n label=\"상품내용\",\n widget=forms.HiddenInput,\n )\n\n def clean(self):\n cleaned_data = super().clean()\n quantity = cleaned_data.get(\"quantity\")\n product = cleaned_data.get(\"product\")\n fcuser = self.request.session.get(\"user\")\n print(quantity)\n print(product)\n print(fcuser)\n if quantity and product and fcuser:\n with transaction.atomic():\n prod = Product.objects.get(\n pk=product\n )\n order = Order(\n quantity=quantity,\n product=Product.objects.get(\n pk=product\n ),\n fcuser=Fcuser.objects.get(\n email=fcuser\n ),\n )\n order.save()\n prod.stock -= quantity\n prod.save()\n else:\n self.product = product\n self.add_error(\"quantity\", \"값이 없습니다.\")\n self.add_error(\"product\", \"값이 없습니다.\")\n","sub_path":"fc_django/order/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"582005256","text":"import astropy.io.fits as fits\nimport numpy as np\nfrom scipy.interpolate import splev, splrep\n\n\ndef save_fits(filename, data):\n \"A helper function for saving FITS files.\"\n fits.writeto(filename, np.float32(data), overwrite=True, output_verify='silentfix')\n\n\ndef cross_corr(f, g, shifts=None):\n \"\"\"Cross correlation function.\n Accepts:\n f, g: array_like\n shifts: array_like\n Returns:\n c: array_like, correlation values.\"\"\"\n if shifts is None:\n shifts = np.arange(len(g))\n c = np.zeros(len(shifts), dtype=float)\n f_pad = np.zeros(3 * len(f))\n g_pad = np.zeros(3 * len(f))\n f_pad[len(f): 2 * len(f)] = f - f.mean()\n g_pad[len(g): 2 * len(g)] = g - g.mean()\n for i in range(len(shifts)):\n c[i] = np.correlate(f_pad, np.roll(g_pad, -shifts[i]))\n\n return c\n\n\ndef wavelength_shift(in_pixel, ref_pixel, ref_wavelength, dispersion):\n \"\"\"A helper function for determining wavelength shift.\n Accepts a pixel to be determined, a reference pixel, and the dispersion value.\"\"\"\n\n pixel_diff = in_pixel - ref_pixel\n wavelength = pixel_diff * dispersion\n\n return wavelength\n\n\ndef norm_med_comb(data, region=((None, None), (None, None))):\n \"\"\"Function implementing normalized median combination.\"\"\"\n ((y1, x1), (y2, x2)) = region\n\n num_frames = data.shape[0]\n norm_factors = np.zeros(num_frames)\n norm_data = data.copy()\n\n for frame in range(num_frames):\n norm_factors[frame] = np.median(norm_data[frame, y1:y2, x1:x2])\n norm_data[frame] /= norm_factors[frame]\n\n med_comb_data = np.median(norm_data, axis=0)\n\n return med_comb_data, norm_factors\n\n\ndef splinterp(x_new, x_old, y_old):\n \"\"\"Function implementing spline interpolation.\"\"\"\n\n spline = splrep(x_old, y_old)\n y_new = splev(x_new, spline)\n\n return y_new\n","sub_path":"astronomy_work/ast_proj_scripts.py","file_name":"ast_proj_scripts.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"202825003","text":"#!/usr/bin/env python\r\n\r\nimport tweepy\r\nfrom tweepy import OAuthHandler\r\nimport sys, os\r\nimport time\r\n\r\n# import for security issues\r\nimport requests.packages.urllib3\r\nrequests.packages.urllib3.disable_warnings()\r\n\r\n# Your's credential\r\nauth_token = '273049818-Ez9NWMfgO9UzLpLjlxCVRfoToQPDMWqxvKTpRNLQ'\r\nauth_token_secret = 'TV2lUGRJCDo0dzX3Fmy307yyIU4yvxBks57mWd8lpJzuH'\r\nconsumer_key = \"WvgosFFwWg86rrJqSs4DmDTR6\"\r\nconsumer_secret = \"YTWVEGSWoRIYOeQnLTXipzgIq1dKcElV1NXSzAW9PmkOk7nSzQ\"\r\n\r\n\r\nauth = OAuthHandler(consumer_key,consumer_secret)\r\nauth.set_access_token(auth_token,auth_token_secret)\r\napi = tweepy.API(auth)\r\nme = api.me()\r\nprint (\"I am using python to mine twitter\")\r\n\r\nuser_a = sys.argv[1]\r\nuser_b = sys.argv[2]\r\n\r\nlistforusera = []\r\nlistforuserb = []\r\n\r\n\r\n'''API().followers method is actually GET followers/list, which is limited to 15 requests per window (before next epoch). Each call returns 20 users list by default.\r\nThe solution is to increase the length of user's list received during each call, such that within 15 calls it can fetch all the users.\r\nYou can increase the count of results fetched by per call, by including an extra parameter count.'''\r\n\r\nprint(\"ftasame A\")\r\nc = tweepy.Cursor(api.followers, screen_name=user_a, count = 200).items()\r\nprint(\"ftasame B\")\r\nwhile True:\r\n try:\r\n tweet = c.next()\r\n print(tweet)\r\n listforusera.append( tweet.screen_name )\r\n print(\"new User_A: \",tweet.screen_name)\r\n except tweepy.TweepError:\r\n #time.sleep(60 * 15)\r\n continue\r\n except StopIteration:\r\n break\r\n\r\nc1 = tweepy.Cursor(api.followers, screen_name=user_b, count = 200).items()\r\nwhile True:\r\n try:\r\n tweet1 = c1.next()\r\n listforuserb.append( tweet1.screen_name )\r\n print(\"new User_B: \",tweet1.screen_name )\r\n except tweepy.TweepError:\r\n #time.sleep(60 * 15)\r\n continue\r\n except StopIteration:\r\n break\r\n\r\n\r\nlistincommon= []\r\n\r\nfor id in listforusera:\r\n try:\r\n listforuserb.index( id )\r\n listincommon.append( id )\r\n except:\r\n True\r\nprint (\"\\n\" + user_a, \"has: \", len( listforusera), \"followers\")\r\nprint (user_b, \"has: \", len( listforuserb ), \"followers\")\r\nprint (\"\\n\")\r\nprint (user_a, \"and\", user_b, \"have\", len( listincommon ), \"followers in common and the names of the them are: \", listincommon)\r\n\r\n# run example\r\n# python twitter_mutual_friends.py user1 user2 BethAronin\r\n","sub_path":"twitter_mutual_friends2.py","file_name":"twitter_mutual_friends2.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"128948882","text":"#!/usr/bin/env python\n'''\nInstall script for cowebx apps. Requires prior install of Python coweb\nserver package and pycoweb script.\n\nCopyright (c) The Dojo Foundation 2011. All Rights Reserved.\nCopyright (c) IBM Corporation 2008, 2011. All Rights Reserved.\n'''\nimport subprocess\nimport sys\nimport optparse\nimport os\nimport os.path\n\nclass SetupError(Exception): pass\n\ndef _symlink_path(srcRoot, target):\n for path in os.listdir(srcRoot):\n if path.startswith('.') or path == 'WEB-INF': continue\n src = os.path.abspath(os.path.join(srcRoot, path))\n dest = os.path.join(target, path)\n try:\n os.symlink(src, dest)\n except OSError:\n print('skipped: %s' % path)\n\ndef rm(target, f):\n subprocess.call([\"rm\", \"-rf\", os.path.join(target, f)])\n\ndef ln(src, target):\n subprocess.call([\"ln\", \"-s\", src, target])\n\ndef deploy(options, args):\n '''Deploys the app and their widgets into coweb deploy dir.'''\n # invoke pycoweb to create an empty deployment \n try:\n dest = args[1]\n except IndexError:\n raise SetupError('missing: destination path')\n\n if subprocess.call([\n 'pycoweb', 'deploy', dest, \n '-f' if options.force else '',\n '-t', 'src/main/python/run_server.tmpl']):\n raise SetupError('aborted: cowebx deploy')\n\n # copy the webapps into place\n cmd = 'cp -r src/main/webapp/* ' + os.path.join(dest, 'www/')\n subprocess.check_call(cmd, shell=True)\n\ndef develop(options, args):\n '''Symlinks the apps and widgets into an existing developer env.'''\n try:\n dest = args[1]\n except IndexError:\n raise SetupError('missing: destination path')\n\n if subprocess.call([\n 'pycoweb', 'deploy', dest,\n '-f' if options.force else '',\n '-t', 'src/main/python/run_server.tmpl']):\n raise SetupError('aborted: cowebx develop')\n\n # symlink the webapps\n target = os.path.join(dest, 'www')\n _symlink_path('src/main/webapp', target)\n \ndef clean(options, args):\n '''Cleans up the workpath files created by this script.'''\n try:\n dest= args[1]\n except IndexError:\n raise SetupError('missing: destination path')\n rm(dest, 'bin/run_server.py')\n rm(dest, 'www')\n rm(dest, 'bots')\n\nif __name__ == '__main__':\n parser = optparse.OptionParser('usage: %prog '\n '[options] ')\n parser.add_option('-f', '--force', dest='force', action='store_true',\n default=False,\n help='overwrite an existing file or folder (default: False)')\n (options, args) = parser.parse_args()\n\n try:\n func = globals()[args[0]]\n except Exception:\n parser.print_usage()\n sys.exit(255)\n try:\n func(options, args)\n except SetupError as e:\n print(e)\n sys.exit(1)\n","sub_path":"dojo-boilerplate/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"91087527","text":"#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\nAuteur : Stanislas Gueniffey(000377223)\r\nCours : INFO-F-106\r\nProjet : Partie 4\r\n\"\"\"\r\n\r\nimport tkinter as tk\r\n\r\n\r\nclass CluedoDialog:\r\n \"\"\"\r\n Ouvre une fenetre permettant a l'utilisateur de choisir une rumeur de type Cluedo et de \r\n l'assigner a une personne du reseau\r\n \"\"\"\r\n def __init__(self, person, options, root, app):\r\n \"\"\"Constructeur de la classe CluedoDialog\"\"\"\r\n self.parentApp = app #Application principale\r\n self.topForm = tk.Toplevel(root)#Fenetre 'supérieure'\r\n self.person = person #Personne dont on modifie la rumeur\r\n \r\n self.topForm.protocol('WM_DELETE_WINDOW', self.clickedCancel) #Action en cas de fermeture\r\n self.topForm.bind(\"\", self.clickedOK) #On relie Enter à OK\r\n self.topForm.title(\"Choose a combination for %s\"%person.getName())\r\n \r\n listFrame = tk.Frame(self.topForm) #Conteneur des listBox\r\n listFrame.grid(row=0, column=0, columnspan=2)\r\n \r\n indexes = person.getRumor(1) #Index a selectionner (rumeur Cluedo)\r\n \r\n #Liste des personnes\r\n scroll1 = tk.Scrollbar(listFrame, orient=tk.VERTICAL) #Scrollbar associée\r\n self.nameList = tk.Listbox(listFrame, exportselection=False, yscrollcommand=scroll1.set)\r\n for item in options[0]:\r\n self.nameList.insert(tk.END, str(item))\r\n self.nameList.grid(row=1, column=0, padx=2, pady=2, sticky=\"NSEW\")\r\n scroll1.config(command=self.nameList.yview)\r\n scroll1.grid(row=1, column=1, sticky=\"NS\")\r\n self.nameList.selection_set(indexes[0]) #Sélectionne la rumeur (partielle) connue\r\n self.nameList.see(indexes[0]) #S'assure que la sélection soit apparente\r\n \r\n #Liste des armes\r\n scroll2 = tk.Scrollbar(listFrame, orient=tk.VERTICAL)\r\n self.weaponList = tk.Listbox(listFrame, exportselection=False, yscrollcommand=scroll2.set)\r\n for item in options[1]:\r\n self.weaponList.insert(tk.END, str(item))\r\n self.weaponList.grid(row=1, column=2, padx=2, pady=2, sticky=\"NSEW\")\r\n scroll2.config(command=self.weaponList.yview)\r\n scroll2.grid(row=1, column=3, sticky=\"NS\")\r\n self.weaponList.selection_set(indexes[1])\r\n self.weaponList.see(indexes[1])\r\n \r\n #Liste des emplacements\r\n scroll3 = tk.Scrollbar(listFrame, orient=tk.VERTICAL)\r\n self.placeList = tk.Listbox(listFrame, exportselection=False, yscrollcommand=scroll3.set)\r\n for item in options[2]:\r\n self.placeList.insert(tk.END, str(item))\r\n self.placeList.grid(row=1, column=4, padx=2, pady=2, sticky=\"NSEW\")\r\n scroll3.config(command=self.placeList.yview)\r\n scroll3.grid(row=1, column=5, sticky=\"NS\")\r\n self.placeList.selection_set(indexes[2])\r\n self.placeList.see(indexes[2])\r\n\r\n okButton = tk.Button(self.topForm, text=\"OK\", width=8, fg=\"blue\", command=self.clickedOK)\r\n okButton.grid(row=1, column=0, padx=5, pady=5)\r\n \r\n cancelButton = tk.Button(self.topForm, text=\"Cancel\", width=8, command=self.clickedCancel)\r\n cancelButton.grid(row=1, column=1, padx=5, pady=5)\r\n \r\n self.topForm.resizable(width=tk.FALSE, height=tk.FALSE) #On fixe la taille\r\n\r\n def getTop(self):\r\n \"\"\"Retourne une reference a la fenetre de la classe.\"\"\"\r\n return self.topForm\r\n \r\n def clickedOK(self, event=None):\r\n \"\"\"Constitue une nouvelle rumeur a partir de la selection et la transmet a la personne.\"\"\"\r\n newCluedo=(int(self.nameList.curselection()[0]),\r\n int(self.weaponList.curselection()[0]),\r\n int(self.placeList.curselection()[0]))\r\n self.person.setRumor(newCluedo, 1)\r\n self.topForm.destroy() #Detruit la fenetre\r\n \r\n def clickedCancel(self):\r\n \"\"\"Detruit la fenetre sans modifier la rumeur de la personne.\"\"\"\r\n self.topForm.destroy()\r\n","sub_path":"CluedoDialog.py","file_name":"CluedoDialog.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"248319597","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport pytest\nimport os\n\nfrom toml_parser import TOMLParser\n\nclass TestTOMLParser(object):\n\n def teardown_class(cls):\n os.remove('test.toml')\n\n @pytest.fixture()\n def conf(cls):\n str_toml = \"\"\"\n[all]\nrootpath_in = '/work2/kenshi/'\nrootpath_out = '/work/ando/detect_disturb'\nyear = [2010, 2011]\ncase = ['Case-0001', 'Case-0002']\n\n[sub]\nid = 101\nratio = 1.25\ncoord = -123\ncomment = \"average\"\n\n[sub.arr1]\nid = 101\n\n[[sub.arr1.arr2]]\na = 1\nb = 10\n\n[[sub.arr1.arr2]]\na = 2\nb = 20\n\"\"\"[1:]\n\n with open('test.toml', 'w') as f:\n f.write(str_toml)\n\n parser = TOMLParser()\n parser.parse('test.toml')\n return parser.dict_root\n\n def test_parse(self, conf):\n assert conf['all']['rootpath_in'] == '/work2/kenshi/'\n assert conf['all']['year'][0] == 2010\n assert conf['all']['year'][1] == 2011\n assert conf['all']['case'][0] == 'Case-0001'\n assert conf['all']['case'][1] == 'Case-0002'\n assert conf['sub']['comment'] == 'average'\n assert conf['sub']['arr1']['id'] == 101\n assert conf['sub']['arr1']['arr2'][0]['a'] == 1\n assert conf['sub']['arr1']['arr2'][0]['b'] == 10\n assert conf['sub']['arr1']['arr2'][1]['a'] == 2\n assert conf['sub']['arr1']['arr2'][1]['b'] == 20\n \n# pytest.main()\n","sub_path":"test_toml_parser.py","file_name":"test_toml_parser.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"398496902","text":"import cv2\nimport pytesseract\n\npytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'\n\nimg = cv2.imread('matricula.jpg')\ntext = pytesseract.image_to_string(img)\n\nmatricula = text [1:len(text)]\n\nf=open(\"matriculas.txt\",\"w\")\nf.write(matricula + \"\\n\")\n\nf.close()\n\nprint(matricula)","sub_path":"corba/matriculas-complete/matriculas-detector.py","file_name":"matriculas-detector.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"290556868","text":"# Copyright 2010 Jose Maria Zambrana Arze \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom django.conf.urls.defaults import *\n\nurlpatterns = patterns('blob.views',\n url(r'^upload$', 'blobinfo_upload', name='blobinfo_upload'),\n url(r'^admin$', 'blob_admin', name='blob_admin'),\n url(r'^serve/(?P[\\w\\d\\-]+)$', 'blob_serve', name='blob_serve'),\n)","sub_path":"blob/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"515336020","text":"#(1)search_box.send_keys ...Google検索をする\n#(2)mailbody+= ...検索結果からメール本文を作成\n#(3)smtpobj.sendmail ...メールを送信する\n#---------------------------------------------------始めていきましょう!\n# -*- coding: utf-8 -*-\nimport datetime\nfrom selenium import webdriver #No module named selenium\nimport chromedriver_binary #学習済-5th\n#pip install chromedriver-binary==87.0.4280.88.0 \nimport time #学習済-5th\nimport datetime #学習済-4th\n#---------------------->check https://docs.python.org/ja/3/library/datetime.html\n#driver = webdriver.Firefox()\n#driver.get(\"http://www.google.com\")\n#driver.execute_script(\"document.getElementById('lga').style.display = 'none';\")\nfrom bs4 import BeautifulSoup #学習済-1st\nimport requests #学習済-1st\n#setting-mail #5th\nimport smtplib #学習済-5th\nfrom email.mime.text import MIMEText #学習済-5th\nfrom email.utils import formatdate #学習済-5th\nimport ssl #学習済-5th\n# ---------------------------------------------------------------------------v\nsetting_10th = '玄米 トースター'\n\ninterval = 1\n#10th-以下、\n#myEDIT.\n#mw-parser-output #

#<----*これをstyle=\"opacity:0.5;\"---->\n#mw-parser-output #

#<----*これをstyle=\"opacity:1;\"---->\n#mw-parser-output #

#<----*これをstyle=\"onClick=class\"---->\ndriver = webdriver.Chrome()\ndriver.get('https://www.google.com/')\nsearch_box = driver.find_element_by_name(\"q\")\nsearch_box.send_keys(setting_10th)\nsearch_box.submit()\ntime.sleep(interval)\n\n\n#setting-mail\nmailbody=''\n#検索結果の一覧を取得する 〜driver.close\nresults = []\nflag = False\n#日付を取得\nnowObj = datetime.datetime.now()\nnow = nowObj.strftime('%Y年%m月%d日%H時%M分')\n#now = str(nowObj.year)+'年'+str(nowObj.month)+'月'+str(nowObj.day)+'日'+str(nowObj.hour)+'時'+str(nowObj.minute)+'分'\nprint(now)\n\nno=1\nwhile True:\n\n g_ary = driver.find_elements_by_class_name('g')\n for g in g_ary:\n result = {}\n result['url'] = g.find_element_by_class_name('yuRUbf').find_element_by_tag_name('a').get_attribute('href')\n result['title'] = g.find_element_by_tag_name('h3').find_element_by_tag_name('span').text\n print(now+'-'+str(no)+'-------------\\n')#改行\\n\n mailbody+=now+'-'+str(no)+'-------------\\n'\n mailbody+=result['title']+'\\n'\n mailbody+=result['url']+'\\n\\n'\n no += 1\n print(result['title']+'-------------\\n')\n print(result['url']+'-------------\\n')\n \n results.append(result)\n if len(results) >= 50:\n flag = True\n break\n if flag:\n break\n driver.find_element_by_id('pnnext').click()#time.sleep(30)へ。#検索結果の一覧を取得する\n\n\n\n#メール送信をする ~send\n#setting-mail\n#mail\nFROM_ADDRESS = '(指定する)'\nMY_PASSWORD = '(指定する)'\nTO_ADDRESS = '(指定する)'\nBCC = ''\nSUBJECT = \"MyPython:\"+setting_10th #検索ワード\nBODY = mailbody\n#return msg\ndef create_message(from_addr, to_addr, bcc_addrs, subject, body):\n msg = MIMEText(body)\n msg['Subject'] = subject\n msg['From'] = from_addr\n msg['To'] = to_addr\n msg['Bcc'] = bcc_addrs\n msg['Date'] = formatdate()\n msg['Body'] = body\n return msg\n#smtpobj.sendmail \ndef send(from_addr, to_addrs, msg):\n #context = ssl.create_default_context()\n smtpobj = smtplib.SMTP_SSL('smtp.gmail.com', 465, timeout=10)\n smtpobj.login(FROM_ADDRESS, MY_PASSWORD)\n smtpobj.sendmail(from_addr, to_addrs, msg.as_string())\n smtpobj.close()\nif __name__ == '__main__':\n to_addr = TO_ADDRESS\n subject = SUBJECT\n body = BODY\n msg = create_message(FROM_ADDRESS, to_addr, BCC, subject, body)\n send(FROM_ADDRESS, to_addr, msg,) #以上です。\n #------------------------------------------------10th\n\ncountDown=30\nwhile countDown > 0:\n print(countDown) #1秒カウントダウン、ログ表示をしています\n countDown -= 1\n time.sleep(1)\ntime.sleep(\"driver.close()\")\n#time.sleep(30)\ndriver.close()#以上です。#検索結果の一覧を取得する\n\n","sub_path":"10th_google_search.py","file_name":"10th_google_search.py","file_ext":"py","file_size_in_byte":4075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"513432032","text":"import os\nimport sys\nimport random\nimport torch.optim\nimport torch.nn.functional as f\n\ncur_path = os.path.abspath(__file__)\ncur_dir = os.path.dirname(cur_path)\npar_dir = os.path.dirname(cur_dir)\ngra_dir = os.path.dirname(par_dir)\nsys.path.append(cur_dir)\nsys.path.append(par_dir)\nsys.path.append(gra_dir)\n\nfrom math23k.src.model_utils import generate_decoder_input\nfrom math23k.src.model_utils import generate_rule_mask\nfrom math23k.src.masked_cross_entropy import masked_cross_entropy\n\nMAX_OUTPUT_LENGTH = 45\nMAX_INPUT_LENGTH = 120\nUSE_CUDA = torch.cuda.is_available()\n\n\nclass Beam: # the class save the beam node\n def __init__(self, score, input_var, hidden, all_output):\n self.score = score\n self.input_var = input_var\n self.hidden = hidden\n self.all_output = all_output\n\n\ndef train_attn(input_batch, input_length, target_batch, target_length,\n num_batch, nums_stack_batch, copy_nums, generate_nums,\n encoder, decoder,\n encoder_optimizer, decoder_optimizer,\n output_lang, clip=0,\n use_teacher_forcing=1, beam_size=1, english=False):\n\n seq_mask = []\n max_len = max(input_length)\n for i in input_length:\n seq_mask.append([0 for _ in range(i)] + [1 for _ in range(i, max_len)])\n seq_mask = torch.ByteTensor(seq_mask)\n\n num_start = output_lang.n_words - copy_nums - 2 # 5\n unk = output_lang.word2index[\"UNK\"] # 22\n\n # Turn padded arrays into (batch_size x max_len) tensors, transpose into (max_len x batch_size)\n input_var = torch.LongTensor(input_batch).transpose(0, 1)\n target = torch.LongTensor(target_batch).transpose(0, 1)\n\n batch_size = len(input_length)\n\n encoder.train()\n decoder.train()\n\n if USE_CUDA:\n input_var = input_var.cuda()\n seq_mask = seq_mask.cuda()\n\n # Zero gradients of both optimizers\n encoder_optimizer.zero_grad()\n decoder_optimizer.zero_grad()\n\n # Run words through encoder\n encoder_outputs, encoder_hidden = encoder(input_seqs=input_var,\n input_lengths=input_length,\n hidden=None)\n\n # Prepare input and output variables\n decoder_input = torch.LongTensor([output_lang.word2index[\"SOS\"]] * batch_size)\n\n decoder_hidden = encoder_hidden[:decoder.n_layers] # Use last (forward) hidden state from encoder\n\n max_target_length = max(target_length)\n all_decoder_outputs = torch.zeros(max_target_length, batch_size, decoder.output_size)\n\n # Move new Variables to CUDA\n if USE_CUDA:\n all_decoder_outputs = all_decoder_outputs.cuda()\n\n if random.random() < use_teacher_forcing:\n # Run through decoder one time step at a time\n for t in range(max_target_length):\n if USE_CUDA:\n decoder_input = decoder_input.cuda()\n\n decoder_output, decoder_hidden = decoder(input_seq=decoder_input,\n last_hidden=decoder_hidden,\n encoder_outputs=encoder_outputs,\n seq_mask=seq_mask)\n\n all_decoder_outputs[t] = decoder_output\n\n decoder_input = generate_decoder_input(target=target[t],\n decoder_output=decoder_output,\n nums_stack_batch=nums_stack_batch,\n num_start=num_start,\n unk=unk)\n target[t] = decoder_input\n else:\n beam_list = list()\n score = torch.zeros(batch_size)\n if USE_CUDA:\n score = score.cuda()\n\n beam_list.append(Beam(score=score,\n input_var=decoder_input,\n hidden=decoder_hidden,\n all_output=all_decoder_outputs))\n\n # Run through decoder one time step at a time\n for t in range(max_target_length):\n beam_len = len(beam_list)\n beam_scores = torch.zeros(batch_size, decoder.output_size * beam_len)\n all_hidden = torch.zeros(decoder_hidden.size(0), batch_size * beam_len, decoder_hidden.size(2))\n all_outputs = torch.zeros(max_target_length, batch_size * beam_len, decoder.output_size)\n if USE_CUDA:\n beam_scores = beam_scores.cuda()\n all_hidden = all_hidden.cuda()\n all_outputs = all_outputs.cuda()\n\n for b_idx in range(len(beam_list)):\n decoder_input = beam_list[b_idx].input_var\n decoder_hidden = beam_list[b_idx].hidden\n\n rule_mask = generate_rule_mask(decoder_input=decoder_input,\n nums_batch=num_batch,\n word2index=output_lang.word2index,\n batch_size=batch_size,\n nums_start=num_start,\n copy_nums=copy_nums,\n generate_nums=generate_nums,\n english=english)\n\n if USE_CUDA:\n rule_mask = rule_mask.cuda()\n decoder_input = decoder_input.cuda()\n\n decoder_output, decoder_hidden = decoder(input_seq=decoder_input,\n last_hidden=decoder_hidden,\n encoder_outputs=encoder_outputs,\n seq_mask=seq_mask)\n\n score = f.log_softmax(decoder_output, dim=1) + rule_mask\n beam_score = beam_list[b_idx].score\n beam_score = beam_score.unsqueeze(1)\n repeat_dims = [1] * beam_score.dim()\n repeat_dims[1] = score.size(1)\n\n beam_score = beam_score.repeat(*repeat_dims)\n score += beam_score\n\n beam_scores[:, b_idx * decoder.output_size: (b_idx + 1) * decoder.output_size] = score\n all_hidden[:, b_idx * batch_size:(b_idx + 1) * batch_size, :] = decoder_hidden\n\n beam_list[b_idx].all_output[t] = decoder_output\n all_outputs[:, batch_size * b_idx: batch_size * (b_idx + 1), :] = \\\n beam_list[b_idx].all_output\n\n topv, topi = beam_scores.topk(beam_size, dim=1)\n beam_list = list()\n\n for k in range(beam_size):\n temp_topk = topi[:, k]\n temp_input = temp_topk % decoder.output_size\n temp_input = temp_input.data\n if USE_CUDA:\n temp_input = temp_input.cpu()\n\n temp_beam_pos = temp_topk / decoder.output_size\n\n indices = torch.LongTensor(range(batch_size))\n if USE_CUDA:\n indices = indices.cuda()\n indices += temp_beam_pos * batch_size\n\n temp_hidden = all_hidden.index_select(1, indices)\n temp_output = all_outputs.index_select(1, indices)\n\n beam_list.append(Beam(score=topv[:, k],\n input_var=temp_input,\n hidden=temp_hidden,\n all_output=temp_output))\n\n all_decoder_outputs = beam_list[0].all_output\n\n for t in range(max_target_length):\n target[t] = generate_decoder_input(target=target[t],\n decoder_output=all_decoder_outputs[t],\n nums_stack_batch=nums_stack_batch,\n num_start=num_start,\n unk=unk)\n # Loss calculation and backpropagation\n\n if USE_CUDA:\n target = target.cuda()\n\n loss = masked_cross_entropy(\n logits=all_decoder_outputs.transpose(0, 1).contiguous(), # -> batch x seq\n target=target.transpose(0, 1).contiguous(), # -> batch x seq\n length=target_length\n )\n\n loss.backward()\n return_loss = loss.item()\n\n # Clip gradient norms\n if clip:\n torch.nn.utils.clip_grad_norm_(encoder.parameters(), clip)\n torch.nn.utils.clip_grad_norm_(decoder.parameters(), clip)\n\n # Update parameters with optimizers\n encoder_optimizer.step()\n decoder_optimizer.step()\n\n return return_loss\n\n\ndef evaluate_attn(input_seq, input_length,\n num_list, copy_nums, generate_nums,\n encoder, decoder,\n output_lang, beam_size=1, english=False, max_length=MAX_OUTPUT_LENGTH):\n\n seq_mask = torch.ByteTensor(1, input_length).fill_(0)\n num_start = output_lang.n_words - copy_nums - 2\n\n # Turn padded arrays into (batch_size x max_len) tensors, transpose into (max_len x batch_size)\n input_var = torch.LongTensor(input_seq).unsqueeze(1)\n if USE_CUDA:\n input_var = input_var.cuda()\n seq_mask = seq_mask.cuda()\n\n # Set to not-training mode to disable dropout\n encoder.eval()\n decoder.eval()\n\n # Run through encoder\n encoder_outputs, encoder_hidden = encoder(input_seqs=input_var,\n input_lengths=[input_length],\n hidden=None)\n\n # Create starting vectors for decoder\n decoder_input = torch.LongTensor([output_lang.word2index[\"SOS\"]]) # SOS\n decoder_hidden = encoder_hidden[:decoder.n_layers] # Use last (forward) hidden state from encoder\n beam_list = list()\n score = 0\n beam_list.append(Beam(score=score,\n input_var=decoder_input,\n hidden=decoder_hidden,\n all_output=[]))\n\n # Run through decoder\n for di in range(max_length):\n temp_list = list()\n beam_len = len(beam_list)\n\n for xb in beam_list:\n if int(xb.input_var[0]) == output_lang.word2index[\"EOS\"]:\n temp_list.append(xb)\n beam_len -= 1\n\n if beam_len == 0:\n return beam_list[0].all_output\n\n beam_scores = torch.zeros(decoder.output_size * beam_len)\n hidden_size_0 = decoder_hidden.size(0)\n hidden_size_2 = decoder_hidden.size(2)\n all_hidden = torch.zeros(beam_len, hidden_size_0, 1, hidden_size_2)\n\n if USE_CUDA:\n beam_scores = beam_scores.cuda()\n all_hidden = all_hidden.cuda()\n\n all_outputs = []\n current_idx = -1\n\n for b_idx in range(len(beam_list)):\n decoder_input = beam_list[b_idx].input_var\n if int(decoder_input[0]) == output_lang.word2index[\"EOS\"]:\n continue\n\n current_idx += 1\n decoder_hidden = beam_list[b_idx].hidden\n\n if USE_CUDA:\n decoder_input = decoder_input.cuda()\n\n decoder_output, decoder_hidden = decoder(input_seq=decoder_input,\n last_hidden=decoder_hidden,\n encoder_outputs=encoder_outputs,\n seq_mask=seq_mask)\n\n # score = f.log_softmax(decoder_output, dim=1) + rule_mask.squeeze()\n score = f.log_softmax(decoder_output, dim=1)\n score += beam_list[b_idx].score\n\n beam_scores[current_idx * decoder.output_size: (current_idx + 1) * decoder.output_size] = score\n all_hidden[current_idx] = decoder_hidden\n all_outputs.append(beam_list[b_idx].all_output)\n\n topv, topi = beam_scores.topk(beam_size)\n\n for k in range(beam_size):\n word_n = int(topi[k])\n word_input = word_n % decoder.output_size\n temp_input = torch.LongTensor([word_input])\n indices = int(word_n / decoder.output_size)\n\n temp_hidden = all_hidden[indices]\n temp_output = all_outputs[indices]+[word_input]\n temp_list.append(Beam(score=float(topv[k]),\n input_var=temp_input,\n hidden=temp_hidden,\n all_output=temp_output))\n\n temp_list = sorted(temp_list, key=lambda x: x.score, reverse=True)\n\n if len(temp_list) < beam_size:\n beam_list = temp_list\n else:\n beam_list = temp_list[:beam_size]\n return beam_list[0].all_output\n","sub_path":"math23k/src_baseline/train_and_evaluate_baseline.py","file_name":"train_and_evaluate_baseline.py","file_ext":"py","file_size_in_byte":12809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"215466967","text":"class ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\ndef constructListNode(input_list):\n \"\"\"\n construct listnode from list\n e.g: l1 = s.constructListNode([7,2,4,3])\n \"\"\"\n root = ListNode(0)\n curr = root\n for i in range(len(input_list)):\n curr.next = ListNode(input_list[i])\n curr = curr.next\n return root.next\n\ndef printListNode(head):\n res = []\n while head:\n res.append(head.val)\n head = head.next\n print(res)\n \nimport pysnooper\nclass Solution:\n @pysnooper.snoop('./pysnooper.log')\n def numSubarrayProductLessThanK(self, nums, k):\n pass\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef Tree_Builds_BFS(node_val_list):\n if len(node_val_list) == 0:\n return None\n node_list = []\n for index, val in enumerate(node_val_list):\n if val is not None:\n node = TreeNode(val)\n # print(val)\n else:\n node = None\n if index == 0:\n root = node\n node_list.append(root)\n else:\n\n if index%2:\n tmp = node_list[index//2]\n tmp.left = node\n else:\n tmp = node_list[index//2-1]\n tmp.right = node\n node_list.append(node)\n return root\n\ndef treeLevel(root):\n \"\"\"\n return the depth of the tree\n \"\"\"\n\n if not root:\n return 0\n else:\n return 1+max(treeLevel(root.left),treeLevel(root.right))\n\nfrom collections import deque\ndef printBinaryTree(root):\n \"\"\"\n print the binary tree, not very elegant now\n \"\"\"\n level = treeLevel(root)\n q = deque([root])\n while level > 0:\n new_q = deque()\n while q:\n tmp = q.popleft()\n new_q.append(tmp.left)\n new_q.append(tmp.right)\n print(level*' ', tmp.val, end='')\n print('\\n')\n q = new_q\n level -= 1\n return","sub_path":"Python/LeetCode (2).py","file_name":"LeetCode (2).py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"332138598","text":"# 경로 설정 프로그램\n# 김홍빈\n# input: 1. numpy array (from lidar)\n# 2. numpy array (from lane_cam)\n# output: 차선 center 위치, 기울기, 곡률이 담긴 numpy array (for default driving)\n# 그 외 미션 주행에 필요한 각 정보들\n\n\n# modes = {'DEFAULT': 0, 'PARKING': 1, 'STATIC_OBS': 2, 'MOVING_OBS': 3,\n# 'S_CURVE': 4, 'NARROW': 5, 'U_TURN': 6, 'CROSS_WALK': 7}\n\n# =================Module===================\nimport time\nimport cv2\nimport numpy as np\nimport pycuda.driver as drv\nfrom pycuda.compiler import SourceModule\n\n# ==========================================\nfrom src.parabola import Parabola\nfrom src.sign_cam import SignCam\nfrom src.lane_cam import LaneCam\nfrom src.lidar import Lidar\nfrom src.key_cam import KeyCam\nfrom src.video_stream import VideoStream as video_stream\n\n# ==========================================\n\n\nclass MotionPlanner:\n def __init__(self):\n self.lidar = Lidar() # lidar_instance\n\n self.lane_cam = LaneCam() # lane_cam_instance\n self.sign_cam = SignCam() # sign_cam_instance\n self.key_cam = KeyCam()\n\n self.sign_cam.start()\n\n self.mission_num = 0\n\n self.lap_during_collision = 0\n self.lap_during_clear = 0\n self.mission_start_lap = 0\n\n self.previous_target = None\n self.previous_data = None\n\n self.motion_parameter = None\n\n self.motion_planner_frame = video_stream.VideoStream()\n self.parking_lidar = video_stream.VideoStream()\n self.moving_obs_frame = video_stream.VideoStream()\n self.u_turn_frame = video_stream.VideoStream()\n self.windows_is = []\n\n # pycuda alloc\n\n self.sign_delay = 0\n\n drv.init()\n global context\n from pycuda.tools import make_default_context\n context = make_default_context()\n\n mod = SourceModule(r\"\"\"\n #include \n #include \n\n #define PI 3.14159265\n __global__ void detect(int data[][2], int* rad, int* range, unsigned char *frame, int *pcol) {\n for(int r = 0; r < rad[0]; r++) {\n const int thetaIdx = threadIdx.x;\n const int theta = thetaIdx + range[0];\n int x = rad[0] + int(r * cos(theta * PI/180)) - 1;\n int y = rad[0] - int(r * sin(theta * PI/180)) - 1;\n\n if (data[thetaIdx][0] == 0) data[thetaIdx][1] = r;\n if (*(frame + y * *pcol + x) != 0) data[thetaIdx][0] = 1;\n }\n }\n \"\"\")\n\n self.path = mod.get_function(\"detect\")\n # pycuda alloc end\n time.sleep(2)\n\n def get_sign_trigger(self):\n self.sign_delay = self.sign_cam.sign_control()\n return self.sign_delay\n\n def get_frame(self):\n lanecam_getFrame = self.lane_cam.getFrame()\n # monitor 에서 사용 여부\n # window_is:\n # 차선인식 raw 화면, 차선인식 결과 화면, 주차공간 인식 화면, 정지선 인식 화면,\n # 장애물 미션 화면, 주차 공간 라이다 화면, 동적장애물 화면, 유턴 화면\n self.windows_is = [True, True, False, False, False, False, False, False]\n if self.mission_num == 0: self.windows_is = [True, True, False, False, False, False, False, False]\n elif self.mission_num == 1: self.windows_is = [True, True, True, False, False, True, False, False]\n elif self.mission_num == 2: self.windows_is = [False, False, False, False, True, False, False, False]\n elif self.mission_num == 3: self.windows_is = [False, False, False, False, False, False, True, False]\n elif self.mission_num == 4: self.windows_is = [False, False, False, False, True, False, False, False]\n elif self.mission_num == 5: self.windows_is = [False, False, False, False, True, False, False, False]\n elif self.mission_num == 6: self.windows_is = [False, False, False, False, False, False, False, True]\n elif self.mission_num == 7: self.windows_is = [False, False, False, True, False, False, False, False]\n\n return lanecam_getFrame + (self.motion_planner_frame.read(),\n self.parking_lidar.read(), self.moving_obs_frame.read(), self.u_turn_frame.read())\n\n def get_motion_parameter(self):\n return self.motion_parameter # motion parameter\n\n def plan_motion(self, control_status):\n # ------------------------------------- 미션 번호 변경과 탈출 -------------------------------------\n # modes = {'DEFAULT': 0, 'PARKING': 1, 'STATIC_OBS': 2, 'MOVING_OBS': 3,\n # 'S_CURVE': 4, 'NARROW': 5, 'U_TURN': 6, 'CROSS_WALK': 7}\n\n #if self.keycam.get_mission() != 0:\n self.mission_num = self.key_cam.get_mission()\n\n if self.mission_num == 0:\n self.sign_cam.restart()\n #self.signcam.detect_one_frame()\n self.mission_num = self.sign_cam.get_mission()\n\n self.key_cam.mission_num = self.mission_num\n #self.mission_num = self.keycam.get_mission()\n\n if self.mission_num != 0:\n self.mission_start_lap = time.time()\n\n if self.mission_num == 1:\n if control_status[1] == 6:\n self.mission_num = 0\n self.key_cam.mission_num = 0\n self.mission_start_lap = 0\n\n elif self.mission_num == 3:\n if control_status[2] == 2:\n self.mission_num = 0\n self.key_cam.mission_num = 0\n self.mission_start_lap = 0\n\n elif self.mission_num == 6:\n if control_status[0] == 4:\n self.mission_num = 0\n self.key_cam.mission_num = 0\n self.mission_start_lap = 0\n\n elif self.mission_num == 7:\n if control_status[2] == 2:\n self.mission_num = 0\n self.key_cam.mission_num = 0\n self.mission_start_lap = 0\n\n elif self.mission_num == 2:\n if control_status[2] == 2:\n self.mission_num = 0\n self.key_cam.mission_num = 0\n self.mission_start_lap = 0\n\n elif self.mission_num == 4:\n if control_status[2] == 2:\n self.mission_num = 0\n self.key_cam.mission_num = 0\n self.mission_start_lap = 0\n\n elif self.mission_num == 5:\n if control_status[2] == 2:\n self.mission_num = 0\n self.key_cam.mission_num = 0\n self.mission_start_lap = 0\n\n\n if self.mission_num != 0:\n self.sign_cam.stop()\n\n # --------------------------------------- 미션 수행 ----------------------------------------\n # modes = {'DEFAULT': 0, 'PARKING': 1, 'STATIC_OBS': 2, 'MOVING_OBS': 3,\n # 'S_CURVE': 4, 'NARROW': 5, 'U_TURN': 6, 'CROSS_WALK': 7}\n if self.mission_num == 0:\n self.lane_handling()\n\n elif self.mission_num == 1:\n self.sign_cam.stop()\n self.parking_line_handling()\n\n elif self.mission_num == 3:\n self.moving_obs_handling()\n\n elif self.mission_num == 2: # 공사장: 정적 장애물 탈출 시 문제 발생 가능!\n # 이유: 장애물 사이의 거리가 멀어서 멀리 보고, 타임아웃이 길다.\n # 인자:\n # 부채살 반경, 부채살 사잇각, 장애물 offset 크기, 차선 offset 크기, timeout 시간(초)\n self.static_obs_handling(400, 110, 80, 100, 3)\n\n elif self.mission_num == 4:\n self.static_obs_handling(300, 110, 65, 60, 2)\n\n elif self.mission_num == 5:\n self.static_obs_handling(300, 110, 70, 60, 2)\n\n elif self.mission_num == 6:\n self.u_turn_handling()\n\n elif self.mission_num == 7:\n self.stop_line_handling()\n\n def lane_handling(self):\n self.lane_cam.default_loop(0)\n\n if self.lane_cam.left_coefficients is not None and self.lane_cam.right_coefficients is not None:\n path_coefficients = (self.lane_cam.left_coefficients + self.lane_cam.right_coefficients) / 2\n path = Parabola(path_coefficients[2], path_coefficients[1], path_coefficients[0])\n\n self.motion_parameter = (0, (path.get_value(-10), path.get_derivative(-10), path.get_curvature(-10)), None,\n self.get_sign_trigger())\n\n else:\n self.motion_parameter = (0, None, None, self.get_sign_trigger())\n\n def static_obs_handling(self, radius, angle, obs_size, lane_size, timeout):\n self.lane_cam.default_loop(1)\n left_lane_points = self.lane_cam.left_current_points\n right_lane_points = self.lane_cam.right_current_points\n\n RAD = np.int32(radius)\n AUX_RANGE = np.int32((180 - angle) / 2)\n\n lidar_raw_data = self.lidar.data_list\n current_frame = np.zeros((RAD, RAD * 2), np.uint8)\n\n points = np.full((361, 2), -1000, np.int) # 점 찍을 좌표들을 담을 어레이 (x, y), 멀리 -1000 으로 채워둠.\n\n for theta in range(0, 361):\n r = lidar_raw_data[theta] / 10 # 차에서 장애물까지의 거리, 단위는 cm\n\n if 2 <= r: # 라이다 바로 앞 1cm 의 노이즈는 무시\n\n # r-theta 를 x-y 로 바꿔서 (실제에서의 위치, 단위는 cm)\n x = -r * np.cos(np.radians(0.5 * theta))\n y = r * np.sin(np.radians(0.5 * theta))\n\n # 좌표 변환, 화면에서 보이는 좌표(왼쪽 위가 (0, 0))에 맞춰서 집어넣는다\n points[theta][0] = round(x) + RAD\n points[theta][1] = RAD - round(y)\n\n for point in points: # 장애물들에 대하여\n cv2.circle(current_frame, tuple(point), obs_size, 255, -1) # 캔버스에 점 찍기\n\n data_ = np.zeros((angle + 1, 2), np.int)\n\n if current_frame is not None:\n self.path(drv.InOut(data_), drv.In(RAD), drv.In(AUX_RANGE), drv.In(current_frame), drv.In(np.int32(RAD * 2)),\n block=(angle + 1, 1, 1))\n\n count_ = np.sum(np.transpose(data_)[0])\n\n if count_ == 0:\n self.lap_during_clear = time.time()\n\n else:\n self.lap_during_collision = time.time()\n\n # 다음 세 가지 조건을 모두 만족하면 탈출한다:\n # 전방이 깨끗한 시간이 timeout 이상일 때\n # 장애물을 한 번이라도 만난 뒤에\n # 미션을 시작한 지 3초 이상 지난 뒤에 (표지판을 인식하고 미션을 수행하기 전 탈출하는 것을 방지)\n if self.lap_during_clear - self.lap_during_collision >= timeout and self.lap_during_collision != 0 and \\\n time.time() - self.mission_start_lap > 5:\n self.lap_during_clear = 0\n self.lap_during_collision = 0\n self.mission_start_lap = 0\n self.mission_num = 0\n self.sign_cam.mission_number = 0\n self.key_cam.mission_num = 0\n\n if left_lane_points is not None:\n for i in range(0, len(left_lane_points)):\n if left_lane_points[i] != -1:\n if lane_size != 0:\n cv2.circle(current_frame, (RAD - left_lane_points[i], RAD - 30 * i), lane_size, 100, -1)\n\n if right_lane_points is not None:\n for i in range(0, len(right_lane_points)):\n if right_lane_points[i] != -1:\n if lane_size != 0:\n cv2.circle(current_frame, (RAD + 299 - right_lane_points[i], RAD - 30 * i), lane_size, 100, -1)\n\n data = np.zeros((angle + 1, 2), np.int)\n\n color = None\n target = None\n\n if current_frame is not None:\n self.path(drv.InOut(data), drv.In(RAD), drv.In(AUX_RANGE), drv.In(current_frame), drv.In(np.int32(RAD * 2)),\n block=(angle + 1, 1, 1))\n\n data_transposed = np.transpose(data)\n\n # 장애물에 부딫힌 곳까지 하얀 선 그리기\n for i in range(0, angle + 1):\n x = RAD + int(data_transposed[1][i] * np.cos(np.radians(i + AUX_RANGE))) - 1\n y = RAD - int(data_transposed[1][i] * np.sin(np.radians(i + AUX_RANGE))) - 1\n cv2.line(current_frame, (RAD, RAD), (x, y), 255)\n\n # 진행할 방향을 빨간색으로 표시하기 위해 흑백에서 BGR 로 변환\n color = cv2.cvtColor(current_frame, cv2.COLOR_GRAY2BGR)\n\n # count 는 장애물이 부딪힌 방향의 갯수를 의미\n count = np.sum(data_transposed[0])\n\n if count <= angle - 1:\n relative_position = np.argwhere(data_transposed[0] == 0) - 90 + AUX_RANGE\n minimum_distance = int(min(abs(relative_position)))\n\n for i in range(0, len(relative_position)):\n if abs(relative_position[i]) == minimum_distance:\n target = int(90 + relative_position[i])\n\n else:\n target = int(np.argmax(data_transposed[1]) + AUX_RANGE)\n\n if np.sum(data_transposed[1]) == 0:\n r = 0\n found = False\n while not found:\n for theta in (AUX_RANGE, 180 - AUX_RANGE):\n x = RAD + int(r * np.cos(np.radians(theta))) - 1\n y = RAD - int(r * np.sin(np.radians(theta))) - 1\n\n if current_frame[y][x] == 0:\n found = True\n target = -theta\n break\n r += 1\n\n if target >= 0:\n if self.previous_data is not None and abs(\n self.previous_data[self.previous_target - AUX_RANGE][1] - data[target - AUX_RANGE][1]) <= 1 and \\\n data[target - AUX_RANGE][1] != RAD - 1:\n target = self.previous_target\n\n x_target = RAD + int(data_transposed[1][int(target) - AUX_RANGE] * np.cos(np.radians(int(target))))\n y_target = RAD - int(data_transposed[1][int(target) - AUX_RANGE] * np.sin(np.radians(int(target))))\n cv2.line(color, (RAD, RAD), (x_target, y_target), (0, 0, 255), 2)\n\n self.motion_parameter = (self.mission_num, (data_transposed[1][target - AUX_RANGE], target), None,\n self.get_sign_trigger())\n\n self.previous_data = data\n self.previous_target = target\n\n else:\n x_target = RAD + int(100 * np.cos(np.radians(int(-target)))) - 1\n y_target = RAD - int(100 * np.sin(np.radians(int(-target)))) - 1\n cv2.line(color, (RAD, RAD), (x_target, y_target), (0, 0, 255), 2)\n\n self.motion_parameter = (self.mission_num, (10, target), None, self.get_sign_trigger())\n\n if color is None: return\n\n self.motion_planner_frame.write(color)\n\n def stop_line_handling(self):\n self.lane_cam.stopline_loop()\n self.motion_parameter = (7, self.lane_cam.stopline_info, None, self.get_sign_trigger())\n\n def parking_line_handling(self):\n RAD = 500 # 라이다가 보는 반경\n self.lane_cam.default_loop(0) # 차선을 얻는 0번 모드 (함수 얻기)\n self.lane_cam.parkingline_loop() # 주차선 찾기 함수 실행\n parking_line = self.lane_cam.parkingline_info\n \n # 양 쪽 차선을 다 본 다음에 중앙선을 넘겨준다.\n if self.lane_cam.left_coefficients is not None and self.lane_cam.right_coefficients is not None:\n path_coefficients = (self.lane_cam.left_coefficients + self.lane_cam.right_coefficients) / 2\n path = Parabola(path_coefficients[2], path_coefficients[1], path_coefficients[0])\n\n else:\n path = Parabola(0, 0, 0)\n\n # 왜 1번칸에 장애물이 안 잡힐까? 더 민감하게 장애물을 받는 라이다 코드가 필요해\n # 라이다\n lidar_raw_data = self.lidar.data_list\n current_frame = np.zeros((RAD, RAD * 2), np.uint8)\n\n points = np.full((361, 2), -1000, np.int) # 점 찍을 좌표들을 담을 어레이 (x, y), 멀리 -1000 으로 채워둠.\n\n for angle in range(0, 361):\n r = lidar_raw_data[angle] / 10 # 차에서 장애물까지의 거리, 단위는 cm\n\n if 2 <= r: # 라이다 바로 앞 1cm 의 노이즈는 무시\n\n # r-theta 를 x-y 로 바꿔서 (실제에서의 위치, 단위는 cm)\n x = -r * np.cos(np.radians(0.5 * angle))\n y = r * np.sin(np.radians(0.5 * angle))\n\n # 좌표 변환, 화면에서 보이는 좌표(왼쪽 위가 (0, 0))에 맞춰서 집어넣는다\n points[angle][0] = round(x) + RAD\n points[angle][1] = RAD - round(y)\n\n for point in points: # 장애물들에 대하여\n cv2.circle(current_frame, tuple(point), 30, 255, -1) # 캔버스에 점 찍기\n \n # 주차선 검출 후\n if parking_line is not None:\n r = 0\n obstacle_detected = False\n\n while not obstacle_detected and r <= 200: # 장애물을 만날 때까지 레이저 쏜다\n temp_x = RAD + parking_line[0] + int(r * np.cos(parking_line[2]))\n temp_y = int(RAD - (parking_line[1] + r * np.sin(parking_line[2])))\n try:\n if current_frame[temp_y][temp_x] != 0:\n obstacle_detected = True\n except Exception as e:\n print(\"parking lidar e: \", e)\n pass\n r += 1\n \n # 모니터로 확인\n cv2.line(current_frame, (RAD + parking_line[0] + int(10 * np.cos(parking_line[2])),\n int(RAD - (parking_line[1] + 10 * np.sin(parking_line[2])))),\n (RAD + parking_line[0] + int(r * np.cos(parking_line[2])),\n int(RAD - (parking_line[1] + r * np.sin(parking_line[2])))), 100, 3)\n\n if not obstacle_detected:\n self.motion_parameter = (1, True,\n (path.get_value(-10), path.get_derivative(-10), parking_line[0], parking_line[1]),\n self.get_sign_trigger())\n\n else: # if obstacle detected\n self.motion_parameter = (1, False,\n (path.get_value(-10), path.get_derivative(-10), parking_line[0], parking_line[1]),\n self.get_sign_trigger())\n\n else:\n self.motion_parameter = (1, False, (path.get_value(-10), path.get_derivative(-10), 0, 0), self.get_sign_trigger())\n print(self.motion_parameter)\n\n self.parking_lidar.write(current_frame)\n\n def u_turn_handling(self):\n self.lane_cam.default_loop(0)\n\n right_lane = None\n if self.lane_cam.right_coefficients is not None:\n right_coefficients = self.lane_cam.right_coefficients\n right_lane = Parabola(right_coefficients[2], right_coefficients[1], right_coefficients[0])\n\n UTURN_RANGE = 20\n RAD = np.int32(500)\n AUX_RANGE = np.int32((180 - np.int32(UTURN_RANGE)) / 2)\n\n lidar_raw_data = self.lidar.data_list\n uturn_frame = np.zeros((RAD, RAD * 2), np.uint8)\n\n points = np.full((361, 2), -1000, np.int) # 점 찍을 좌표들을 담을 어레이 (x, y), 멀리 -1000 으로 채워둠.\n\n for angle in range(0, 361):\n r = lidar_raw_data[angle] / 10 # 차에서 장애물까지의 거리, 단위는 cm\n\n if 2 <= r: # 라이다 바로 앞 1cm 의 노이즈는 무시\n\n # r-theta 를 x-y 로 바꿔서 (실제에서의 위치, 단위는 cm)\n x = -r * np.cos(np.radians(0.5 * angle))\n y = r * np.sin(np.radians(0.5 * angle))\n\n # 좌표 변환, 화면에서 보이는 좌표(왼쪽 위가 (0, 0))에 맞춰서 집어넣는다\n points[angle][0] = round(x) + RAD\n points[angle][1] = RAD - round(y)\n\n for point in points: # 장애물들에 대하여\n cv2.circle(uturn_frame, tuple(point), 15, 255, -1) # 캔버스에 점 찍기\n\n data = np.zeros((UTURN_RANGE + 1, 2), np.int)\n\n minimum_dist = None\n\n if uturn_frame is not None:\n self.path(drv.InOut(data), drv.In(RAD), drv.In(AUX_RANGE), drv.In(uturn_frame),\n drv.In(np.int32(RAD * 2)),\n block=(UTURN_RANGE + 1, 1, 1))\n\n for i in range(0, UTURN_RANGE + 1):\n x = RAD + int(round(data[i][1] * np.cos(np.radians(i + AUX_RANGE)))) - 1\n y = RAD - int(round(data[i][1] * np.sin(np.radians(i + AUX_RANGE)))) - 1\n cv2.line(uturn_frame, (RAD, RAD), (x, y), 255)\n\n data_transposed = data.transpose()\n\n minimum_dist = np.min(data_transposed[1])\n\n self.u_turn_frame.write(uturn_frame) # 유턴 프레임을 모니터에 송출\n\n if right_lane is not None:\n self.motion_parameter = (6, minimum_dist,(right_lane.get_value(-10),\n right_lane.get_derivative(-10)), self.get_sign_trigger())\n else:\n self.motion_parameter = (6, minimum_dist, None, self.get_sign_trigger())\n print(self.motion_parameter)\n\n def moving_obs_handling(self):\n self.lane_cam.default_loop(0)\n path = None\n\n # 차선 보고 가다가 앞에 막히면\n if self.lane_cam.left_coefficients is not None and self.lane_cam.right_coefficients is not None:\n path_coefficients = (self.lane_cam.left_coefficients + self.lane_cam.right_coefficients) / 2\n path = Parabola(path_coefficients[2], path_coefficients[1], path_coefficients[0])\n\n MOVING_OBS_RANGE = 60\n RAD = np.int32(300)\n AUX_RANGE = np.int32((180 - np.int32(MOVING_OBS_RANGE)) / 2)\n\n lidar_raw_data = self.lidar.data_list\n moving_obs_frame = np.zeros((RAD, RAD * 2), np.uint8)\n\n points = np.full((361, 2), -1000, np.int) # 점 찍을 좌표들을 담을 어레이 (x, y), 멀리 -1000 으로 채워둠.\n\n for angle in range(0, 361):\n r = lidar_raw_data[angle] / 10 # 차에서 장애물까지의 거리, 단위는 cm\n\n if 2 <= r: # 라이다 바로 앞 1cm 의 노이즈는 무시\n\n # r-theta 를 x-y 로 바꿔서 (실제에서의 위치, 단위는 cm)\n x = -r * np.cos(np.radians(0.5 * angle))\n y = r * np.sin(np.radians(0.5 * angle))\n\n # 좌표 변환, 화면에서 보이는 좌표(왼쪽 위가 (0, 0))에 맞춰서 집어넣는다\n points[angle][0] = round(x) + RAD\n points[angle][1] = RAD - round(y)\n\n for point in points: # 장애물들에 대하여\n cv2.circle(moving_obs_frame, tuple(point), 25, 255, -1) # 캔버스에 점 찍기\n\n data = np.zeros((MOVING_OBS_RANGE + 1, 2), np.int)\n\n if moving_obs_frame is not None:\n self.path(drv.InOut(data), drv.In(RAD), drv.In(AUX_RANGE), drv.In(moving_obs_frame), drv.In(np.int32(RAD * 2)),\n block=(MOVING_OBS_RANGE + 1, 1, 1))\n\n for i in range(0, MOVING_OBS_RANGE + 1):\n x = RAD + int(round(data[i][1] * np.cos(np.radians(i + AUX_RANGE)))) - 1\n y = RAD - int(round(data[i][1] * np.sin(np.radians(i + AUX_RANGE)))) - 1\n cv2.line(moving_obs_frame, (RAD, RAD), (x, y), 255)\n\n data_transposed = data.transpose()\n collision_count = np.sum(data_transposed[0]) # 막힌 부채살 개수\n minimum_dist = np.min(data_transposed[1]) # 막힌 부채살 중 가장 짧은 길이\n\n if path is not None:\n if collision_count > 20 and minimum_dist < 200:\n # 미션 번호, (이차곡선의 함수값, 미분값, 곡률), 가도 되는지 안 되는지\n self.motion_parameter = (3, (path.get_value(-10),\n path.get_derivative(-10)), False, self.get_sign_trigger())\n\n else:\n self.motion_parameter = (3, (path.get_value(-10),\n path.get_derivative(-10)), True, self.get_sign_trigger())\n else:\n self.motion_parameter = (3, None, False, self.get_sign_trigger())\n\n self.moving_obs_frame.write(moving_obs_frame)\n\n def stop(self):\n self.stop_fg = True\n self.lidar.stop()\n self.lane_cam.stop()\n self.sign_cam.exit()\n\n # pycuda dealloc\n global context\n context.pop()\n context = None\n from pycuda.tools import clear_context_caches\n clear_context_caches()\n # pycuda dealloc end\n\n\nif __name__ == \"__main__\":\n from src.monitor import Monitor\n motion_plan = MotionPlanner()\n monitor = Monitor()\n\n while True:\n motion_plan.plan_motion()\n\n monitor.show('parking', *motion_plan.get_frame())\n if cv2.waitKey(1) & 0xFF == ord('q'): break\n motion_plan.stop()\n","sub_path":"src/motion_planner.py","file_name":"motion_planner.py","file_ext":"py","file_size_in_byte":25606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"213767107","text":"from botlog import BotLog\nfrom botindicators import BotIndicators\nfrom bottrade import BotTrade\n\n\nclass BotStrategy(object):\n def __init__(self):\n self.output = BotLog()\n self.prices = []\n self.closes = [] # Needed for Momentum Indicator\n self.trades = []\n self.current_price = \"\"\n self.current_close = \"\"\n self.num_concurrent_trades = 1\n self.indicators = BotIndicators()\n\n def tick(self, candlestick):\n self.current_price = float(candlestick.price_average)\n self.prices.append(self.current_price)\n\n # self.current_close = float(candlestick['close'])\n # self.closes.append(self.current_close)\n\n self.output.log(\"Price: \" + str(candlestick.price_average) + \"\\tMoving Average: \" +\n str(self.indicators.moving_average(self.prices, 15)))\n\n self.evaluate_positions()\n self.update_open_trades()\n self.show_positions()\n\n def evaluate_positions(self):\n open_trades = []\n for trade in self.trades:\n if trade.status == \"OPEN\":\n open_trades.append(trade)\n\n if len(open_trades) < self.num_concurrent_trades:\n if self.current_price < self.indicators.moving_average(self.prices, 15):\n self.trades.append(BotTrade(self.current_price, stop_loss=.0001))\n\n for trade in open_trades:\n if self.current_price > self.indicators.moving_average(self.prices, 15):\n trade.close(self.current_price)\n\n def update_open_trades(self):\n for trade in self.trades:\n if trade.status == \"OPEN\":\n trade.tick(self.current_price)\n\n def show_positions(self):\n for trade in self.trades:\n trade.show_trade()\n","sub_path":"part 3/botstrategy.py","file_name":"botstrategy.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"196802100","text":"\"\"\"\r\nreference to the implementation in the Pytorch\r\n\"\"\"\r\nimport sys\r\n# sys.path.append('/export/home/chengyh/Anomaly_DA')\r\nimport torch\r\nimport torch.nn as nn\r\nimport torchsnooper\r\nimport torch.nn.functional as F\r\nfrom collections import OrderedDict\r\nfrom lib.networks.auxiliary.flownet2.models import FlowNet2\r\nfrom lib.networks.parts.base.commonness import Conv2dLeakly, ConcatDeconv2d, Deconv2d, BasicConv2d, Inception\r\n\r\nclass AMCGenerator(nn.Module):\r\n def __init__(self, c_in, opticalflow_channel_num=2, image_channel_num=3, dropout_prob=0, bilinear=True):\r\n super(AMCGenerator, self).__init__()\r\n self.c_in = c_in\r\n self.bilinear = bilinear\r\n\r\n # common encoder\r\n self.inception = Inception(c_in, 64)\r\n self.h1 = Conv2dLeakly(64, 64, bn_flag=False, kernel_size=3, stride=1, padding=1)\r\n self.h2 = Conv2dLeakly(64, 128, bn_flag=True, kernel_size=4, stride=2, padding=1)\r\n self.h3 = Conv2dLeakly(128, 256, bn_flag=True, kernel_size=4, stride=2, padding=1)\r\n self.h4 = Conv2dLeakly(256, 512, bn_flag=True, kernel_size=4, stride=2, padding=1)\r\n self.h5 = Conv2dLeakly(512, 512, bn_flag=True, kernel_size=4, stride=2, padding=1)\r\n # unet for optical flow, decoder\r\n self.h4fl = ConcatDeconv2d(512, 256, dropout_prob)\r\n self.h3fl = ConcatDeconv2d(768, 256, dropout_prob)\r\n self.h2fl = ConcatDeconv2d(512, 128, dropout_prob)\r\n self.h1fl = ConcatDeconv2d(256, 64, dropout_prob)\r\n self.conv_fl = BasicConv2d(128, opticalflow_channel_num,kernel_size=3, stride=1, padding=1)\r\n \r\n # decoder for frame\r\n self.h4fr = Deconv2d(512, 256, dropout_prob)\r\n self.h3fr = Deconv2d(256, 256, dropout_prob)\r\n self.h2fr = Deconv2d(256, 128, dropout_prob)\r\n self.h1fr = Deconv2d(128, 64, dropout_prob)\r\n self.conv_fr = BasicConv2d(64, image_channel_num, kernel_size=3, stride=1, padding=1)\r\n\r\n self._init_weights()\r\n\r\n def _init_weights(self):\r\n for m in self.modules():\r\n if isinstance(m, nn.Conv2d):\r\n m.weight = nn.init.kaiming_normal_(m.weight, mode='fan_out') \r\n\r\n # @torchsnooper.snoop()\r\n def forward(self, x):\r\n # common encoder\r\n x = self.inception(x)\r\n x1 = self.h1(x)\r\n x2 = self.h2(x1)\r\n x3 = self.h3(x2)\r\n x4 = self.h4(x3)\r\n x5 = self.h5(x4)\r\n \r\n # unet for optical flow\r\n fl4 = self.h4fl(x5, x4)\r\n fl3 = self.h3fl(fl4,x3)\r\n fl2 = self.h2fl(fl3, x2)\r\n fl1 = self.h1fl(fl2, x1)\r\n out_flow = self.conv_fl(fl1)\r\n\r\n # for frame\r\n fr4 = self.h4fr(x5)\r\n fr3 = self.h3fr(fr4)\r\n fr2 = self.h2fr(fr3)\r\n fr1 = self.h1fr(fr2)\r\n out_frame = self.conv_fr(fr1)\r\n\r\n return out_flow, out_frame\r\n\r\nclass AMCDiscriminiator(nn.Module):\r\n def __init__(self, c_in, filters):\r\n super(AMCDiscriminiator, self).__init__()\r\n self.conv1 = nn.Conv2d(c_in, filters, kernel_size=4, stride=2)\r\n self.conv2 = nn.Conv2d(filters, filters*2, kernel_size=4, stride=2)\r\n self.bn2 = nn.BatchNorm2d(filters*2)\r\n self.conv3 = nn.Conv2d(filters*2, filters*4, kernel_size=4, stride=2)\r\n self.bn3 = nn.BatchNorm2d(filters*4)\r\n self.conv4 = nn.Conv2d(filters*4, filters*8, kernel_size=4, stride=2)\r\n self.bn4 = nn.BatchNorm2d(filters*8)\r\n\r\n self._init_weights()\r\n \r\n def _init_weights(self):\r\n for m in self.modules():\r\n if isinstance(m, nn.Conv2d):\r\n m.weight = nn.init.kaiming_normal_(m.weight, mode='fan_out')\r\n\r\n def forward(self, x):\r\n x = self.conv1(x)\r\n x = F.leaky_relu_(x)\r\n x = self.conv2(x)\r\n x = self.bn2(x)\r\n x = F.leaky_relu_(x)\r\n x = self.conv3(x)\r\n x = self.bn3(x)\r\n x = F.leaky_relu_(x)\r\n x = self.conv4(x)\r\n x = self.bn4(x)\r\n x_sigmod = F.sigmoid(x)\r\n \r\n return x_sigmod\r\n\r\ndef get_model_amc(cfg):\r\n if cfg.MODEL.flownet == 'flownet2':\r\n from collections import namedtuple\r\n from lib.networks.auxiliary.flownet2.models import FlowNet2\r\n temp = namedtuple('Args', ['fp16', 'rgb_max'])\r\n args = temp(False, 1.0)\r\n elif cfg.MODEL.flownet == 'liteflownet':\r\n from lib.networks.auxiliary.liteflownet.models import LiteFlowNet\r\n \r\n flow_model = FlowNet2(args)\r\n flow_model.load_state_dict(torch.load(cfg.MODEL.flow_model_path)['state_dict'])\r\n \r\n generator_model = AMCGenerator(c_in=3, opticalflow_channel_num=2, image_channel_num=cfg.DATASET.channel_num, dropout_prob=0.7)\r\n discriminator_model = AMCDiscriminiator(c_in=5, filters=64)\r\n model_dict = OrderedDict()\r\n model_dict['Generator'] = generator_model\r\n model_dict['Discriminator'] = discriminator_model\r\n model_dict['FlowNet'] = flow_model\r\n return model_dict\r\n\r\n\r\nif __name__ == '__main__':\r\n # model = GeneratorUnet(3,3)\r\n model = AMCDiscriminiator(c_in=6, filters=64)\r\n temp = torch.rand((8,6,128,192))\r\n output = model(temp)\r\n import ipdb; ipdb.set_trace()","sub_path":"lib/networks/parts/amc_networks.py","file_name":"amc_networks.py","file_ext":"py","file_size_in_byte":5130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"368917876","text":"data1 = \"Data1.txt\"\r\ndata2 = \"Data2.txt\"\r\n\r\ndef readData(dataX):\r\n x = []\r\n with open(dataX) as data :\r\n for line in data :\r\n x = line.split()\r\n return x\r\n\r\ntxt = readData(data1) + readData(data2)\r\ntemp = []\r\nfor i in txt:\r\n if i not in temp:\r\n temp.append(i)\r\n\r\nfor i in temp:\r\n print(i)\r\n","sub_path":"01 - List/SG-Basic-Gen.03/DataLatihan/answer2.py","file_name":"answer2.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"73060363","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2019 CERN.\n# Copyright (C) 2019 RERO.\n#\n# Invenio-Circulation is free software; you can redistribute it and/or modify\n# it under the terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"Circulation Patron JSON Resolver module.\"\"\"\n\nimport jsonresolver\nfrom werkzeug.routing import Rule\n\n\n@jsonresolver.hookimpl\ndef jsonresolver_loader(url_map):\n \"\"\"Resolve the patron reference.\"\"\"\n from flask import current_app as app\n resolving_path = app.config.get(\n \"CIRCULATION_DOCUMENT_RESOLVING_PATH\") or \"/\"\n url_map.add(Rule(\n resolving_path,\n endpoint=app.config.get('CIRCULATION_DOCUMENT_RESOLVER_ENDPOINT'),\n host=app.config.get('JSONSCHEMAS_HOST')))\n","sub_path":"invenio_circulation/records/jsonresolver/document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"188326168","text":"# -*- coding: UTF-8 -*-\n\n\nimport base64\nimport hashlib\nimport random\nimport string\nimport struct\nfrom Crypto.Cipher import AES\nfrom socket import htonl as hostbytes_to_netbytes\n\nAES_ENCODE_OK = 10\nAES_ENCODE_ERROR = 11\nAES_DECODE_OK = 20\nAES_DECODE_ERROR = 21\n\n\nclass _PKCS7Cryptor(object):\n \"\"\"PKCS7对称加解密\"\"\"\n BLOCKSIZE = 32\n\n def encode(self, text):\n text_len = len(text)\n amount_to_pad = self.BLOCKSIZE - (text_len % self.BLOCKSIZE)\n if amount_to_pad == 0:\n return text\n pad_str = chr(amount_to_pad)\n return text + pad_str * amount_to_pad\n\n def decode(self, padded_str):\n amount_to_pad = ord(padded_str[-1])\n if amount_to_pad < 1 or amount_to_pad > self.BLOCKSIZE:\n amount_to_pad = 0\n return padded_str[:-amount_to_pad]\n\n\nclass _AESCryptor(object):\n def __init__(self, key):\n self.key = key\n self.mode = AES.MODE_CBC\n\n def encrypt(self, text, appid):\n text_t = (self.__class__.get_random_str(16) + struct.pack('I', hostbytes_to_netbytes(len(text))).decode('utf-8')\n + text + appid)\n pkcs7 = _PKCS7Cryptor()\n text_p = pkcs7.encode(text_t)\n cryptor = AES.new(self.key, self.mode, self.key[:16])\n try:\n crypted_text = cryptor.encrypt(text_p)\n return AES_ENCODE_OK, base64.b64encode(crypted_text)\n except Exception as e:\n print(\"AES encode:\", e)\n return AES_ENCODE_ERROR, None\n\n def decrypt(self, text, appid):\n try:\n cryptor = AES.new(self.key, self.mode, self.key[:16])\n plain_text = cryptor.decrypt(base64.b64decode(text))\n except Exception as e:\n print(e)\n return\n\n @staticmethod\n def get_random_str(length):\n rule = string.ascii_letters + string.digits\n tmp_str = random.sample(rule, length)\n return \"\".join(tmp_str)\n\n\nclass MsgCryptor(object):\n \"\"\"\n 微信公众平台发送给开发者的信息解密、开发者发送给微信公众平台的消息加密\n \"\"\"\n\n def __init__(self, token, encoding_aes_key, appid):\n try:\n self.key = base64.b64decode(encoding_aes_key + '=')\n assert len(self.key) == 32\n except AssertionError:\n raise ValueError('Invalid EncodingAESKey')\n self.token = token\n self.appid = appid\n\n def encrypt(self, reply_xmlstr, nonce, timestamp):\n aes = _AESCryptor(self.key)\n return_code, encrypt = aes.encrypt(reply_xmlstr, self.appid)\n if return_code != AES_ENCODE_OK:\n return return_code, None\n return return_code, encrypt\n\n def decrypt(self, en):\n pass\n","sub_path":"tweixin/wxcrypt.py","file_name":"wxcrypt.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"547420865","text":"import asyncio\nimport pie\n\n\nclass infos(pie.Plugin):\n\n def __init__(self):\n\n super().__init__()\n self.index = 0\n self.infos = ['This mode needs minimum 4 players.',\n 'You can cast votes in \"Esc -> Manage Server\" menu.',\n 'The Warm Up will be skiped if everyone presses \"Give Up\".',\n 'If you have a good map for this mode tell MakeLove.',\n 'Please change to Spectator when going AFK!']\n\n\n @asyncio.coroutine\n def on_load(self):\n\n self.connect_event('ManiaPlanet.EndMatch', self.print_next_info)\n\n\n @asyncio.coroutine\n def print_next_info(self, callback):\n\n #yield from pie.server.AutoTeamBalance()\n yield from pie.chat_send('$<$f00Info:$> ' + self.nextInfo())\n\n\n def nextInfo(self):\n\n t = self.infos[self.index]\n if self.index == len(self.infos) - 1:\n self.index = 0\n else:\n self.index = self.index + 1\n return t\n\n\n\n","sub_path":"plugins/infos.py","file_name":"infos.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"159690835","text":"from django.http import HttpResponse\nfrom django.http import Http404\n\nfrom django.shortcuts import render\nfrom django.shortcuts import redirect\n\nfrom django.template import RequestContext\n\nfrom kanban.models import Task\nfrom kanban.models import Board\nfrom django.forms import ModelForm\n\nfrom django.contrib.auth.models import User\n\nfrom django.contrib.auth.decorators import login_required\n\n@login_required\ndef index(request):\n boards = Board.objects.all()\n return render(request, 'index.html', {'boards': boards})\n\n@login_required\ndef taskshow(request, task_id):\n try:\n task = Task.objects.get(pk=task_id)\n except:\n raise Http404\n\n return render(request, 'task.html', {'task': task})\n\n\nclass TaskNewForm(ModelForm):\n class Meta:\n model = Task\n exclude = [\"done_date\", \"queue_number\", \"owner\", \"group\"]\n\n def __init__(self, *args, **kwargs):\n super(TaskNewForm, self).__init__(*args, **kwargs)\n self.fields['start_date'].widget.format = '%m/%d/%Y'\n self.fields['start_date'].widget.attrs.update({'class':'datePicker', 'readonly':'true'})\n\n@login_required\ndef tasknew(request, board_id):\n try:\n board = Board.objects.get(pk=board_id)\n except:\n raise Http404\n cf = TaskNewForm()\n return render(request, 'newtask.html', {'board_id': board_id, 'form': cf})\n\n@login_required\ndef taskcreate(request, board_id):\n if request.method != 'POST':\n raise Http404\n\n form = TaskNewForm(data = request.POST)\n if not form.is_valid():\n raise Http404\n\n try:\n board = Board.objects.get(pk=board_id)\n except:\n raise Http404\n\n try:\n user = User.objects.get(pk=1)\n except:\n raise Http404\n\n obj = form.save(commit = False)\n obj.owner = user\n obj.queue_number = 0\n obj.save()\n task_id = obj.id\n board.save()\n board.task.add(obj)\n\n return redirect('kanban:boardshow', board_id)\n\n@login_required\ndef taskforw(request, board_id, task_id):\n try:\n board = Board.objects.get(pk=board_id)\n except:\n raise Http404\n try:\n task = Task.objects.get(pk=task_id)\n except:\n raise Http404\n\n nextphase = None\n getnext = False\n for phase in board.phases.order_by('order'):\n if getnext:\n nextphase = phase\n break \n if phase == task.phase:\n getnext = True\n\n if nextphase is not None:\n task.phase = nextphase\n task.save()\n\n return redirect('kanban:boardshow', board_id)\n\n@login_required\ndef taskback(request, board_id, task_id):\n try:\n board = Board.objects.get(pk=board_id)\n except:\n raise Http404\n try:\n task = Task.objects.get(pk=task_id)\n except:\n raise Http404\n\n prevphase = None\n getprev = False\n for phase in board.phases.order_by('order'):\n if phase == task.phase:\n getprev = True\n break\n prevphase = phase\n\n if getprev and prevphase is not None:\n task.phase = prevphase\n task.save()\n\n return redirect('kanban:boardshow', board_id)\n\n@login_required\ndef boardshow(request, board_id):\n try:\n board = Board.objects.get(pk=board_id)\n except:\n raise Http404\n\n return render(request, 'board.html', {'board': board})\n\nclass BoardNewForm(ModelForm):\n class Meta:\n model = Board\n exclude = [\"task\"]\n\n def __init__(self, *args, **kwargs):\n super(BoardNewForm, self).__init__(*args, **kwargs)\n self.fields['start_date'].widget.format = '%m/%d/%Y'\n self.fields['start_date'].widget.attrs.update({'class':'datePicker', 'readonly':'true'})\n\n@login_required\ndef boardnew(request):\n cf = BoardNewForm()\n return render(request, 'boardnew.html', {'form': cf})\n\n@login_required\ndef boardcreate(request):\n if request.method != 'POST':\n raise Http404\n\n form = BoardNewForm(data=request.POST)\n if not form.is_valid():\n raise Http404\n\n obj = form.save(commit = False)\n obj.save()\n form.save_m2m()\n if obj.phases.count() == 0:\n form = BoardNewForm(instance=obj, data=request.POST)\n return render(request, 'boardnew.html', {'form': form, 'errormsg': 'Please select at least one phase'} )\n board_id = obj.id\n\n return redirect('kanban:boardshow', board_id)\n","sub_path":"bligress/kanban/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"530040926","text":"# Created By: Virgil Dupras\n# Created On: 2009-03-03\n# Copyright 2011 Hardcoded Software (http://www.hardcoded.net)\n\n# This software is licensed under the \"BSD\" License as described in the \"LICENSE\" file, \n# which should be included with this package. The terms are also available at \n# http://www.hardcoded.net/licenses/bsd_license\n\nimport os\nimport sys\nimport os.path as op\nimport shutil\nimport tempfile\nimport plistlib\nfrom subprocess import Popen\nimport re\nimport importlib\nfrom datetime import datetime\n\nfrom .util import rem_file_ext, modified_after, find_in_path\n\ndef print_and_do(cmd):\n print(cmd)\n p = Popen(cmd, shell=True)\n p.wait()\n\ndef ensure_empty_folder(path):\n \"\"\"Make sure that the path exists and that it's an empty folder.\n \"\"\"\n if op.exists(path):\n shutil.rmtree(path)\n os.mkdir(path)\n\ndef filereplace(filename, outfilename=None, **kwargs):\n \"\"\"Reads `filename`, replaces all {variables} in kwargs, and writes the result to `outfilename`.\n \"\"\"\n if outfilename is None:\n outfilename = filename\n fp = open(filename, 'rt', encoding='utf-8')\n contents = fp.read()\n fp.close()\n # We can't use str.format() because in some files, there might be {} characters that mess with it.\n for key, item in kwargs.items():\n contents = contents.replace('{{{}}}'.format(key), item) \n fp = open(outfilename, 'wt', encoding='utf-8')\n fp.write(contents)\n fp.close()\n\ndef get_module_version(modulename):\n mod = importlib.import_module(modulename)\n return mod.__version__\n\ndef build_all_qt_ui(base_dir='.', from_imports=False):\n from PyQt4.uic import compileUiDir\n mapper = lambda d, f: (d, rem_file_ext(f) + '_ui.py')\n compileUiDir(base_dir, map=mapper, from_imports=from_imports)\n\ndef build_all_qt_locs(basedir, extradirs=None):\n \"\"\"Builds all .ts files in `basedir` and create a .qm file with the same name.\n \n If extradirs is not None, for each .ts file in basedir a .ts file with the same name is sought\n for in extradirs and added to the resulting .qm file.\n \"\"\"\n if extradirs is None:\n extradirs = []\n tsfiles = [fn for fn in os.listdir(basedir) if fn.endswith('.ts')]\n for ts in tsfiles:\n files_in_cmd = [op.join(basedir, ts)]\n for extradir in extradirs:\n extrats = op.join(extradir, ts)\n if op.exists(extrats):\n files_in_cmd.append(extrats)\n tsfiles_cmd = ' '.join(files_in_cmd)\n destfile = op.join(basedir, ts.replace('.ts', '.qm'))\n print_and_do('lrelease {} -qm {}'.format(tsfiles_cmd, destfile))\n\ndef build_dmg(app_path, dest_path):\n print(repr(op.join(app_path, 'Contents', 'Info.plist')))\n plist = plistlib.readPlist(op.join(app_path, 'Contents', 'Info.plist'))\n workpath = tempfile.mkdtemp()\n dmgpath = op.join(workpath, plist['CFBundleName'])\n os.mkdir(dmgpath)\n print_and_do('cp -R \"%s\" \"%s\"' % (app_path, dmgpath))\n print_and_do('ln -s /Applications \"%s\"' % op.join(dmgpath, 'Applications'))\n dmgname = '%s_osx_%s.dmg' % (plist['CFBundleName'].lower().replace(' ', '_'), plist['CFBundleVersion'].replace('.', '_'))\n print('Building %s' % dmgname)\n # UDBZ = bzip compression. UDZO (zip compression) was used before, but it compresses much less.\n print_and_do('hdiutil create \"%s\" -format UDBZ -nocrossdev -srcdir \"%s\"' % (op.join(dest_path, dmgname), dmgpath))\n print('Build Complete')\n\ndef build_cocoa_localization(model_path, loc_path):\n \"\"\"Use 'ibtool --strings-file' on all xib in loc_path using 'model_path' as a model.\n \n For example, if you give 'en.lproj' as model_path and 'fr.lproj' as loc_path, this function\n looks in en.lproj for all xibs. For each of them, it looks if there's a .strings file of the\n same name in fr.lproj. If there is, we use ibtool to merge the fr strings file with the en xib\n and write it to fr.lproj. If there's no strings file, the xib is copied over to loc_path\n \"\"\"\n xibs = [name for name in os.listdir(model_path) if name.endswith('.xib')]\n for xib in xibs:\n basename = rem_file_ext(xib)\n model_xib = op.join(model_path, xib)\n loc_strings = op.join(loc_path, basename+'.strings')\n dest_xib = op.join(loc_path, xib)\n if op.exists(loc_strings):\n if modified_after(model_xib, dest_xib) or modified_after(loc_strings, dest_xib):\n cmd = 'ibtool --strings-file {0} --write {1} {2}'\n print_and_do(cmd.format(loc_strings, dest_xib, model_xib))\n else:\n if modified_after(model_xib, dest_xib):\n print(\"Copying {0}\".format(model_xib))\n shutil.copy(model_xib, dest_xib)\n\ndef build_all_cocoa_locs(basedir):\n locs = [name for name in os.listdir(basedir) if name.endswith('.lproj')]\n locs.remove('en.lproj')\n model_path = op.join(basedir, 'en.lproj')\n for loc in locs:\n loc_path = op.join(basedir, loc)\n print(\"Building {0} localizations\".format(loc_path))\n build_cocoa_localization(model_path, loc_path)\n\ndef add_to_pythonpath(path):\n \"\"\"Adds `path` to both PYTHONPATH env and sys.path.\n \"\"\"\n abspath = op.abspath(path)\n pythonpath = os.environ.get('PYTHONPATH', '')\n pathsep = ';' if sys.platform == 'win32' else ':'\n pythonpath = pathsep.join([abspath, pythonpath]) if pythonpath else abspath\n os.environ['PYTHONPATH'] = pythonpath\n sys.path.insert(1, abspath)\n\n# This is a method to hack around those freakingly tricky data inclusion/exlusion rules\n# in setuptools. We copy the packages *without data* in a build folder and then build the plugin\n# from there.\ndef copy_packages(packages_names, dest):\n ignore = shutil.ignore_patterns('.hg', 'tests', 'testdata', 'modules', 'docs')\n for package_name in packages_names:\n if op.exists(package_name):\n source_path = package_name\n else:\n mod = __import__(package_name)\n source_path = op.dirname(mod.__file__)\n dest_name = op.basename(package_name) # the package name can be a path as well\n dest_path = op.join(dest, dest_name)\n if op.exists(dest_path):\n shutil.rmtree(dest_path)\n print(\"Copying package at {0} to {1}\".format(source_path, dest_path))\n shutil.copytree(source_path, dest_path, ignore=ignore)\n\ndef copy_qt_plugins(folder_names, dest): # This is only for Windows\n qmake_path = find_in_path('qmake.exe')\n qt_dir = op.split(op.dirname(qmake_path))[0]\n qt_plugin_dir = op.join(qt_dir, 'plugins')\n def ignore(path, names):\n if path == qt_plugin_dir:\n return [n for n in names if n not in folder_names]\n else:\n return [n for n in names if not n.endswith('.dll')]\n shutil.copytree(qt_plugin_dir, dest, ignore=ignore)\n\ndef build_debian_changelog(changelogpath, destfile, pkgname, from_version=None):\n \"\"\"Builds a debian changelog out of a YAML changelog.\n \"\"\"\n def desc2list(desc):\n # We take each item, enumerated with the '*' character, and transform it into a list.\n desc = desc.replace('\\n', ' ')\n desc = desc.replace(' ', ' ')\n result = desc.split('*')\n return [s.strip() for s in result if s.strip()]\n \n ENTRY_MODEL = \"{pkg} ({version}) stable; urgency=low\\n\\n{changes}\\n -- Virgil Dupras {date}\\n\\n\"\n CHANGE_MODEL = \" * {description}\\n\"\n changelogs = read_changelog_file(changelogpath)\n if from_version:\n # We only want logs from a particular version\n for index, log in enumerate(changelogs):\n if log['version'] == from_version:\n changelogs = changelogs[:index+1]\n break\n rendered_logs = []\n for log in changelogs:\n version = log['version']\n logdate = log['date']\n desc = log['description']\n rendered_date = logdate.strftime('%a, %d %b %Y 00:00:00 +0000')\n rendered_descs = [CHANGE_MODEL.format(description=d) for d in desc2list(desc)]\n changes = ''.join(rendered_descs)\n rendered_log = ENTRY_MODEL.format(pkg=pkgname, version=version, changes=changes, date=rendered_date)\n rendered_logs.append(rendered_log)\n result = ''.join(rendered_logs)\n fp = open(destfile, 'w')\n fp.write(result)\n fp.close()\n\nre_changelog_header = re.compile(r'=== ([\\d.]*) \\(([\\d\\-]*)\\)')\ndef read_changelog_file(filename):\n def iter_by_three(it):\n while True:\n version = next(it)\n date = next(it)\n description = next(it)\n yield version, date, description\n \n with open(filename, 'rt', encoding='utf-8') as fp:\n contents = fp.read()\n splitted = re_changelog_header.split(contents)[1:] # the first item is empty\n # splitted = [version1, date1, desc1, version2, date2, ...]\n result = []\n for version, date_str, description in iter_by_three(iter(splitted)):\n date = datetime.strptime(date_str, '%Y-%m-%d').date()\n d = {'date': date, 'date_str': date_str, 'version': version, 'description': description.strip()}\n result.append(d)\n return result\n","sub_path":"hscommon/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":9117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"182865656","text":"import requests\nimport urllib\nimport json\n\ndef getSubType(cik, adsh):\n\turl = \"https://www.sec.gov/Archives/edgar/data/\" + cik + \"/\" + str(adsh).replace(\"-\", \"\") + \"/\" + str(adsh) + \"-index-headers.html\"\n\t#print(url)\n\tresp = requests.get(url)\n\tdata = resp.text\n\tindex = data.find(\"CONFORMED SUBMISSION TYPE\")\n\t#print(index)\n\ttype = data[1187:1191]\n\treturn type\n","sub_path":"src/python/subtype.py","file_name":"subtype.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"22754331","text":"from flask import Flask, jsonify, request\nfrom tinydb import TinyDB, Query\n\nimport json\n\nfrom tinydb.queries import where\n\napp = Flask(__name__)\n\ndb = TinyDB(\"db.json\")\ntodo_table = db.table(\"todo\")\n\n\nclass Todo():\n def __init__(self, id, content, expiry_date, status, start_date):\n self.id = id\n self.content = content\n self.expiry_date = expiry_date\n self.status = status\n self.start_date = start_date\n\n def toJson(self):\n return json.loads(json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4))\n\n\nclass DuplicateItem(Exception):\n pass\n\n\n@app.route(\"/todo\", methods=[\"GET\"])\ndef todo_get_all():\n todos = todo_table.all()\n return jsonify([todo.to_json() for todo in todos])\n\n\n@app.route(\"/todo\", methods=[\"POST\"])\ndef todo_create():\n req = request.get_json()\n try:\n new_todo = Todo(req['id'], req['content'],\n req['expiry_date'], req['status'], req['start_date'])\n if len(todo_table.search(Query()['id'] == req['id'])) == 0:\n todo_table.insert(new_todo.toJson())\n else:\n raise DuplicateItem\n except KeyError:\n return {\"message\": \"invalid property\", \"code\": 400}\n except DuplicateItem:\n return {\"message\": \"id must be unique\", \"code\": 400}\n return {\"message\": \"OK\", \"code\": 200}\n\n\n@app.route(\"/todo/\", methods=[\"DELETE\"])\ndef todo_delete(todo_id):\n todo_table.remove(where('id') == todo_id)\n return {\"message\": \"OK\", \"code\": 200}\n\n\n@app.route(\"/todo/\", methods=[\"PATCH\"])\ndef todo_update(todo_id):\n todo_update = request.get_json()\n try:\n todo_need_update = todo_table.search(\n Query()['id'] == todo_update['id'])[0]\n except IndexError:\n return {\"message\": \"Error\", \"code\": 400}\n for key in todo_update:\n if key == 'id':\n continue\n todo_need_update[key] = todo_update[key]\n todo_table.update(todo_need_update, Query()[\n 'id'] == todo_need_update['id'])\n return {\"message\": \"OK\", \"code\": 200}","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"365707986","text":"from __future__ import unicode_literals\n\nfrom utils import print_message\n\n\nclass Command:\n def __init__(self, keyword, function, name, helpable=True, match=False, args=None):\n self.keyword = keyword\n self.function = function\n self.name = name\n self.help = helpable\n self.match = match\n self.args = args\n\n def __str__(self):\n return \"Command {} activate by {} helpable {} with args {} matchable {}\".format(self.name, self.keyword,\n self.help, self.args,\n self.match)\n\n\ndef command_loop(message, msg_type, sock, pseudo, cmds):\n if \"help\" == message:\n help_cmds(cmds, msg_type, sock)\n print_message(\"[!] help called by \" + pseudo)\n return 1\n for cmd in cmds:\n if isinstance(cmd.keyword, str) or isinstance(cmd.keyword, unicode):\n if message == cmd.keyword or message + \"?\" == cmd.keyword:\n if \"?\" in message:\n help_cmd(cmd, msg_type, sock)\n else:\n print_message(\"[!] function \" + cmd.name + \" called by \" + pseudo)\n try:\n cmd.function(message, msg_type, sock, pseudo)\n except Exception as e:\n print_message(\"ERROR:{}\\r\\n\".format(e),msg_type,sock,pseudo)\n else:\n print_message(\"success\\r\\n\", msg_type, sock, pseudo)\n return 1\n else:\n for key in cmd.keyword:\n if message.startswith(key):\n if \"?\" in message:\n help_cmd(cmd, msg_type, sock)\n else:\n print_message(\"[!] function \" + cmd.name + \" called by \" + pseudo)\n try:\n cmd.function(message, msg_type, sock, pseudo)\n except Exception as e:\n print_message(\"ERROR:{}\\r\\n\".format(e), msg_type, sock, pseudo)\n else:\n print_message(\"success\\r\\n\", msg_type, sock, pseudo)\n return 1\n elif cmd.match and key in message:\n if \"?\" in message:\n help_cmd(cmd, msg_type, sock)\n else:\n print_message(\"[!] function \" + cmd.name + \" called by \" + pseudo)\n try:\n cmd.function(message, msg_type, sock, pseudo)\n except Exception as e:\n print_message(\"ERROR:{}\\r\\n\".format(e), msg_type, sock, pseudo)\n else:\n print_message(\"success\\r\\n\", msg_type, sock, pseudo)\n return 1\n\n\ndef help_cmd(cmd, msg_type, sock):\n if isinstance(cmd.keyword, str) or isinstance(cmd.keyword, unicode):\n ret = cmd.keyword\n else:\n ret = cmd.keyword[0]\n if cmd.args is not None:\n for arg in cmd.args:\n ret += \" <{}|{}>\".format(arg[0], arg[1])\n if cmd.help:\n print_message(ret+\"\\r\\n\", msg_type, sock)\n\n\ndef help_cmds(cmds, msg_type, sock):\n ret = \"Command available:\"\n for cmd in cmds:\n if cmd.help:\n if isinstance(cmd.keyword, str) or isinstance(cmd.keyword, unicode):\n ret += cmd.keyword + \",\"\n else:\n ret += cmd.keyword[0] + \",\"\n print_message(ret + \"\\r\\n\", msg_type, sock)\n","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"332609541","text":"#!/usr/bin/env python3\nimport os\nimport re\nimport sys\nimport subprocess\nimport taglib\n\nfrom acceptable_tags import ACCEPTABLE_TAGS\n\ndef rec_get_files_with_ext(directory_path, ext):\n ret = []\n for item in os.listdir(directory_path):\n if (item.startswith('.')):\n continue\n item_path = os.path.join(directory_path, item)\n if (os.path.isdir(item_path)):\n ret += rec_get_files_with_ext(item_path, ext)\n elif (item.endswith(ext)):\n ret.append(item_path)\n return ret\n\n\ndef exec_cmd(cmd, newline_on_output=False):\n foo = subprocess.run(cmd,\n stderr=subprocess.STDOUT,\n stdout=subprocess.PIPE,\n universal_newlines=True)\n if (foo.stdout != ''):\n if (newline_on_output):\n print()\n print(foo.stdout, end='', flush=True)\n return foo.returncode\n\n\ndef albumrg(directory_path):\n flac_files = rec_get_files_with_ext(directory_path, '.flac')\n\n print('scanning...', end='', flush=True)\n sorted_songs = {}\n for f in flac_files:\n song = taglib.File(f)\n k = '; '.join(song.tags['ARTIST']) + ' - ' + song.tags['ALBUM'][0]\n if (k in sorted_songs):\n sorted_songs[k].append(f)\n else:\n sorted_songs[k] = [f]\n print('done')\n\n for album, songs in sorted_songs.items():\n print(album + '...', end='', flush=True)\n cmd = ['metaflac', '--add-replay-gain'] + songs\n ret = exec_cmd(cmd, newline_on_output=True)\n print('ERROR' if (ret != 0) else 'done')\n\n\ndef convert(file_exts, directory_path):\n for ext in file_exts:\n files_to_convert = rec_get_files_with_ext(directory_path, ext)\n for f in files_to_convert:\n cmd = [\n 'ffmpeg',\n '-i', f,\n '-c:a', 'flac',\n os.path.splitext(f)[0] + '.flac',\n ]\n ret = exec_cmd(cmd)\n if (ret == 0):\n os.remove(f)\n\n\ndef remove_pictures(f):\n cmd = [\n 'metaflac',\n '--remove',\n '--dont-use-padding',\n '--block-type=PICTURE',\n f,\n ]\n exec_cmd(cmd)\n\n\ndef recompress(f):\n cmd = ['flac', f, '--best', '--force', '--verify']\n exec_cmd(cmd)\n\n\ndef is_acceptable_tag(t):\n for e in ACCEPTABLE_TAGS:\n if (isinstance(e, re._pattern_type)):\n if (e.match(t)):\n return True\n else:\n if (e == t):\n return True\n return False\n\n\ndef normalize_tags(f):\n song = taglib.File(f)\n for t in list(song.tags):\n if (not is_acceptable_tag(t)):\n del song.tags[t]\n continue\n if (t in ['DISCNUMBER', 'TRACKNUMBER']):\n foo = song.tags[t][0]\n if ('/' in foo):\n si = foo.index('/')\n foo = foo[:si]\n if (len(foo) == 1):\n foo = '0' + foo\n song.tags[t] = [foo]\n ret = song.save()\n if (ret):\n for k in ret:\n print('ERROR: failed to save tag \\'' + k + '\\'')\n if ('TRACKNUMBER' not in ret and 'TITLE' not in ret and\n 'TRACKNUMBER' in song.tags and 'TITLE' in song.tags):\n song_title = song.tags['TITLE'][0].replace('/', '')\n new_fn = song.tags['TRACKNUMBER'][0] + ' - ' + song_title + '.flac'\n new_f = os.path.join(os.path.dirname(f), new_fn)\n if (f != new_f):\n os.rename(f, new_f)\n\n\ndef normalize(directory_path):\n flac_files = rec_get_files_with_ext(directory_path, '.flac')\n for f in flac_files:\n remove_pictures(f)\n recompress(f)\n normalize_tags(f)\n cmd = ['puddletag', directory_path]\n exec_cmd(cmd)\n\n\ndef just_order_tags(directory_path):\n flac_files = rec_get_files_with_ext(directory_path, '.flac')\n for f in flac_files:\n song = taglib.File(f)\n ret = song.save()\n if (ret):\n for k in ret:\n print('ERROR: failed to save tag \\'' + k + '\\'')\n\n\ndef strip_BOM(cf):\n s = open(cf, mode='r', encoding='utf-8-sig').read()\n open(cf, mode='w', encoding='utf-8').write(s)\n\n\ndef split(directory_path):\n cue_files = rec_get_files_with_ext(directory_path, '.cue')\n src_files = [os.path.splitext(x)[0] + '.flac' for x in cue_files]\n prev_flac_list = rec_get_files_with_ext(directory_path, '.flac')\n for i, cf in enumerate(cue_files):\n strip_BOM(cf) # cuetag.sh doesn't like BOM headers\n cf_dir = os.path.dirname(cf)\n f = src_files[i]\n # split into tracks\n cmd = [\n 'shnsplit',\n '-d', cf_dir,\n '-f', cf,\n '-o', 'flac',\n '-t', '%n - %t',\n f,\n ]\n ret = exec_cmd(cmd)\n curr_flac_list = rec_get_files_with_ext(directory_path, '.flac')\n if (ret == 0):\n os.remove(f)\n # add tags using cue sheet\n new_tracks = list(set(curr_flac_list) - set(prev_flac_list))\n new_tracks.sort() # track order\n cmd = ['cuetag.sh', cf] + new_tracks\n ret = exec_cmd(cmd)\n if (ret == 0):\n os.remove(cf)\n prev_flac_list = curr_flac_list\n\n\ndef print_command_list():\n print('command list:')\n print('albumrg - apply replay gain by album tags')\n print('convert - convert other lossless files to FLAC')\n print('normalize - make all FLAC metadata follow the same format')\n print('split - split big flac file into tracks')\n\n\ndef main(argc, argv):\n try:\n command = argv[1]\n except IndexError:\n print('usage: command')\n print_command_list()\n sys.exit(1)\n\n if (command == 'albumrg'):\n if (argc != 3):\n print('usage: ' + argv[0] + ' albumrg directory_path')\n sys.exit(1)\n albumrg(argv[2])\n elif (command == 'convert'):\n if (argc != 4):\n print('usage: ' + argv[0] + ' convert file_exts directory_path')\n sys.exit(1)\n file_exts = [x.strip() for x in argv[2].split(',')]\n convert(file_exts, argv[3])\n elif (command == 'normalize'):\n if (argc < 3 or argc > 4):\n print('usage: ' + argv[0] + ' normalize [options] directory_path')\n print('options:')\n print('--just-order-tags: rewrite tags in alphabetical order (no '\n 'picture removal or recompression)')\n sys.exit(1)\n\n flag_just_order_tags = False\n for flag in argv[2:-1]:\n if (flag == '--just-order-tags'):\n flag_just_order_tags = True\n else:\n print('invalid flag \"' + flag + '\"')\n sys.exit(1)\n\n if (flag_just_order_tags):\n just_order_tags(argv[-1])\n else:\n normalize(argv[-1])\n elif (command == 'split'):\n if (argc != 3):\n print('usage: ' + argv[0] + ' split directory_path')\n sys.exit(1)\n split(argv[2])\n else:\n print_command_list()\n sys.exit(1)\n\nif (__name__ == '__main__'):\n main(len(sys.argv), sys.argv)\n","sub_path":"suzukiflac.py","file_name":"suzukiflac.py","file_ext":"py","file_size_in_byte":7112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"593281221","text":"\"\"\"\nCopyright 2021 Mohamed Khalil\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport os\nos.environ['NUMPY_EXPERIMENTAL_ARRAY_FUNCTION'] = '0'\n\nimport numpy as np\nfrom typing import Union\n\n\ndef rotate(theta: Union[float, np.ndarray],\n *arrays: Union[np.ndarray, list[np.ndarray]],\n ) -> None:\n \"\"\"\n Rotates a 1 * nx * 4 ndarray that represents a row of nodes from a State by theta degrees counterclockwise.\n The contents of the array may be Conservative/Primitive state variables, Fluxes, etc...\n\n y\n |\n y' | x'\n * | *\n * | *\n * | *\n * | *\n * | * \\\n * | * \\\n * | * theta \\\n ------------------------------- x\n\n x' = x cos(theta) + y sin(theta)\n y' = y cos(theta) - x sin(theta)\n \"\"\"\n\n if np.ndim(theta) == 3:\n theta = theta[:, :, 0]\n elif np.ndim(theta) > 3:\n raise RuntimeError('theta cannot have more than 3 dimensions.')\n\n for array in arrays:\n\n u = array[:, :, 1] * np.cos(theta) + array[:, :, 2] * np.sin(theta)\n v = array[:, :, 2] * np.cos(theta) - array[:, :, 1] * np.sin(theta)\n\n array[:, :, 1] = u\n array[:, :, 2] = v\n\n\ndef unrotate(theta: float,\n *arrays: Union[np.ndarray, list[np.ndarray]],\n ) -> None:\n \"\"\"\n Rotates a 1 * nx * 4 ndarray that represents a row of nodes from a State by theta degrees clockwise. Basically the\n inverse of rotate_row(). The contents of the array may be Conservative/Primitive state variables, Fluxes, etc...\n\n y\n |\n y' | x'\n * | *\n * | *\n * | *\n * | *\n * | * \\\n * | * \\\n * | * theta \\\n ------------------------------- x\n\n x = x' cos(theta) - y' sin(theta)\n y = y' cos(theta) + x' sin(theta)\n \"\"\"\n\n if np.ndim(theta) == 3:\n theta = theta[:, :, 0]\n elif np.ndim(theta) > 3:\n raise RuntimeError('theta cannot have more than 3 dimensions.')\n\n for array in arrays:\n u = array[:, :, 1] * np.cos(theta) - array[:, :, 2] * np.sin(theta)\n v = array[:, :, 2] * np.cos(theta) + array[:, :, 1] * np.sin(theta)\n\n array[:, :, 1] = u\n array[:, :, 2] = v\n\n\ndef reflect_point(x1: float,\n y1: float,\n x2: float,\n y2: float,\n xr: float,\n yr: float\n ) -> [float]:\n\n if y1 == y2:\n return xr, 2 * y1 - yr\n elif x1 == x2:\n return 2 * x1 - xr, yr\n else:\n m = (y1 - y2) / (x1 - x2)\n b = 0.5 * (y1 + y2 - m * (x1 + x2))\n\n xp = ((1 - m ** 2) * xr + 2 * m * yr - 2 * m * b) / (1 + m ** 2)\n yp = (2 * m * xr - (1 - m ** 2) * yr + 2 * b) / (1 + m ** 2)\n\n return xp, yp\n","sub_path":"pyHype/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"218585513","text":"\"\"\"User, Medicine\n\nRevision ID: 086301f61256\nRevises: \nCreate Date: 2018-06-01 18:43:01.326071\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '086301f61256'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('user',\n sa.Column('id', sa.String(length=36), nullable=False),\n sa.Column('email', sa.String(length=140), nullable=True),\n sa.Column('password_hash', sa.String(length=60), nullable=True),\n sa.Column('admin', sa.Boolean(), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email')\n )\n op.create_table('medicine',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=140), nullable=True),\n sa.Column('description', sa.String(length=140), nullable=True),\n sa.Column('user_id', sa.String(length=36), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('medicine')\n op.drop_table('user')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/086301f61256_user_medicine.py","file_name":"086301f61256_user_medicine.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"310853690","text":"class Solution(object):\r\n def twoSum(self, nums, target):\r\n \"\"\"\r\n :type nums: List[int]\r\n :type target: int\r\n :rtype: List[int]\r\n \"\"\"\r\n for i,x in enumerate(nums):\r\n s_list = nums[i+1:]\r\n if target-x in s_list:\r\n return [nums.index(x), s_list.index(target-x)+i+1]","sub_path":"Week2/两数之和.py","file_name":"两数之和.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"607572696","text":"#!/usr/bin/env python\n#dataset: nbgq\n\nimport sys\nimport string\n\nKEY = 4\nVAL = 3\n\ncurrentkey = None\nmin_value = [sys.maxsize for i in range(5)]\nfor line in sys.stdin:\n line = line.strip()\n key, value = line.split('\\t',1)\n value = value.split()\n if currentkey == None or key == currentkey:\n currentkey = key\n else:\n print('{0}\\t{1}'.format(currentkey,max(min_value)))\n min_value = [sys.maxsize for i in range(KEY)]\n currentkey = key\n key = key.split()\n manhattanDis = 0\n if (len(key)==KEY and len(value)==VAL):\n for i in range(0,KEY-1):\n manhattanDis += abs(float(key[i+1])-float(value[i]))\n if manhattanDis < max(min_value):\n min_value[min_value.index(max(min_value))] = manhattanDis\n \nif currentkey is not None:\n print('{0}\\t{1}'.format(currentkey,max(min_value)))\n","sub_path":"Fair-Student-Funding/block-nested-loop/src/map-reduce/reduce.py","file_name":"reduce.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"557520389","text":"import streamlit as st\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\n# Data Processing\nimport pandas as pd\n\nimage1 = Image.open('images/Feature_Imp.JPG')\n\nst.set_option('deprecation.showPyplotGlobalUse', False)\ntemplate_dict = {'Decision Tree': 0, 'Logistic Regression': 1, 'Random Forest': 2, 'XGBoost': 3}\ninputs = {}\n\ndata = {'Model': ['Random Forest', 'Random Forest', 'Random Forest', 'Random Forest',\n 'Decision Tree', 'Decision Tree', 'Decision Tree', 'Decision Tree',\n 'Logistic Regression', 'Logistic Regression', 'Logistic Regression', 'Logistic Regression',\n 'XGBoost', 'XGBoost', 'XGBoost', 'XGBoost'],\n 'Metric': ['Accuracy', 'Precision', 'Recall', 'F1',\n 'Accuracy', 'Precision', 'Recall', 'F1',\n 'Accuracy', 'Precision', 'Recall', 'F1',\n 'Accuracy', 'Precision', 'Recall', 'F1'],\n 'Score': [93.1, 89.9, 96.9, 93.3,\n 91.2, 87.3, 96.1, 91.5,\n 73.1, 74.8, 68.3,71.4,\n 76.1, 82.4, 65.6, 73.0]\n }\ndf = pd.DataFrame(data, columns=['Model', 'Metric', 'Score'])\n\n\ndef write(state):\n st.title('Model')\n st.markdown('This section provides the ability to select different models and analyze the importance of different features.')\n col1, col2 = st.beta_columns(2)\n with col1:\n inputs[\"model1\"] = st.selectbox(\n \"select Model-1\", list(template_dict.keys())\n )\n\n # if inputs[\"model1\"] == 'Decision Tree':\n df1 = df.loc[df['Model'] == inputs[\"model1\"]]\n df1.plot.barh(x='Metric', y='Score', title=inputs[\"model1\"], color='green')\n st.pyplot()\n if inputs[\"model1\"] == 'Random Forest':\n st.image(image1)\n\n with col2:\n inputs[\"model2\"] = st.selectbox(\n \"select Model-2\", list(template_dict.keys())\n )\n df2 = df.loc[df['Model'] == inputs[\"model2\"]]\n df2.plot.barh(x='Metric', y='Score', title=inputs[\"model2\"], color='blue')\n st.pyplot()\n if inputs[\"model2\"] == 'Random Forest':\n st.image(image1)\n\n st.write('')\n sp1, new_row, sp2 = st.beta_columns((0.1, 1, 0.1))\n df_disp = pd.pivot_table(df, values='Score', index=['Model'], columns='Metric').reset_index()\n with new_row:\n st.header(\"**Data**\")\n st.dataframe(df_disp)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"227003860","text":"from app import create_app, db\nfrom app.models import Compartment, Enzyme, EvidenceLevel, Mechanism, Metabolite, Model, Organism, Reaction, Reference, \\\n ReferenceType, EnzymeReactionOrganism, EnzymeReactionActivation, EnzymeReactionEffector, EnzymeReactionMiscInfo, \\\n EnzymeReactionInhibition, ModelAssumptions\nfrom app.utils.parsers import ReactionParser\nimport re\nfrom config import Config\n\n\ndef add_compartments():\n\n compartment_list = [('Cytosol', 'c'), ('Mitochondria', 'm'), ('Imaginary', 'v'), ('Extracellular', 'e')]\n\n for name, acronym in compartment_list:\n compartment = Compartment(name=name, bigg_id=acronym)\n db.session.add(compartment)\n\n db.session.commit()\n\n\ndef add_evidence_levels():\n evidence_list = [('Got it from papers for the given organism'),\n ('Got it from papers of other organisms'),\n ('Predicted by some algorithm'),\n ('Educated guess')]\n\n for description in evidence_list:\n evidence = EvidenceLevel(description=description)\n db.session.add(evidence)\n db.session.commit()\n\n\ndef add_metabolite(client):\n grasp_id = '2pg'\n name = '2-phosphoglycerate'\n bigg_id = '2pg'\n metanetx_id = 'MNXM23'\n\n compartments = ['1', '2']\n chebi_ids = 'CHEBI:86354, CHEBI:8685'\n inchis = 'InChI=1S/C3H4O3/c1-2(4)3(5)6/h4H,1H2,(H,5,6), InChI=1S/C3H4O4/c1-2(4)3(5)6/h4H,1H2,(H,5,6)'\n\n response = client.post('/add_metabolite', data=dict(\n grasp_id=grasp_id,\n name=name,\n bigg_id=bigg_id,\n metanetx_id=metanetx_id,\n compartments=compartments,\n chebi_ids=chebi_ids,\n inchis=inchis), follow_redirects=True)\n\n assert response.status_code == 200\n\n\ndef add_mechanisms():\n mechanism_list = ['uniUni', 'orderedBiBi', 'randomBibi', 'massAction', 'fixedExchange', 'freeExchange', 'diffusion']\n\n for name in mechanism_list:\n mechanism = Mechanism(name=name)\n db.session.add(mechanism)\n db.session.commit()\n\n\ndef add_organisms():\n organism_list = ['E. coli', 'S. cerevisiae']\n\n for name in organism_list:\n organism = Organism(name=name)\n db.session.add(organism)\n db.session.commit()\n\n\ndef add_reference_types():\n reference_type_list = ['Article', 'Thesis', 'Online database', 'Book']\n\n for type in reference_type_list:\n reference_type = ReferenceType(type=type)\n db.session.add(reference_type)\n db.session.commit()\n\n\ndef add_references():\n ref_type = ReferenceType.query.filter_by(type='Online database').first()\n reference = Reference(title='eQuilibrator', type=ref_type)\n db.session.add(reference)\n db.session.commit()\n\n\n# only for development\ndef add_enzymes(client):\n\n enzyme_name = 'Phosphofructokinase'\n enzyme_acronym = 'PFK'\n isoenzyme = 'PFK1'\n ec_number = '1.2.1.31'\n\n organism_name = 'E. coli'\n number_of_active_sites = 4\n gene_bigg_ids = 'b001, b003'\n uniprot_ids = 'PC3W1, P34D'\n pdb_structure_ids = '3H8A, 1E9I'\n strain = 'WT'\n\n response = client.post('/add_enzyme', data=dict(\n name=enzyme_name,\n acronym=enzyme_acronym,\n isoenzyme=isoenzyme,\n ec_number=ec_number,\n organism_name='1', # querySelectField\n number_of_active_sites=number_of_active_sites,\n gene_names=gene_bigg_ids,\n uniprot_id_list=uniprot_ids,\n pdb_structure_ids=pdb_structure_ids,\n strain=strain), follow_redirects=True)\n\n assert response.status_code == 200\n\n enzyme_list = [('Phosphofructokinase', 'PFK', 'PFK2', '1.2.3.33'),\n ('Fake enzyme for exchange reactions', 'EX_enz', 'EX_enz', None)]\n\n for name, acronym, isoenzyme, ec_number in enzyme_list:\n enzyme = Enzyme(name=name, acronym=acronym, isoenzyme=isoenzyme, ec_number=ec_number)\n db.session.add(enzyme)\n db.session.commit()\n\n\ndef add_ex_enzyme():\n\n enzyme_list = [('Fake enzyme for exchange reactions', 'EX_enz', 'EX_enz', None)]\n\n for name, acronym, isoenzyme, ec_number in enzyme_list:\n enzyme = Enzyme(name=name, acronym=acronym, isoenzyme=isoenzyme, ec_number=ec_number)\n db.session.add(enzyme)\n db.session.commit()\n\n\n# only for development\ndef add_models():\n model_list = [('E. coli - iteration 1', 'E. coli', 'MG16555'),\n ('E. coli - iteration 2', 'E. coli', 'MG16555')]\n\n for name, organism_name, strain in model_list:\n model = Model(name=name, organism_name=organism_name, strain=strain)\n db.session.add(model)\n db.session.commit()\n\n\ndef add_reaction(client):\n reaction_name = 'phosphofructokinase'\n reaction_acronym = 'PFK'\n reaction_grasp_id = 'PFK1'\n reaction_string = '1 pep_c + 1.5 adp_c <-> pyr_c + 2.0 atp_c'\n metanetx_id = ''\n bigg_id = ''\n kegg_id = ''\n\n compartment = '1'\n organism = '1'\n models = ['1', '2']\n enzymes = ['1', '2']\n mechanism = '1'\n mechanism_references = 'https://doi.org/10.1093/bioinformatics/bty942, https://doi.org/10.1093/bioinformatics/bty943'\n mechanism_evidence_level = '1'\n subs_binding_order = 'adp_c, pep_c'\n prod_release_order = 'pyr_c, atp_c'\n std_gibbs_energy = 2.1\n std_gibbs_energy_std = 0.2\n std_gibbs_energy_ph = 7\n std_gibbs_energy_ionic_strength = 0.2\n std_gibbs_energy_references = 'equilibrator'\n comments = ''\n\n\n response = client.post('/add_reaction', data=dict(\n name=reaction_name,\n acronym=reaction_acronym,\n grasp_id=reaction_grasp_id,\n reaction_string=reaction_string,\n bigg_id=bigg_id,\n kegg_id=kegg_id,\n metanetx_id=metanetx_id,\n compartment=compartment,\n organism=organism,\n models=models,\n enzymes=enzymes,\n mechanism=mechanism,\n mechanism_references=mechanism_references,\n mechanism_evidence_level=mechanism_evidence_level,\n subs_binding_order=subs_binding_order,\n prod_release_order=prod_release_order,\n std_gibbs_energy=std_gibbs_energy,\n std_gibbs_energy_std=std_gibbs_energy_std,\n std_gibbs_energy_ph=std_gibbs_energy_ph,\n std_gibbs_energy_ionic_strength=std_gibbs_energy_ionic_strength,\n std_gibbs_energy_references=std_gibbs_energy_references,\n comments=comments), follow_redirects=True)\n\n assert response.status_code == 200\n\n met_db = Metabolite.query.filter_by(bigg_id='atp').first()\n compartment_db = Compartment.query.filter_by(bigg_id='m').first()\n\n met_db.add_compartment(compartment_db)\n\n db.session.commit()\n\n \ndef add_inhibitions(client):\n\n enzyme = '1'\n reaction = '1'\n organism = '1'\n models = '1'\n inhibitor_met = 'adp'\n affected_met = 'atp'\n inhibition_type = 'Competitive'\n inhibition_constant = 1.3*10**-4\n\n evidence_level = '1'\n references = 'https://doi.org/10.1093/bioinformatics/bty942, https://doi.org/10.1093/bioinformatics/bty943'\n comments = ''\n\n response = client.post('/add_enzyme_inhibition', data=dict(\n enzyme=enzyme,\n reaction=reaction,\n organism=organism,\n models=models,\n inhibitor_met=inhibitor_met,\n affected_met=affected_met,\n inhibition_type=inhibition_type,\n inhibition_constant=inhibition_constant,\n inhibition_evidence_level=evidence_level,\n references=references,\n comments=comments), follow_redirects=True)\n\n assert response.status_code == 200\n\n inhibitor_met = 'nad'\n affected_met = 'nadh'\n inhibition_type = 'Competitive'\n inhibition_constant = 1.3*10**-4\n\n evidence_level = '1'\n references = 'https://doi.org/10.1093/bioinformatics/bty942, https://doi.org/10.1093/bioinformatics/bty943'\n comments = ''\n\n response = client.post('/add_enzyme_inhibition', data=dict(\n enzyme=enzyme,\n reaction=reaction,\n organism=organism,\n models=models,\n inhibitor_met=inhibitor_met,\n affected_met=affected_met,\n inhibition_type=inhibition_type,\n inhibition_constant=inhibition_constant,\n inhibition_evidence_level=evidence_level,\n references=references,\n comments=comments), follow_redirects=True)\n\n assert response.status_code == 200\n\n\ndef add_activations(client):\n enzyme = '1'\n reaction = '1'\n organism = '1'\n models = '1'\n activator_met = 'adp'\n activation_constant = 1.3*10**-4\n\n evidence_level = '1'\n references = 'https://doi.org/10.1093/bioinformatics/bty942, https://doi.org/10.1093/bioinformatics/bty943'\n comments = ''\n\n response = client.post('/add_enzyme_activation', data=dict(\n enzyme=enzyme,\n reaction=reaction,\n organism=organism,\n models=models,\n activator_met=activator_met,\n activation_constant=activation_constant,\n activation_evidence_level=evidence_level,\n references=references,\n comments=comments), follow_redirects=True)\n\n assert response.status_code == 200\n\n\n activator_met = 'nad'\n activation_constant = 1.3*10**-4\n\n evidence_level = '1'\n references = 'https://doi.org/10.1093/bioinformatics/bty942, https://doi.org/10.1093/bioinformatics/bty943'\n comments = ''\n\n response = client.post('/add_enzyme_activation', data=dict(\n enzyme=enzyme,\n reaction=reaction,\n organism=organism,\n models=models,\n activator_met=activator_met,\n activation_constant=activation_constant,\n activation_evidence_level=evidence_level,\n references=references,\n comments=comments), follow_redirects=True)\n\n assert response.status_code == 200\n \n \ndef add_effectors(client):\n \n enzyme = '1'\n reaction = '1'\n organism = '1'\n models = '1'\n effector_met = 'adp'\n effector_type = 'Inhibiting'\n\n evidence_level = '1'\n references = 'https://doi.org/10.1093/bioinformatics/bty942, https://doi.org/10.1093/bioinformatics/bty943'\n comments = ''\n\n response = client.post('/add_enzyme_effector', data=dict(\n enzyme=enzyme,\n reaction=reaction,\n organism=organism,\n models=models,\n effector_met=effector_met,\n effector_type=effector_type,\n effector_evidence_level=evidence_level,\n references=references,\n comments=comments), follow_redirects=True)\n\n assert response.status_code == 200\n\n\n effector_met = 'nad'\n effector_type = 'Activating'\n\n evidence_level = '1'\n references = 'https://doi.org/10.1093/bioinformatics/bty942, https://doi.org/10.1093/bioinformatics/bty943'\n comments = ''\n\n response = client.post('/add_enzyme_effector', data=dict(\n enzyme=enzyme,\n reaction=reaction,\n organism=organism,\n models=models,\n effector_met=effector_met,\n effector_type=effector_type,\n effector_evidence_level=evidence_level,\n references=references,\n comments=comments), follow_redirects=True)\n\n assert response.status_code == 200\n\n \ndef add_misc_infos(client):\n enzyme = '1'\n reaction = '1'\n organism = '1'\n models = '1'\n topic = 'allostery'\n description = 'looks like this met is an allosteric inhibitor for that enzyme'\n\n evidence_level = '1'\n references = 'https://doi.org/10.1093/bioinformatics/bty942, https://doi.org/10.1093/bioinformatics/bty943'\n comments = ''\n\n response = client.post('/add_enzyme_misc_info', data=dict(\n enzyme=enzyme,\n reaction=reaction,\n organism=organism,\n models=models,\n topic=topic,\n description=description,\n evidence_level=evidence_level,\n references=references,\n comments=comments), follow_redirects=True)\n\n assert response.status_code == 200\n\n topic = 'blurb'\n description = 'looks like this met is an allosteric inhibitor for that enzyme'\n\n evidence_level = '1'\n references = 'https://doi.org/10.1093/bioinformatics/bty942, https://doi.org/10.1093/bioinformatics/bty943'\n comments = ''\n\n response = client.post('/add_enzyme_misc_info', data=dict(\n enzyme=enzyme,\n reaction=reaction,\n organism=organism,\n models=models,\n topic=topic,\n description=description,\n evidence_level=evidence_level,\n references=references,\n comments=comments), follow_redirects=True)\n\n assert response.status_code == 200\n\n\ndef add_model_assumptions(client):\n\n model = '1'\n assumption = 'allostery sucks'\n description = 'looks like this met is an allosteric inhibitor for that enzyme'\n included_in_model = 'True'\n evidence_level = '1'\n references = 'https://doi.org/10.1093/bioinformatics/bty942, https://doi.org/10.1093/bioinformatics/bty943'\n comments = ''\n\n response = client.post('/add_model_assumption', data=dict(\n model=model,\n assumption=assumption,\n description=description,\n evidence_level=evidence_level,\n included_in_model=included_in_model,\n references=references,\n comments=comments), follow_redirects=True)\n\n assert response.status_code == 200\n\n model = '1'\n assumption = 'inhibition also sucks'\n description = 'blerb'\n included_in_model = 'True'\n evidence_level = '1'\n references = 'https://doi.org/10.1093/bioinformatics/bty942, https://doi.org/10.1093/bioinformatics/bty943'\n comments = ''\n\n response = client.post('/add_model_assumption', data=dict(\n model=model,\n assumption=assumption,\n description=description,\n evidence_level=evidence_level,\n included_in_model=included_in_model,\n references=references,\n comments=comments), follow_redirects=True)\n\n assert response.status_code == 200\n\n\ndef load_empty_entries():\n enz_rxn_inhib = EnzymeReactionInhibition(comments='')\n db.session.add(enz_rxn_inhib)\n\n enz_rxn_activation = EnzymeReactionActivation(comments='')\n db.session.add(enz_rxn_activation)\n\n enz_rxn_effector = EnzymeReactionEffector(comments='')\n db.session.add(enz_rxn_effector)\n\n enz_rxn_misc_info = EnzymeReactionMiscInfo(topic='',\n description='',\n comments='')\n db.session.add(enz_rxn_misc_info)\n\n model_assumption = ModelAssumptions(assumption='',\n description='',\n comments='')\n db.session.add(model_assumption)\n\n db.session.commit()\n\n\nclass LoadDataConfig(Config):\n LOGIN_DISABLED = True\n WTF_CSRF_ENABLED = False\n\n\ndef main():\n app = create_app(LoadDataConfig)\n app_context = app.app_context()\n app_context.push()\n client = app.test_client()\n\n #add_models()\n #add_references()\n #add_activations(client)\n add_inhibitions(client)\n add_effectors(client)\n add_misc_infos(client)\n add_model_assumptions(client)\n\n#main()\n","sub_path":"app/utils/populate_db.py","file_name":"populate_db.py","file_ext":"py","file_size_in_byte":17954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"333968552","text":"import time, random\nfrom constants import *\nfrom bubble_file import *\nfrom math import sqrt\nimport pygame as pg\n\nclass GridManager():\n\n\tdef __init__(self):\n\t\tself.rows = GRID_ROWS\n\t\tself.cols = GRID_COLS\n\t\tself.even_offset = True\n\t\tself.targets = []\n\n\t\tself.grid = [[0 for col in range(self.cols)] for row in range(self.rows)]\n\n\t\tfor row in range(self.rows):\n\t\t\tfor col in range(self.cols):\n\t\t\t\tpos = self.calcPos(row, col, self.even_offset)\n\t\t\t\tself.grid[row][col] = GridBubble(row, col, pos)\n\n\n\t\tfor row in range(self.rows):\n\t\t\tfor col in range(self.cols):\n\t\t\t\tself.findComrades(self.grid[row][col])\n\n\t\tself.appendBottom()\n\t\tself.findTargets()\n\t\tself.collided = False\n\t\tself.collision_counter = 0\n\t\tself.animations = []\n\t\tself.paths = []\n\t\tself.prev_time = 0\n\n\tdef view(self, gun, game):\n\n\t\tif gun.fired.exists: self.checkCollision(gun.fired)\n\n\t\tif self.collided: \n\t\t\tself.collision_counter += 1\n\t\t\tbubble = self.reviveBubble(gun.fired)\t\t\t\n\t\t\tself.updateRows()\n\t\t\tself.popCluster(bubble, game)\n\t\t\tself.findTargets()\n\t\t\tself.checkGameOver(game)\n\t\t\tself.collided = False\n\n\t\tself.draw()\n\n\tdef checkGameOver(self, game):\n\n\t\tif self.rows < GAMEOVER_ROWS: return\n\n\t\tfor col in range(self.cols):\n\t\t\tif self.grid[GAMEOVER_ROWS - 1][col].exists:\n\t\t\t\tgame.over = True\n\t\t\t\treturn\t\n\n\n\tdef checkCollision(self, bullet):\n\n\t\tbullet_x, bullet_y = bullet.pos\n\t\tbullet_x += bullet.dx\n\t\tbullet_y += bullet.dy\n\n\t\tfor target in self.targets:\n\t\t\ttarget_x, target_y = target.pos\n\n\t\t\tL = target_x - (HITBOX_SIZE/2)\n\t\t\tR = target_x + (HITBOX_SIZE/2)\n\t\t\tU = target_y - (HITBOX_SIZE/2)\n\t\t\tD = target_y + (HITBOX_SIZE/2)\n\n\t\t\tif (bullet_y - (HITBOX_SIZE/2)) < D:\t\t\n\t\t\t\tif (bullet_x + (HITBOX_SIZE/2)) > L:\t\n\t\t\t\t\tif (bullet_x - (HITBOX_SIZE/2)) < R:\t\t\t\n\t\t\t\t\t\tif (bullet_y + (HITBOX_SIZE/2)) > U:\n\t\t\t\t\t\t\tbullet.exists = False\n\t\t\t\t\t\t\tself.collided = True\n\n\t\tif bullet_y < 0: \n\t\t\tbullet.exists = False\n\t\t\tself.collided = True\n\n\tdef reviveBubble(self, bullet):\n\n\t\tcollide_point = bullet.pos\n\n\t\timaginary = []\n\t\tdists = []\n\n\t\tfor row in range(self.rows):\n\t\t\tfor col in range(self.cols):\n\t\t\t\tif not self.grid[row][col].exists:\n\t\t\t\t\timaginary.append(self.grid[row][col])\n\n\t\tfor bubble in imaginary:\n\t\t\tx,y = collide_point\n\t\t\tbubble_x, bubble_y = bubble.pos\n\n\t\t\tdist = sqrt( (((x - bubble_x) ** 2) + (y - bubble_y) ** 2) )\n\t\t\tdists.append(dist)\n\n\t\tidx = dists.index(min(dists))\n\t\treplacement = imaginary[idx]\n\n\t\treplacement.exists = True\n\t\treplacement.color = bullet.color\n\n\t\treturn replacement\n\n\tdef updateRows(self):\n\n\t\tif (self.collision_counter % APPEND_COUNTDOWN == 0) and (self.collision_counter != 0): self.appendTop()\n\n\t\tfor col in range(self.cols):\n\t\t\tif self.grid[self.rows-1][col].exists:\n\t\t\t\tself.appendBottom()\n\t\t\t\treturn\n\n\t\tfor col in range(self.cols):\n\t\t\tif self.grid[self.rows - 2][col].exists:\n\t\t\t\treturn\n\n\t\tself.deleteBottom()\n\n\n\tdef appendTop(self):\n\n\t\tfor row in range(self.rows):\n\t\t\tfor col in range(self.cols):\n\t\t\t\tself.grid[row][col].row += 1\n\n\t\tnew_row = []\n\t\tself.rows += 1\n\t\tself.even_offset = not self.even_offset\n\n\t\tfor col in range(self.cols):\n\t\t\tpos = self.calcPos(0, col, self.even_offset)\n\t\t\tnew_row.append(GridBubble(0, col, (0,0)))\n\n\t\tself.grid.insert(0, new_row)\n\n\t\tfor row in range(self.rows):\n\t\t\tfor col in range(self.cols):\n\t\t\t\tself.grid[row][col].pos = self.calcPos(row, col, self.even_offset)\n\t\t\t\tif (row == 0) or (row == 1): self.findComrades(self.grid[row][col])\t\n\n\tdef appendBottom(self):\n\n\t\trow = []\n\n\t\tfor col in range(self.cols):\n\t\t\tpos = self.calcPos(self.rows, col, self.even_offset)\n\t\t\trow.append(GridBubble(self.rows, col, pos, exists = False, color = BG_COLOR))\n\n\t\tself.grid.append(row)\n\n\t\tself.rows += 1\n\n\t\tfor row in range(self.rows - 3, self.rows):\n\t\t\tfor col in range(self.cols):\n\t\t\t\tself.findComrades(self.grid[row][col])\n\n\tdef deleteBottom(self):\n\t\tself.grid.pop()\n\t\tself.rows -= 1\n\n\t\tfor col in range(self.cols):\n\t\t\tself.findComrades(self.grid[self.rows - 1][col])\n\n\n\n\tdef popCluster(self, bubble, game):\n\n\t\tcluster = self.findCluster(bubble)\n\n\t\tif (len(cluster) >= 3) or (bubble.color == BLACK):\t\t\t\n\t\t\twhile len(cluster) > 0:\n\t\t\t\tbubble = cluster.pop()\n\n\t\t\t\tframes = bubble.pop()\n\t\t\t\tself.animations.append(frames)\n\n\t\t\t\tgame.score += 1\n\n\t\t\t\tfor comrade in bubble.getComrades():\n\t\t\t\t\tif comrade.exists and (comrade not in cluster):\n\t\t\t\t\t\trooted = self.findRoot(comrade)\n\t\t\t\t\t\tif not rooted: cluster.append(comrade)\n\n\n\tdef findCluster(self, bubble, reached = None):\n\t\t\n\t\tif reached == None: reached = []\n\n\t\tfor comrade in bubble.getComrades():\n\t\t\tif comrade.exists:\n\t\t\t\tif (comrade not in reached) and ((comrade.color == bubble.color) or (bubble.color == BLACK)):\n\t\t\t\t\treached.append(comrade)\n\t\t\t\t\treached = self.findCluster(comrade, reached)\n\n\t\treturn reached\n\n\tdef findRoot(self, bubble, reached = None, rooted = False):\n\n\t\t# print('row, col = ({}, {})'.format(bubble.row, bubble.col))\n\n\t\tif reached == None:\treached = []\n\n\t\tif bubble.row == 0:\n\t\t\tself.paths.append(reached)\n\t\t\treturn True\n\n\t\tfor comrade in bubble.getComrades():\n\t\t\tif comrade.exists and (comrade not in reached):\n\t\t\t\treached.append(comrade)\n\n\t\t\t\trooted = self.findRoot(comrade, reached)\n\t\t\t\tif rooted:\treturn True\n\n\n\n\t\treturn rooted\n\t\t\n\n\tdef findComrades(self, bubble):\n\t\tbubble.L = None\n\t\tbubble.R = None\n\t\tbubble.UL = None\n\t\tbubble.UR = None\n\t\tbubble.DL = None\n\t\tbubble.DR = None\n\n\t\teven_offset = self.even_offset\n\t\trow = bubble.row\n\t\tcol = bubble.col\n\n\t\tif col > 0: bubble.L = self.grid[row][col - 1]\n\t\tif col < (self.cols - 1): bubble.R = self.grid[row][col + 1]\n\t\t\n\t\tif not ((row % 2) == even_offset): \n\t\t\tif row > 0:\n\t\t\t\tbubble.UL = self.grid[row - 1][col]\n\n\t\t\t\tif col < (self.cols - 1):\n\t\t\t\t\tbubble.UR = self.grid[row - 1][col + 1]\n\n\t\t\tif row < (self.rows - 1):\n\t\t\t\tbubble.DL = self.grid[row + 1][col]\n\n\t\t\t\tif col < (self.cols - 1):\n\t\t\t\t\tbubble.DR = self.grid[row + 1][col + 1]\n\n\t\telse:\n\t\t\tif row > 0:\n\t\t\t\tbubble.UR = self.grid[row - 1][col]\n\n\t\t\t\tif col > 0:\n\t\t\t\t\tbubble.UL = self.grid[row - 1][col - 1]\n\n\t\t\tif row < (self.rows - 1):\n\t\t\t\tbubble.DR = self.grid[row + 1][col]\n\n\t\t\t\tif col > 0:\n\t\t\t\t\tbubble.DL = self.grid[row + 1][col - 1]\n\n\n\tdef updateComrades(self, bubble):\n\n\t\tfor comrade in bubble.getComrades():\n\t\t\tself.findComrades(comrade)\n\n\t\t\t\n\tdef findTargets(self):\n\t\tself.targets = []\n\n\t\tfor row in range(self.rows):\n\t\t\tfor col in range(self.cols):\n\t\t\t\tbubble = self.grid[row][col]\n\n\t\t\t\tif not bubble.exists:\n\t\t\t\t\tfor comrade in bubble.getComrades():\n\t\t\t\t\t\tif (comrade not in self.targets) and comrade.exists:\n\t\t\t\t\t\t\tself.targets.append(comrade)\n\n\t\t# for target in self.targets: print('row, col = {}, {}'.format(target.row, target.col))\n\n\n\tdef calcPos(self, row, col, even_offset):\n\n\t\tx = (col * ((ROOM_WIDTH - BUBBLE_RADIUS) / (GRID_COLS))) + WALL_BOUND_L + BUBBLE_RADIUS\n\n\t\tif not ((row % 2) == even_offset): \n\t\t\tx += BUBBLE_RADIUS\n\n\t\ty = BUBBLE_RADIUS + (row * BUBBLE_RADIUS * 2) \n\n\t\treturn (x,y)\n\n\tdef draw(self):\n\n\t\tfor row in range(self.rows):\n\t\t\tfor col in range(self.cols):\n\n\t\t\t\tif ((self.collision_counter + 1) % APPEND_COUNTDOWN == 0):\n\t\t\t\t\t\tself.grid[row][col].shake()\n\n\t\t\t\telse: self.grid[row][col].draw()\n\n\t\tfor animation in self.animations:\n\t\t\tif not animation: \n\t\t\t\tself.animations.remove(animation)\n\t\t\t\tcontinue\n\t\t\tframe = animation.pop()\n\t\t\tframe.draw()\n\n\t\tif SHOW_COMRADES or VISUALIZATIONS:\n\t\t\tfor row in range(self.rows):\n\t\t\t\tfor col in range(self.cols):\n\t\t\t\t\tbubble = self.grid[row][col]\n\t\t\t\t\tbubble_x, bubble_y = bubble.pos\n\n\t\t\t\t\tfor comrade in bubble.getComrades():\n\t\t\t\t\t\tcomrade_x, comrade_y = comrade.pos\n\t\t\t\t\t\tx_vec = (comrade_x - bubble_x)/2\n\t\t\t\t\t\ty_vec = (comrade_y - bubble_y)/2\n\n\n\t\t\t\t\t\tpg.draw.line(display, BLACK, bubble.pos, (bubble_x + x_vec, bubble_y + y_vec))\n\n\t\tif SHOW_TARGETS or VISUALIZATIONS:\n\t\t\tfor target in self.targets:\n\t\t\t\tx, y = int(target.pos[0]), int(target.pos[1])\n\t\t\t\t# circle(Surface, color, pos, radius, width=0) -> Rect\n\t\t\t\tpg.draw.circle(display, BLACK, (x,y), 5)\n\n\t\tif SHOW_HITBOXES or VISUALIZATIONS:\n\t\t\tfor target in self.targets:\n\t\t\t\tx, y = target.pos\n\t\t\t\thitbox = pg.Surface((HITBOX_SIZE, HITBOX_SIZE), pg.SRCALPHA, 32)\n\t\t\t\thitbox.fill((50, 50, 50, 180))\n\t\t\t\tdisplay.blit(hitbox, (x - HITBOX_SIZE/2, y - HITBOX_SIZE/2))\n\n\n\t\tif SHOW_ROOT_PATH or VISUALIZATIONS:\n\t\t\tfor path in self.paths:\n\t\t\t\tfor idx in range(len(path)):\n\t\t\t\t\tif idx == 0: continue\n\t\t\t\t\tpg.draw.line(display, BLACK, path[idx-1].pos, path[idx].pos, 3)\n\n\n\t\t\tif time.time() - self.prev_time > 0.01:\n\t\t\t\tself.prev_time = time.time()\n\t\t\t\tif self.paths:\n\t\t\t\t\tdel self.paths[0][0]\n\t\t\t\t\tif not self.paths[0]: del self.paths[0]","sub_path":"grid_file.py","file_name":"grid_file.py","file_ext":"py","file_size_in_byte":8449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"364133918","text":"\"\"\"\n\nPiece class, representing a piece of chess\nauthor: @fuego\n\n\"\"\"\nfrom copy import deepcopy\nimport logging\n\n\nclass Rule():\n def __init__(self, rule, board, piece):\n self.function = None\n self.piece = piece\n self.board = board\n self.piece_only = False\n self.replace = False\n\n if rule == \"promotion\":\n self.function = self.promotion\n if rule == \"check\":\n self.function = self.check\n if rule == \"pawn_two_steps\":\n self.replace = True\n self.function = self.pawn_two_steps\n\n logging.debug('Rule {} created'.format(rule))\n\n def get_replace(self):\n return self.replace\n\n def promotion(self, piece, move):\n if piece == self.piece:\n if self.piece.get_side() == \"w\" and move[0] == 7:\n logging.info('Pawn {} promoted'.format(piece.get_position()))\n self.piece.set_queen()\n elif move[0] == 0 and self.piece.get_side() == \"b\":\n logging.info('Pawn {} promoted'.format(piece.get_position()))\n self.piece.set_queen()\n return True\n\n def check(self, piece, move):\n previous_state = True\n pieces = self.board.get_pieces()\n logging.debug(\"First check check\")\n for potential_piece in pieces:\n if potential_piece.get_side() != self.piece.get_side():\n if self.board.is_allowed_attack(potential_piece, self.piece.get_position()):\n previous_state = False\n\n new_board = deepcopy(self.board)\n new_piece = deepcopy(piece)\n new_piece.set_position([move[0], move[1]])\n new_board.remove_piece(piece)\n new_board.place_piece(new_piece)\n\n pieces = new_board.get_pieces()\n logging.debug(\"Second check check\")\n for potential_piece in pieces:\n if potential_piece.get_side() != self.piece.get_side():\n if new_board.is_allowed_attack(potential_piece, self.piece.get_position()):\n if previous_state:\n logging.info(\"Check from {} to {}\".format(potential_piece.get_position(), self.piece.get_position()))\n else:\n logging.info(\"Can't move ! Check from {} to {}\".format(potential_piece.get_position(), self.piece.get_position()))\n return previous_state\n\n previous_state = True\n\n return previous_state\n\n def pawn_two_steps(self, piece, move):\n gradient = [move[0] - piece.get_position()[0], move[1] - piece.get_position()[1]]\n if piece == self.piece:\n if not piece.get_moved() and (gradient == [2, 0] or gradient == [-2, 0]):\n logging.debug(\"Pawn going two steps ahead\")\n return True\n\n def is_respected(self, piece, move):\n return self.function(piece, move)\n","sub_path":"board/rule.py","file_name":"rule.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"71072578","text":"from problem1 import Node\nfrom problem2 import get_adj\nimport sys\n\n\ndef dijkstra(adj_matrix, node_list, source, dest=None):\n Q = []\n Q.append(source)\n source.d = 0\n while(len(Q) != 0):\n u = sorted(Q, key=lambda x: x.d, reverse=False)[0]\n Q.remove(u)\n for v in get_adj(adj_matrix, node_list, u):\n if u.d + adj_matrix[u.id][v.id] <= v.d:\n v.d=u.d + adj_matrix[u.id][v.id]\n Q.append(v)\n if dest is not None:\n if dest.d == sys.maxint:\n return \"unreachable\"\n else:\n return dest.d\n\n\n\nif __name__ == \"__main__\":\n line = map(int, raw_input().split(' '))\n n = line[0]\n m = line[1]\n S = line[2]\n T = line[3]\n node_list = [Node(str(x), x) for x in range(n)]\n adj_matrix = [[sys.maxint for x in range(n)] for y in range(n)]\n for x in range(n):\n line = raw_input()\n if line == \"0 0 0 0\":\n break\n line = map(int, line.split(' '))\n adj_matrix[line[0]][line[1]] = line[2]\n adj_matrix[line[1]][line[0]] = line[2]\n print(\"Distance from \" + str(S) + \" to \" + str(T) + \" is \" + str(dijkstra(adj_matrix, node_list, node_list[S],\n node_list[T])))\n","sub_path":"project1/problem3.py","file_name":"problem3.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"536120128","text":"import xlrd\r\n\r\nfrom gurobipy import *\r\nimport networkx as nx #Para trabajar con grafos\r\nimport matplotlib.pyplot as plt #Para visualizar los grafos\r\n\r\nfrom openpyxl import Workbook, load_workbook\r\nfrom openpyxl.styles.borders import Border, Side\r\nfrom openpyxl.styles import Font,Alignment\r\nfrom datetime import date, timedelta\r\nimport os\r\n\r\n\r\n# Give the location of the file\r\nloc = (\"Datos con asignación.xlsx\")\r\n\r\n# To open Workbook\r\nwb = xlrd.open_workbook(loc)\r\n\r\n\r\nsheet_obras = wb.sheet_by_index(0)\r\nsheet_plantas = wb.sheet_by_index(1)\r\nsheet_calculos_ruteo = wb.sheet_by_index(5)\r\n\r\ndias = [i+1 for i in range(7)]\r\nobras = [i+1 for i in range(225)]\r\n# Obras demanda separa las obras con demanda mayor a 120 en un dia en dos obras, \r\n# porque la tienen que despachar dos camiones\r\nobras_demanda = []\r\nfor i in range(225):\r\n mayor_120 = 0\r\n for dia in dias:\r\n # Se agregan obras con demanda que pueden caber en un camión grande\r\n if int(sheet_obras.cell_value(i+4, dia+4)) > 120:\r\n mayor_120 = 1\r\n if mayor_120 == 0:\r\n obras_demanda.append(i+1)\r\n else:\r\n obras_demanda.append(i+1)\r\n obras_demanda.append(i+1.1)\r\n\r\nplantas = [i+1 for i in range(4)]\r\n# Cree conjunto dias_inventa para mantener el inventario del 8vo día positivo y que se cumpla la restricción el domingo\r\ndias_inventa = [i+1 for i in range(8)]\r\nturnos = [i+1 for i in range(3)]\r\n\r\n# Posiciones de las obras\r\nposiciones_obras = {}\r\n# Producción máxima de cada planta\r\nproduccion_max = {}\r\n# Producción máxima de cada planta\r\ndemanda_diaria = {}\r\n# Distancia entre obras y plantas\r\ndistancia_obra_planta = {}\r\n# Stock en día 1\r\nstock_inicial = {}\r\n# Costos de producción por planta\r\ncostos_planta = {}\r\n# Costos de almacenamiento por planta\r\nalmacenamiento_planta = {}\r\n# Tiempo maximo de uso de camión en despacho en dia t de obra x\r\n# Se considerada viaje de ida y vuelta\r\ntiempo_uso_camion = {}\r\n# Para cada obra se tiene el tiempo que demora a la planta más lejana\r\ntiempo_viaje_obra_planta = {}\r\n# Duracion de descarga de las obras\r\nduracion_descarga_obras = {}\r\n# Para un dia d, obras que se demoran menos de t horas en ser despachadas\r\ntiempo_despachos = {}\r\n# Turnos de disponibilidad para almacenamiento de las distintas obras\r\nturnos_ab = {}\r\nfor obra in obras_demanda:\r\n for turno in turnos:\r\n turnos_ab[(obra, turno)] = int(sheet_obras.cell_value(int(obra)+3,turno+11))\r\n \r\nposiciones_plantas = {}\r\nfor planta in plantas:\r\n posiciones_plantas[planta] = (int(sheet_plantas.cell_value(planta+2, 2)), int(sheet_plantas.cell_value(planta+2, 3)))\r\n\r\nfor planta in plantas:\r\n produccion_max[planta] = int(sheet_plantas.cell_value(planta+2, 7))\r\nfor planta in plantas:\r\n stock_inicial[planta] = int(sheet_plantas.cell_value(planta+2, 8))\r\nfor planta in plantas:\r\n costos_planta[planta] = float(sheet_plantas.cell_value(planta+2, 5))\r\nfor planta in plantas:\r\n almacenamiento_planta[planta] = float(sheet_plantas.cell_value(planta+2, 6))\r\n\r\nfor obra in obras:\r\n for dia in dias:\r\n # Se agregan obras con demanda que pueden caber en un camión grande\r\n if int(sheet_obras.cell_value(obra+3, dia+4)) <= 120:\r\n demanda_diaria[(obra, dia)]= int(sheet_obras.cell_value(obra+3, dia+4))\r\n demanda_diaria[(obra+0.1, dia)] = 0\r\n else:\r\n if 120 < int(sheet_obras.cell_value(obra+3, dia+4)) <= 130:\r\n # se usa un camion mediano al maximo y uno chico con 30-40\r\n demanda_diaria[(obra, dia)]= 90\r\n demanda_diaria[(obra+0.1, dia)]= int(sheet_obras.cell_value(obra+3, dia+4))- 90\r\n elif 130 < int(sheet_obras.cell_value(obra+3, dia+4)) <= 140:\r\n # se usa un camion mediano al maximo y uno chico con 40-50\r\n demanda_diaria[(obra, dia)]= 90\r\n demanda_diaria[(obra+0.1, dia)]= int(sheet_obras.cell_value(obra+3, dia+4))- 90\r\n elif 140 < int(sheet_obras.cell_value(obra+3, dia+4)) <= 150:\r\n # se usa un camion mediano al maximo y uno chico con 50-60\r\n demanda_diaria[(obra, dia)]= 90\r\n demanda_diaria[(obra+0.1, dia)]= int(sheet_obras.cell_value(obra+3, dia+4))- 90\r\n elif 150 < int(sheet_obras.cell_value(obra+3, dia+4)) <= 160:\r\n # se usan dos camiones medianos, uno en su maxima capacidad y el otro con 60-70\r\n demanda_diaria[(obra, dia)]= 90\r\n demanda_diaria[(obra+0.1, dia)]= int(sheet_obras.cell_value(obra+3, dia+4))- 90\r\n elif 160 < int(sheet_obras.cell_value(obra+3, dia+4)) <= 170:\r\n # se usan dos camiones medianos, uno en su maxima capacidad y el otro con 70-80\r\n demanda_diaria[(obra, dia)]= 90\r\n demanda_diaria[(obra+0.1, dia)]= int(sheet_obras.cell_value(obra+3, dia+4))- 90\r\n elif 170 < int(sheet_obras.cell_value(obra+3, dia+4)) <= 180:\r\n # se usa un camion grande en su maxima capacidad y uno chico en 50-60\r\n demanda_diaria[(obra, dia)]= 120\r\n demanda_diaria[(obra+0.1, dia)]= int(sheet_obras.cell_value(obra+3, dia+4))- 120\r\n elif 180 < int(sheet_obras.cell_value(obra+3, dia+4)) <= 190:\r\n # se usa un camion grande en su maxima capacidad y uno mediano en 60-70\r\n demanda_diaria[(obra, dia)]= 120\r\n demanda_diaria[(obra+0.1, dia)]= int(sheet_obras.cell_value(obra+3, dia+4))- 120\r\n elif 190 < int(sheet_obras.cell_value(obra+3, dia+4)) <= 200:\r\n # se usa un camion grande en su maxima capacidad y uno mediano en 70-80\r\n demanda_diaria[(obra, dia)]= 120\r\n demanda_diaria[(obra+0.1, dia)]= int(sheet_obras.cell_value(obra+3, dia+4))- 120\r\n elif 200 < int(sheet_obras.cell_value(obra+3, dia+4)) <= 210:\r\n # se usa un camion grande en su maxima capacidad y uno mediano en 80-90\r\n demanda_diaria[(obra, dia)]= 120\r\n demanda_diaria[(obra+0.1, dia)]= int(sheet_obras.cell_value(obra+3, dia+4))- 120\r\n #print(demanda_diaria)\r\n\r\n\r\nfor obra in obras_demanda:\r\n for planta in plantas:\r\n distancia_obra_planta[(obra, planta)] = int(sheet_obras.cell_value(int(obra)+3, planta+16))\r\n \r\nfor obra in obras_demanda:\r\n posiciones_obras[obra] = (int(sheet_obras.cell_value(int(obra)+3, 2)), int(sheet_obras.cell_value(int(obra)+3, 3)))\r\n\r\nfor obra in obras_demanda:\r\n # El tiempo se divide en 10 para que quede el tiempo de descarga por tonelada de hormigón\r\n duracion_descarga_obras[obra] = (float(sheet_obras.cell_value(int(obra)+3, 4))/10)\r\n\r\n# se usa para restriccion de tiempo de camiones \r\n\r\nfor obra in obras_demanda:\r\n for planta in plantas:\r\n tiempo_viaje_obra_planta[planta, obra] = float(sheet_calculos_ruteo.cell_value(int(obra)+2, int(planta)+7))\r\n#print(tiempo_viaje_obra_planta)\r\n#print(demanda_diaria)\r\n# se usa para restriccion de tiempo de camiones\r\nfor obra in obras_demanda:\r\n for dia in dias:\r\n for planta in plantas:\r\n tiempo_despachos[planta, obra, dia] = tiempo_viaje_obra_planta[planta, obra] + demanda_diaria[obra, dia]*duracion_descarga_obras[obra]\r\n # print('tiempo, obra, dia, demanda, tiempo viaje, tiempo descarga', tiempo_despacho, obra, dia, demanda_diaria[obra, dia], tiempo_maximo_viaje_obra[obra], duracion_descarga_obras[obra])\r\n\r\n#print(tiempo_uso_camion)\r\n#print(float(sheet_calculos_ruteo.cell_value(3, 20)))\r\n\r\n\r\nm = Model('Asignacion de obras a plantas')\r\n\r\n# Variable de asignación. 1 si se le asigna la obra a la planta el un día específico. 0 en otro caso\r\nx = {}\r\n\r\nfor planta in plantas:\r\n for obra in obras_demanda:\r\n for dia in dias:\r\n x[(planta, dia, obra)] = m.addVar(vtype=GRB.BINARY, name='x_{}_{}_{}'.format(\r\n planta, dia, obra))\r\nm.update()\r\n\r\nA = {}\r\n\r\nfor planta in plantas:\r\n for obra in obras_demanda:\r\n for dia in range(1,7):\r\n A[(planta, dia, obra)] = m.addVar(vtype=GRB.BINARY, name='A_{}_{}_{}'.format(\r\n planta, dia, obra))\r\nm.update()\r\n\r\n\r\n# Variable de Inventario. Cantidad de inventario disponible al principio del día en una planta.\r\n# Dura hasta el día 8 para asegurar que se cumpla la demanda\r\nInventario = {}\r\n\r\nfor planta in plantas:\r\n for dia in dias_inventa:\r\n Inventario[planta, dia] = m.addVar(vtype=GRB.CONTINUOUS, name='Inventario_{}_{}'.format(\r\n planta, dia))\r\nm.update()\r\n\r\n# Variable de producción. Cantidad producida en una planta en un día\r\nProduc = {}\r\n\r\nfor planta in plantas:\r\n for dia in range(0, 8):\r\n Produc[planta, dia] = m.addVar(vtype=GRB.CONTINUOUS, name='Produc_{}_{}'.format(\r\n planta, dia))\r\nm.update()\r\n\r\n\r\n\r\nplanta_0_1 = 0\r\nobras_asig_0_1 = []\r\nplanta_0_2 = 0\r\nobras_asig_0_2 = []\r\nplanta_0_3 = 0\r\nobras_asig_0_3 = []\r\nplanta_0_4 = 0\r\nobras_asig_0_4 = []\r\nplanta_0_5 = 0\r\nobras_asig_0_5 = []\r\nplanta_0_6 = 0\r\nobras_asig_0_6 = []\r\nplanta_0_7 = 0\r\nobras_asig_0_7 = []\r\n\r\n# 1. Si una obra tiene demanda mayor a 0 en un día específico entonces tiene que tener una planta asignada\r\nfor obra in obras_demanda:\r\n for dia in range(2, 8):\r\n if demanda_diaria[(obra, dia)] > 0:\r\n m.addConstr(quicksum(x[(planta, dia, obra)] for planta in plantas) +\r\n quicksum(A[(planta, dia-1, obra)] for planta in plantas) == 1)\r\nm.update()\r\n\r\nfor obra in obras_demanda:\r\n if demanda_diaria[(obra, 1)] > 0:\r\n m.addConstr(quicksum(x[(planta, 1, obra)] for planta in plantas) == 1)\r\nm.update()\r\n# 2. Si una obra tiene demanda igual a 0 en un día específico entonces no tiene ninguna planta asignada.\r\n# Además se agregan a la lista de plantas sin asignación para ese día específico.\r\nfor obra in obras_demanda:\r\n for dia in dias:\r\n if demanda_diaria[(obra, dia)] == 0:\r\n for planta in plantas:\r\n m.addConstr(x[(planta, dia, obra)] == 0)\r\n if dia == 1:\r\n planta_0_1 += 1\r\n obras_asig_0_1.append(obra)\r\n elif dia == 2:\r\n planta_0_2 += 1\r\n obras_asig_0_2.append(obra)\r\n elif dia == 3:\r\n planta_0_3 += 1\r\n obras_asig_0_3.append(obra)\r\n elif dia == 4:\r\n planta_0_4 += 1\r\n obras_asig_0_4.append(obra)\r\n elif dia == 5:\r\n planta_0_5 += 1\r\n obras_asig_0_5.append(obra)\r\n elif dia == 6:\r\n planta_0_6 += 1\r\n obras_asig_0_6.append(obra)\r\n elif dia == 7:\r\n planta_0_7 += 1\r\n obras_asig_0_7.append(obra)\r\nm.update()\r\n\r\nfor obra in obras_demanda:\r\n for dia in range(1, 7):\r\n if demanda_diaria[(obra, dia)] == 0:\r\n for planta in plantas:\r\n m.addConstr(A[(planta, dia, obra)] == 0)\r\nm.update()\r\n# 3. El inventario para todos los día incluyendo el primero de la semana siguiente es mayor a 0\r\nfor planta in plantas:\r\n for dia in dias_inventa:\r\n m.addConstr(Inventario[planta, dia] >= 0)\r\nm.update()\r\n\r\n# 4. El inventario para el primer día es igual al inventario inicial\r\nfor planta in plantas:\r\n m.addConstr(Inventario[planta, 1] == stock_inicial[planta])\r\nm.update()\r\n\r\n# 5. El inventario al inicio del día, más lo que se produce en ese día, menos la demanda de la obras\r\n# asignadas ese dia es igual al inventario del día siguiente\r\nfor planta in plantas:\r\n for dia in range(1, 7):\r\n m.addConstr(Inventario[planta, dia] + Produc[planta, dia] -\r\n (quicksum(x[(planta, dia, obra)]*demanda_diaria[obra, dia] for obra in obras_demanda)) -\r\n (quicksum(A[(planta, dia, obra)]*demanda_diaria[obra, dia+1] for obra in obras_demanda))\r\n == Inventario[planta, dia+1])\r\nm.update()\r\n\r\nfor planta in plantas:\r\n m.addConstr(Inventario[planta, 7] + Produc[planta, 7] -\r\n (quicksum(x[(planta, 7, obra)]*demanda_diaria[obra, 7]\r\n for obra in obras_demanda)) == Inventario[planta, 8])\r\nm.update()\r\n\r\n\r\n# 6. Suplir la demanda de cada día\r\nfor planta in plantas:\r\n m.addConstr(Inventario[planta, 7] >=\r\n (quicksum(x[(planta, 7, obra)]*demanda_diaria[obra, 7]\r\n for obra in obras_demanda)))\r\nm.update()\r\n\r\nfor planta in plantas:\r\n for dia in range(1, 7):\r\n m.addConstr(Inventario[planta, dia] >=\r\n (quicksum(x[(planta, dia, obra)]*demanda_diaria[obra, dia] +\r\n A[(planta, dia, obra)]*demanda_diaria[obra, dia+1]\r\n for obra in obras_demanda)))\r\nm.update()\r\n\r\n# 7. Producción máxima por planta\r\nfor planta in plantas:\r\n for dia in dias:\r\n m.addConstr(Produc[planta, dia] <= produccion_max[planta])\r\nm.update()\r\n\r\n\r\nobj = quicksum((Produc[planta, dia]*costos_planta[planta])\r\n for planta in plantas for dia in dias)\\\r\n + quicksum((Inventario[planta, dia]*almacenamiento_planta[planta])\r\n for dia in range(2,8) for planta in plantas) \\\r\n + quicksum((x[(planta, dia, obra)]*distancia_obra_planta[(obra, planta)]*0.0021)\r\n for obra in obras_demanda for planta in plantas for dia in dias) \\\r\n + quicksum((A[(planta, dia, obra)]*distancia_obra_planta[(obra, planta)]*0.0021)\r\n for obra in obras_demanda for planta in plantas for dia in range(1,7))\\\r\n + quicksum((A[(planta, dia, obra)]*demanda_diaria[(obra, dia+1)]*0.017)\r\n for planta in plantas for obra in obras for dia in range(1, 7))\r\n\r\n\r\nm.setObjective(obj,GRB.MINIMIZE)\r\nm.update()\r\nm.optimize()\r\n\r\n\r\n\r\nplanta_1_1=0\r\nobras_asig_1_1=[]\r\nplanta_2_1=0\r\nobras_asig_2_1=[]\r\nplanta_3_1=0\r\nobras_asig_3_1=[]\r\nplanta_4_1=0\r\nobras_asig_4_1=[]\r\nplanta_1_2=0\r\nobras_asig_1_2=[]\r\nplanta_2_2=0\r\nobras_asig_2_2=[]\r\nplanta_3_2=0\r\nobras_asig_3_2=[]\r\nplanta_4_2=0\r\nobras_asig_4_2=[]\r\nplanta_1_3=0\r\nobras_asig_1_3=[]\r\nplanta_2_3=0\r\nobras_asig_2_3=[]\r\nplanta_3_3=0\r\nobras_asig_3_3=[]\r\nplanta_4_3=0\r\nobras_asig_4_3=[]\r\nplanta_1_4=0\r\nobras_asig_1_4=[]\r\nplanta_2_4=0\r\nobras_asig_2_4=[]\r\nplanta_3_4=0\r\nobras_asig_3_4=[]\r\nplanta_4_4=0\r\nobras_asig_4_4=[]\r\nplanta_1_5=0\r\nobras_asig_1_5=[]\r\nplanta_2_5=0\r\nobras_asig_2_5=[]\r\nplanta_3_5=0\r\nobras_asig_3_5=[]\r\nplanta_4_5=0\r\nobras_asig_4_5=[]\r\nplanta_1_6=0\r\nobras_asig_1_6=[]\r\nplanta_2_6=0\r\nobras_asig_2_6=[]\r\nplanta_3_6=0\r\nobras_asig_3_6=[]\r\nplanta_4_6=0\r\nobras_asig_4_6=[]\r\nplanta_1_7=0\r\nobras_asig_1_7=[]\r\nplanta_2_7=0\r\nobras_asig_2_7=[]\r\nplanta_3_7=0\r\nobras_asig_3_7=[]\r\nplanta_4_7=0\r\nobras_asig_4_7=[]\r\n\r\nobras_asignadas = {}\r\ncantidad_obras_asignadas = {}\r\nobras_adelantadas = {}\r\ncantidad_obras_adelantadas = {}\r\nfor planta in plantas:\r\n for dia in dias:\r\n obras_asignadas[planta, dia] = []\r\n cantidad_obras_asignadas[planta, dia] = 0\r\nfor planta in plantas:\r\n for dia in dias:\r\n obras_adelantadas[planta, dia] = []\r\n cantidad_obras_adelantadas[planta, dia] = 0\r\n\r\nproduccion_plantas = []\r\ninventario_plantas = {}\r\ncostos_prod = 0\r\ncosto_inventario = 0\r\ncostos_adelantar = 0\r\nfor v in m.getVars():\r\n if v.varName[0:6] == \"Produc\":\r\n produccion_plantas.append((v.varName, v.x))\r\n costos_prod += (v.x*costos_planta[float(v.varName[7:8])])\r\n if v.varName[0:10] == \"Inventario\":\r\n inventario_plantas[(int(v.varName[11:12]), int(v.varName[13:]))]= v.x\r\n costo_inventario += (v.x*almacenamiento_planta[float(v.varName[11:12])])\r\n if v.varName[0:1] == \"A\" and int(v.varName[4:5])<7:\r\n costos_adelantar += (v.x*0.017*demanda_diaria[(int(v.varName[6:7]),int(v.varName[4:5])+1)])\r\n if v.varName[0:5]==\"x_1_1\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[1,1]+=1\r\n obras_asignadas[1, 1].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_2_1\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[2,1]+=1\r\n obras_asignadas[2, 1].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_3_1\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[3,1]+=1\r\n obras_asignadas[3, 1].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_4_1\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[4,1]+=1\r\n obras_asignadas[4, 1].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_1_2\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[1,2]+=1\r\n obras_asignadas[1, 2].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_2_2\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[2,2]+=1\r\n obras_asignadas[2, 2].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_3_2\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[3,2]+=1\r\n obras_asignadas[3, 2].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_4_2\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[4,2]+=1\r\n obras_asignadas[4, 2].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_1_3\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[1,3]+=1\r\n obras_asignadas[1, 3].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_2_3\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[2,3]+=1\r\n obras_asignadas[2, 3].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_3_3\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[3,3]+=1\r\n obras_asignadas[3, 3].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_4_3\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[4,3]+=1\r\n obras_asignadas[4, 3].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_1_4\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[1,4]+=1\r\n obras_asignadas[1, 4].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_2_4\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[2,4]+=1\r\n obras_asignadas[2, 4].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_3_4\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[3,4]+=1\r\n obras_asignadas[3, 4].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_4_4\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[4,4]+=1\r\n obras_asignadas[4, 4].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_1_5\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[1,5]+=1\r\n obras_asignadas[1, 5].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_2_5\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[2,5]+=1\r\n obras_asignadas[2, 5].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_3_5\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[3,5]+=1\r\n obras_asignadas[3, 5].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_4_5\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[4,5]+=1\r\n obras_asignadas[4, 5].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_1_6\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[1,6]+=1\r\n obras_asignadas[1, 6].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_2_6\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[2,6]+=1\r\n obras_asignadas[2, 6].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_3_6\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[3,6]+=1\r\n obras_asignadas[3, 6].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_4_6\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[4,6]+=1\r\n obras_asignadas[4, 6].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_1_7\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[1,7]+=1\r\n obras_asignadas[1, 7].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_2_7\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[2,7]+=1\r\n obras_asignadas[2, 7].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_3_7\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[3,7]+=1\r\n obras_asignadas[3, 7].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"x_4_7\":\r\n if v.x==1:\r\n cantidad_obras_asignadas[4,7]+=1\r\n obras_asignadas[4, 7].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_1_1\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[1,1]+=1\r\n obras_adelantadas[1, 1].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_2_1\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[2,1]+=1\r\n obras_adelantadas[2, 1].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_3_1\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[3,1]+=1\r\n obras_adelantadas[3, 1].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_4_1\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[4,1]+=1\r\n obras_adelantadas[4, 1].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_1_2\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[1,2]+=1\r\n obras_adelantadas[1, 2].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_2_2\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[2,2]+=1\r\n obras_adelantadas[2, 2].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_3_2\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[3,2]+=1\r\n obras_adelantadas[3, 2].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_4_2\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[4,2]+=1\r\n obras_adelantadas[3, 2].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_1_3\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[1,3]+=1\r\n obras_adelantadas[1, 3].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_2_3\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[2,3]+=1\r\n obras_adelantadas[2, 3].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_3_3\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[3,3]+=1\r\n obras_adelantadas[3, 3].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_4_3\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[4,3]+=1\r\n obras_adelantadas[4, 3].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_1_4\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[1,4]+=1\r\n obras_adelantadas[1, 4].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_2_4\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[2,4]+=1\r\n obras_adelantadas[2, 4].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_3_4\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[3,4]+=1\r\n obras_adelantadas[3, 4].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_4_4\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[4,4]+=1\r\n obras_adelantadas[4, 4].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_1_5\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[1,5]+=1\r\n obras_adelantadas[1, 5].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_2_5\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[2,5]+=1\r\n obras_adelantadas[2, 5].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_3_5\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[3,5]+=1\r\n obras_adelantadas[3, 5].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_4_5\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[4,5]+=1\r\n obras_adelantadas[4, 5].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_1_6\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[1,6]+=1\r\n obras_adelantadas[1, 6].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_2_6\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[2,6]+=1\r\n obras_adelantadas[2, 6].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_3_6\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[3,6]+=1\r\n obras_adelantadas[3, 6].append(float(v.varName[6:len(v.varName)]))\r\n elif v.varName[0:5]==\"A_4_6\":\r\n if v.x==1:\r\n cantidad_obras_adelantadas[4,6]+=1\r\n obras_adelantadas[4, 6].append(float(v.varName[6:len(v.varName)]))\r\n\r\n\"\"\"\r\nprint(\"\") \r\nprint(\"Planta 1 abastece \",planta_1_1,\" obras en el día 1\")\r\nprint(\"Obras asignadas a P1 en el día 1\",obras_asig_1_1)\r\nprint(\"\")\r\nprint(\"Planta 2 abastece \",planta_2_1,\" obras en el día 1\")\r\nprint(\"Obras asignadas a P2 en el día 1\",obras_asig_2_1)\r\nprint(\"\")\r\nprint(\"Planta 3 abastece \",planta_3_1,\" obras en el día 1\")\r\nprint(\"Obras asignadas a P3 en el día 1\",obras_asig_3_1)\r\nprint(\"\")\r\nprint(\"Planta 4 abastece \",planta_4_1,\" obras en el día 1\")\r\nprint(\"Obras asignadas a P4 en el día 1\",obras_asig_4_1)\r\nprint(\"\")\r\nprint(planta_0_1,\" obras no tienen demanda en el día 1\")\r\nprint(\"Obras sin demanda en el día 1\", obras_asig_0_1)\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"Planta 1 abastece \",planta_1_2,\" obras en el día 2\")\r\nprint(\"Obras asignadas a P1 en el día 2\",obras_asig_1_2)\r\nprint(\"\")\r\nprint(\"Planta 2 abastece \",planta_2_2,\" obras en el día 2\")\r\nprint(\"Obras asignadas a P2 en el día 2\",obras_asig_2_2)\r\nprint(\"\")\r\nprint(\"Planta 3 abastece \",planta_3_2,\" obras en el día 2\")\r\nprint(\"Obras asignadas a P3 en el día 2\",obras_asig_3_2)\r\nprint(\"\")\r\nprint(\"Planta 4 abastece \",planta_4_2,\" obras en el día 2\")\r\nprint(\"Obras asignadas a P4 en el día 2\",obras_asig_4_2)\r\nprint(\"\")\r\nprint(planta_0_2, \" obras no tienen demanda en el día 2\")\r\nprint(\"Obras sin demanda en el día 2\", obras_asig_0_2)\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"Planta 1 abastece \",planta_1_3,\" obras en el día 3\")\r\nprint(\"Obras asignadas a P1 en el día 3\",obras_asig_1_3)\r\nprint(\"\")\r\nprint(\"Planta 2 abastece \",planta_2_3,\" obras en el día 3\")\r\nprint(\"Obras asignadas a P2 en el día 3\",obras_asig_2_3)\r\nprint(\"\")\r\nprint(\"Planta 3 abastece \",planta_3_3,\" obras en el día 3\")\r\nprint(\"Obras asignadas a P3 en el día 3\",obras_asig_3_3)\r\nprint(\"\")\r\nprint(\"Planta 4 abastece \",planta_4_3,\" obras en el día 3\")\r\nprint(\"Obras asignadas a P4 en el día 3\",obras_asig_4_3)\r\nprint(\"\")\r\nprint(planta_0_3,\" obras no tienen demanda en el día 3\")\r\nprint(\"Obras sin demanda en el día 3\", obras_asig_0_3)\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"Planta 1 abastece \",planta_1_4,\" obras en el día 4\")\r\nprint(\"Obras asignadas a P1 en el día 4\",obras_asig_1_4)\r\nprint(\"\")\r\nprint(\"Planta 2 abastece \",planta_2_4,\" obras en el día 4\")\r\nprint(\"Obras asignadas a P2 en el día 4\",obras_asig_2_4)\r\nprint(\"\")\r\nprint(\"Planta 3 abastece \",planta_3_4,\" obras en el día 4\")\r\nprint(\"Obras asignadas a P3 en el día 4\",obras_asig_3_4)\r\nprint(\"\")\r\nprint(\"Planta 4 abastece \",planta_4_4,\" obras en el día 4\")\r\nprint(\"Obras asignadas a P4 en el día 4\",obras_asig_4_4)\r\nprint(\"\")\r\nprint(planta_0_4,\" obras no tienen demanda en el día 4\")\r\nprint(\"Obras sin demanda en el día 4\", obras_asig_0_4)\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"Planta 1 abastece \",planta_1_5,\" obras en el día 5\")\r\nprint(\"Obras asignadas a P1 en el día 5\",obras_asig_1_5)\r\nprint(\"\")\r\nprint(\"Planta 2 abastece \",planta_2_5,\" obras en el día 5\")\r\nprint(\"Obras asignadas a P2 en el día 5\",obras_asig_2_5)\r\nprint(\"\")\r\nprint(\"Planta 3 abastece \",planta_3_5,\" obras en el día 5\")\r\nprint(\"Obras asignadas a P3 en el día 5\",obras_asig_3_5)\r\nprint(\"\")\r\nprint(\"Planta 4 abastece \",planta_4_5,\" obras en el día 5\")\r\nprint(\"Obras asignadas a P4 en el día 5\",obras_asig_4_5)\r\nprint(\"\")\r\nprint(planta_0_5,\" obras no tienen demanda en el día 5\")\r\nprint(\"Obras sin demanda en el día 5\", obras_asig_0_5)\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"Planta 1 abastece \",planta_1_6,\" obras en el día 6\")\r\nprint(\"Obras asignadas a P1 en el día 6\",obras_asig_1_6)\r\nprint(\"\")\r\nprint(\"Planta 2 abastece \",planta_2_6,\" obras en el día 6\")\r\nprint(\"Obras asignadas a P2 en el día 6\",obras_asig_2_6)\r\nprint(\"\")\r\nprint(\"Planta 3 abastece \",planta_3_6,\" obras en el día 6\")\r\nprint(\"Obras asignadas a P3 en el día 6\",obras_asig_3_6)\r\nprint(\"\")\r\nprint(\"Planta 4 abastece \",planta_4_6,\" obras en el día 6\")\r\nprint(\"Obras asignadas a P4 en el día 6\",obras_asig_4_6)\r\nprint(\"\")\r\nprint(planta_0_6,\" obras no tienen demanda en el día 6\")\r\nprint(\"Obras sin demanda en el día 6\", obras_asig_0_6)\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"Planta 1 abastece \",planta_1_7,\" obras en el día 7\")\r\nprint(\"Obras asignadas a P1 en el día 7\",obras_asig_1_6)\r\nprint(\"\")\r\nprint(\"Planta 2 abastece \",planta_2_7,\" obras en el día 7\")\r\nprint(\"Obras asignadas a P2 en el día 7\",obras_asig_2_6)\r\nprint(\"\")\r\nprint(\"Planta 3 abastece \",planta_3_7,\" obras en el día 7\")\r\nprint(\"Obras asignadas a P3 en el día 7\",obras_asig_3_6)\r\nprint(\"\")\r\nprint(\"Planta 4 abastece \",planta_4_7,\" obras en el día 7\")\r\nprint(\"Obras asignadas a P4 en el día 7\",obras_asig_4_6)\r\nprint(\"\")\r\nprint(planta_0_7,\" obras no tienen demanda en el día 7\")\r\nprint(\"Obras sin demanda en el día 7\", obras_asig_0_7)\r\nprint(\"\")\r\nprint(\"Producción de plantas\", produccion_plantas)\r\nprint(\"Inventario plantas\", inventario_plantas)\r\n\"\"\"\r\n\r\n#lib=load_workbook(filename=\"Datos.xlsx\") #\r\n#del lib[\"Asignación\"]\r\n#ws = lib.create_sheet(\"Asignación\",index=3)#\r\n\r\n#thin_border = Border(left=Side(style='thin'), right=Side(style='thin'),\r\n # top=Side(style='thin'), bottom=Side(style='thin'))\r\n\r\n#cell = ws.cell(row=1, column=1, value=\"Obras\")\r\n#cell.font = Font(bold=True, )\r\n#cell.border = thin_border\r\n#cell = ws.cell(row=1, column=2, value=\"Planta 1\")\r\n#cell.font = Font(bold=True, )\r\n#cell.border = thin_border\r\n#cell = ws.cell(row=1, column=3, value=\"Planta 2\")\r\n# cell.font = Font(bold=True, )\r\n # cell.border = thin_border\r\n # cell = ws.cell(row=1, column=4, value=\"Planta 3\")\r\n # cell.font = Font(bold=True, )\r\n #cell.border = thin_border\r\n# cell = ws.cell(row=1, column=5, value=\"Planta 4\")\r\n # cell.font = Font(bold=True, )\r\n # cell.border = thin_border\r\n\r\n # for i in range(225):\r\n # if (i+1) in obras_asig_1:\r\n # cell = ws.cell(row=2+i, column=2, value=1)\r\n # cell = ws.cell(row=2+i, column=3, value=0)\r\n # cell = ws.cell(row=2+i, column=4, value=0)\r\n # cell = ws.cell(row=2+i, column=5, value=0)\r\n #elif (i+1) in obras_asig_2:\r\n # cell = ws.cell(row=2+i, column=2, value=0)\r\n # cell = ws.cell(row=2+i, column=3, value=1)\r\n # cell = ws.cell(row=2+i, column=4, value=0)\r\n #cell = ws.cell(row=2+i, column=5, value=0)\r\n # elif (i+1) in obras_asig_3:\r\n # cell = ws.cell(row=2+i, column=2, value=0)\r\n # cell = ws.cell(row=2+i, column=3, value=0)\r\n # cell = ws.cell(row=2+i, column=4, value=1)\r\n # cell = ws.cell(row=2+i, column=5, value=0)\r\n # else:\r\n # cell = ws.cell(row=2+i, column=2, value=0)\r\n # cell = ws.cell(row=2+i, column=3, value=0)\r\n # cell = ws.cell(row=2+i, column=4, value=0)\r\n # cell = ws.cell(row=2+i, column=5, value=1)\r\n\r\n# for i in range(225):\r\n # cell = ws.cell(row=2+i, column=1, value=\"Obra \"+str(i+1))\r\n # cell.border = thin_border\r\n\r\n # try:\r\n # lib.save(\"Datos con asignación.xlsx\")\r\n # except Excpetion as e:\r\n # print(e)\r\n # print(\"Ha ocurrido un problema al intentar guardar el archivo\")\r\n\"\"\" \r\nprint(obras_asignadas)\r\nprint(cantidad_obras_asignadas)\r\nprint(obras_adelantadas)\r\nprint(cantidad_obras_adelantadas)\r\nprint(costos_prod)\r\nprint(costo_inventario)\r\nprint(costos_adelantar)\r\nprint('Costo total: %g' % m.objVal)\r\nprint(\"Producción de plantas\", produccion_plantas)\r\nprint(\"Inventario plantas\", inventario_plantas)\r\ntotal = 0\r\nfor i in produccion_plantas:\r\n total += i[1]\r\nprint(total)\r\ntotalinventario = 0\r\nfor i in inventario_plantas.values():\r\n totalinventario += i\r\nprint(totalinventario)\r\nstock = 0\r\nfor i in stock_inicial.values():\r\n stock += i\r\nprint(stock)\r\nprint(totalinventario-total-stock)\r\ndemanda=0\r\nfor k, a in obras_adelantadas.items():\r\n for i in a:\r\n demanda += demanda_diaria[i, (float(k[1]))]\r\nfor k, a in obras_asignadas.items():\r\n for i in a:\r\n demanda += demanda_diaria[(i, float(k[1]))]\r\npedidos1 = 0\r\nfor i in demanda_diaria.values():\r\n if i>0:\r\n pedidos1+= 1\r\nprint(pedidos1)\r\npedidos = 0\r\nfor i in cantidad_obras_adelantadas.values():\r\n pedidos += i\r\nfor i in cantidad_obras_asignadas.values():\r\n pedidos += i\r\nprint(pedidos)\r\n\"\"\"","sub_path":"asignacion_beto.py","file_name":"asignacion_beto.py","file_ext":"py","file_size_in_byte":33624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"49275116","text":"# Copyright 2021, Guillermo Adrián Molina\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n\nfrom rad.rest.client.rad_types import RADInteger\n\n\nclass Property:\n def __init__(self, name, rad_type, detail=None):\n self.name = name\n self.rad_type = rad_type\n self.detail = detail\n\n def get_definition(self):\n definition = {'name': self.name}\n if issubclass(self.rad_type, RADInteger):\n definition['integer_val'] = True\n return definition\n","sub_path":"rad/rest/client/api/zfsmgr/property.py","file_name":"property.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"73391697","text":"# coding=utf-8\n\nimport torch.nn as nn\nimport torch.nn.functional\nimport torch.autograd\nimport torch.tensor\nimport torch.optim\nimport torchvision\nimport torch.utils.data\nimport torchvision.transforms\n\nfrom visdom import Visdom\nimport math\nimport numpy as np\nimport PIL.Image\nimport os\nimport time\nimport json\nimport pickle\n\nfrom Net import net as net\n\n\n# pre_boxs:[8,7,7] Variable\n# gt_boxs:[8,7,7] Variable\n\n# 把 GT的 box 从 xywh 形式 转换成x1 y1 x2 y2 形式\n# box:Variable\ndef transform_gt_box(box):\n\n result = torch.autograd.Variable( torch.FloatTensor(np.zeros([8,7,7])) ).cuda()\n result[0:2,...]=box[0:2,...]-0.5*box[4:6,...]# x1 x1\n result[2:4,...]=box[2:4,...]-0.5*box[6:8,...]# y1 y1\n\n result[4:6,...]=box[0:2,...]+0.5*box[4:6,...]# x2 x2\n result[6:8,...]=box[2:4,...]+0.5*box[6:8,...]# y2 y2\n\n return result\n\n# 把输出的 [x y w h] -> [x1 y1 x2 y2]的 box [8,7,7]\n# box Variable\ndef transform_output_box(box):\n\n # box = torch.autograd.Variable( torch.FloatTensor(8,7,7)).cuda()\n # box[...]=out_box[...]\n\n # [8,7,7] [x1 x1 y1 y1 x2 x2 y2 y2]\n result = torch.autograd.Variable( torch.FloatTensor(8,7,7)).cuda()\n\n result[0:2,...]=box[0:2,...]-0.5*box[4:6,...]# x1 x1\n result[2:4,...]=box[2:4,...]-0.5*box[6:8,...]# y1 y1\n\n result[4:6,...]=box[0:2,...]+0.5*box[4:6,...]# x2 x2\n result[6:8,...]=box[2:4,...]+0.5*box[6:8,...]# y2 y2\n\n return result\n\n\n\n\ndef iou(pre_boxs,gt_boxs):\n box_for_every_ceil= int(pre_boxs.size(0)/4)\n\n iou_truth=torch.autograd.Variable( torch.FloatTensor(np.zeros([2,7,7])) ).cuda()\n\n PRE_bounding= transform_output_box( pre_boxs )\n GT_bounding= transform_gt_box( gt_boxs )\n\n for i in range( box_for_every_ceil ):\n x1_max = torch.cat( [PRE_bounding[i+0*2,...].unsqueeze(0),GT_bounding[i+0*2,...].unsqueeze(0)],dim=0)\n x1_max,_ = torch.max(x1_max,dim=0)\n\n y1_max = torch.cat( [PRE_bounding[i+1*2,...].unsqueeze(0),GT_bounding[i+1*2,...].unsqueeze(0)],dim=0)\n y1_max,_ = torch.max(y1_max,dim=0)\n\n x2_min = torch.cat( [PRE_bounding[i+2*2,...].unsqueeze(0),GT_bounding[i+2*2,...].unsqueeze(0)],dim=0)\n x2_min,_ = torch.min(x2_min,dim=0)\n\n y2_min = torch.cat( [PRE_bounding[i+3*2,...].unsqueeze(0),GT_bounding[i+3*2,...].unsqueeze(0)],dim=0)\n y2_min,_ = torch.min(y2_min,dim=0)\n\n delta_x = x2_min - x1_max\n delta_y = y2_min - y1_max\n\n mask1=delta_x>0\n mask2=delta_y>0\n\n intersetion = (x2_min - x1_max)*(y2_min - y1_max)\n\n intersetion = intersetion * mask1.float() * mask2.float()\n\n iou_truth[i,...]= intersetion/( pre_boxs[i+2*2,...]*pre_boxs[i+2*3,...]+gt_boxs[i+2*2,...]*gt_boxs[i+2*3,...]-intersetion )\n\n return iou_truth\n\n\n\n\ndef l2_loss(input,target,reduce=True):\n\n result = torch.pow(input-target,2)\n\n if reduce:\n return result.mean()\n else:\n return result\n\n\n\n# net_out:[14,7,7] 14: [cls0 cls1 cls2 cls3] 2box[x x y y w w h h c c]\n# yolo_gt: list [11] 11:x y w h class gx gy gx1 gy1 gx2 gy2\n# return: loss[4] coord_loss object_loss noobject_loss class_loss\n\ndef loss_for_one_GT(net_out,yolo_gt,class_num=1):\n box_num = 2\n\n x, y, w, h, cls, gx, gy, gx1, gy1, gx2, gy2=yolo_gt\n # ---------------------------------------------------------------\n # [2,7,7] Variable 表示 目标的中心出现的格子\n response = np.zeros([2,7,7])\n response[0:2,gy,gx]=1#注意, tensor in pytorch is NCHW\n response = torch.autograd.Variable(torch.FloatTensor(response)).cuda()\n\n # [1,7,7] Variable 表示目标出现的格子\n obj_mask = np.zeros([1,7,7])\n obj_mask[0,gy1:gy2+1,gx1:gx2+1]=1#注意, tensor in pytorch is NCHW\n obj_mask = torch.autograd.Variable(torch.FloatTensor(obj_mask)).cuda()\n\n # [8,7,7] Variable box [x x y y w w h h]\n gt_box = np.array([x,x,y,y, w,w, h,h])\n gt_box = gt_box.reshape([8,1,1])\n gt_box = np.tile(gt_box,[1,7,7])# to [8,7,7]\n gt_box = torch.autograd.Variable(torch.FloatTensor(gt_box)).cuda()\n\n pre_box=net_out[class_num:class_num+8,...]\n # ================\n # [2,7,7] Variable 预测框和 GT的 IOU\n iou_truth = iou(pre_box,gt_box)\n\n # [2,7,7] Variable 论文中的 1(obj i,j) 表示目标的中心出现的格子,并且iou值最大的那个box\n response_iou=iou_truth*response\n I_maxium,I_index=response_iou.max(dim=0,keepdim=True)\n mask = torch.ge(response_iou,I_maxium).float()\n I = mask * response\n\n no_I = torch.autograd.Variable(torch.ones([2,7,7])).cuda() - I\n\n # [2,7,7] Variable 预测 和 真实 的 confidence\n pre_confidence=net_out[class_num+8:class_num+8+2,...]\n gt_confidence = iou_truth*response\n\n # [class,7,7] Variable 预测 和 真实 的 classes\n pre_classes=net_out[0:class_num,...]\n cls_vec = [0]*class_num\n cls_vec[cls]=1\n gt_classes = np.array(cls_vec)\n gt_classes = gt_classes.reshape([class_num,1,1])\n gt_classes = np.tile(gt_classes,[1,7,7])\n gt_classes = torch.autograd.Variable(torch.FloatTensor(gt_classes)).cuda()\n\n # -----------------------------------------------------------------\n # (1)coord loss [2,7,7]\n # x , y\n coord_loss_1=l2_loss(pre_box[0:2],gt_box[0:2],reduce=False)+l2_loss(pre_box[2:4],gt_box[2:4],reduce=False)\n # w,h\n\n coord_loss_2=l2_loss(torch.sqrt(pre_box[4:6]),torch.sqrt(gt_box[4:6]),reduce=False)+\\\n l2_loss(torch.sqrt(pre_box[6:8]),torch.sqrt(gt_box[6:8]),reduce=False)\n\n coord_loss = (coord_loss_1 + coord_loss_2)*I\n\n # (2) confidence object_loss [2,7,7]\n object_loss = l2_loss(pre_confidence,gt_confidence,reduce=False)*I\n\n # (3)confidence noobject_loss [2,7,7]\n noobject_loss=l2_loss( pre_confidence,gt_confidence*I,reduce=False)*no_I\n\n # (4)class_loss\n #[4,7,7] -> [1,7,7]\n class_loss = l2_loss(pre_classes,gt_classes,reduce=False).sum(dim=0,keepdim=True)*obj_mask\n\n\n return [coord_loss.sum() ,object_loss.sum() ,noobject_loss.sum() ,class_loss.sum()]\n\n\n\ndef loss_for_one_img(net_out,gt_for_one_img,class_num=1):\n\n coord_loss = torch.autograd.Variable( torch.FloatTensor([0]) ).cuda()\n object_loss= torch.autograd.Variable( torch.FloatTensor([0]) ).cuda()\n noobject_loss= torch.autograd.Variable( torch.FloatTensor([0]) ).cuda()\n class_loss= torch.autograd.Variable( torch.FloatTensor([0]) ).cuda()\n\n for index,item in enumerate(gt_for_one_img):\n loss=loss_for_one_GT(net_out,yolo_gt=item,class_num=class_num)\n\n # print('loss_for_one_GT: ',loss.__len__(),loss[0].size(),coord_loss.size())\n coord_loss+=loss[0]\n object_loss+=loss[1]\n noobject_loss+=loss[2]\n class_loss+=loss[3]\n\n obj_num = gt_for_one_img.__len__()\n\n coord_loss =coord_loss * 5. / obj_num\n object_loss =object_loss * 1./ obj_num\n noobject_loss =noobject_loss * 0.5/ obj_num\n class_loss = class_loss * 1./ obj_num\n return [coord_loss,object_loss,noobject_loss,class_loss]\n\n\ndef loss_for_batch(net_batch_out,gt_batch,class_num=1):\n loss = torch.autograd.Variable( torch.zeros([net_batch_out.size(0),1]) ).cuda()\n for i in range( net_batch_out.size(0) ):\n loss_list = loss_for_one_img( net_batch_out[i],gt_batch[i],class_num )\n loss[i,0] = loss_list[0]+loss_list[1]+loss_list[2]+loss_list[3]\n\n # print( 'batch img: ',i,\\\n # ' coord_loss:',loss_list[0].cpu().data.numpy()[0],\n # ' object_loss: ',loss_list[1].cpu().data.numpy()[0],\n # ' noobject_loss: ',loss_list[2].cpu().data.numpy()[0],\n # ' class_loss: ',loss_list[3].cpu().data.numpy()[0],\n # )\n\n return loss.mean()\n\n\n\n\nif __name__==\"__main__\":\n\n a=np.array([0.5,0.5,0.5,0.5,1,1,1,1])\n a = a.reshape([8,1,1])\n a = np.tile(a,[1,7,7])\n\n a = torch.autograd.Variable(torch.FloatTensor(a)).cuda()\n\n b=np.array([1,1.5,1,1.5,1,1,1,1])\n b = b.reshape([8,1,1])\n b = np.tile(b,[1,7,7])\n b = torch.autograd.Variable(torch.FloatTensor(b)).cuda()\n\n r = iou(a,b)\n\n\n print(r.size())\n\n print(r[0])\n print(r[1])\n\n\n # b=np.array([0,1,2,3,4,5,6])\n # b = np.reshape(b,[7,1])\n # b= np.tile(b,[1,7])\n # b = b[np.newaxis,...]\n # b=np.tile(b,[2,1,1])\n #\n #\n # print(b.shape)\n #\n # print(b)\n # a = torch.autograd.Variable( torch.FloatTensor(8,7,7)).cuda()\n","sub_path":"Net/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":8285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"70070736","text":"from django.urls import reverse\nfrom django.views.generic import TemplateView\nfrom django.contrib.sites.shortcuts import get_current_site\nimport requests\nimport json\n\n\n# Create your views here.\n\n\nclass UserActivation(TemplateView):\n template_name = 'front/show_message.html'\n\n def get(self, request, *args, **kwargs):\n context = self.get_context_data(**kwargs)\n\n try:\n message = self.activate(uidb64=self.kwargs['uidb64'], token=self.kwargs['token'])\n\n except Exception as e:\n message = \"Unexpected {} error\".format(e)\n context['message_to_show'] = message\n return self.render_to_response(context)\n\n def activate(self, uidb64=None, token=None, *args, **kwargs):\n \"\"\"\n Return result message. Success - user mail was confirmed and users 'is_active'\n has become True, detail: - in the other case, which means user activation failed.\n \"\"\"\n url = 'http://' + get_current_site(self.request).domain + reverse('rest_api:user-activate')\n data = {'activation': {\"uid\": uidb64, 'token': token}}\n headers = {'Content-type': 'application/json', 'Accept': 'application/json'}\n rq = requests.post(url, data=json.dumps(data), headers=headers)\n message = rq.json().get('success', None)\n\n return message if message is not None else rq.json().get('detail', None)\n","sub_path":"share_ideas.project/ideas_place/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"382723478","text":"import ConfigParser\nimport logging\nimport os\nimport select\nimport socket\nimport sys\nimport uuid\n\nhere = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, os.path.normpath(os.path.join(here, '../../utilities')))\nfrom utilities import message\nfrom utilities import models\nfrom utilities import helpers\nimport PyQt4.QtGui\nimport PyQt4.QtCore\nfrom client.ui import login\nfrom client.ui import chat\nfrom client.ui import error_message\n\nclass ChatClient():\n\n _client_socket = None\n _chat_window = None\n _user = None\n _requests = {}\n _listener = None\n\n @property\n def _logger(self):\n return self.__logger\n\n @property\n def _config(self):\n return self.__config\n\n def __init__(self):\n self.__logger = logging.getLogger(__name__)\n self.__config = Configuration('chat_client.cfg')\n\n def start(self):\n \"\"\"\n Creates connection to server, opens login window and main window\n \"\"\"\n\n # Create PyQt application\n app = PyQt4.QtGui.QApplication(sys.argv)\n\n # Create socket\n try:\n self._client_socket = self._create_socket()\n except Exception as ex:\n self._logger.exception(ex)\n error_message.ConnectionIsFailed(None)\n sys.exit()\n\n # Create socket listener\n self._listener = ListenerThread(target=self.listen)\n self._listener.start()\n\n # Create login window\n login_window = login.LoginWindow(self)\n # Connect login window to the socket listener\n login_window.connect(self._listener, PyQt4.QtCore.SIGNAL('listener_signal'), self._window_listener)\n\n if login_window.exec_() == PyQt4.QtGui.QDialog.Accepted:\n self._user = models.User()\n self._user.guest = login_window.user.guest\n self._user.login = login_window.user.login\n self._user.user_id = login_window.user.user_id\n\n login_window.disconnect(self._listener, PyQt4.QtCore.SIGNAL('listener_signal'), self._window_listener)\n del login_window\n\n # Create main window\n self._chat_window = chat.ChatWindow(self, self._user)\n\n # Init user's actions\n self._actions = {\n message.Actions.SERVER_MESSAGE: self._chat_window.server_message,\n message.Actions.USER_MESSAGE: self._chat_window.user_message,\n message.Actions.NEW_USER_IN_CHAT: self._chat_window.add_user,\n message.Actions.USER_IS_OFFLINE: self._chat_window.remove_user,\n message.Actions.USER_WAS_BANNED: self._chat_window.remove_banned_user,\n message.Actions.USER_WAS_MADE_ADMIN: self._chat_window.update_user_as_admin,\n message.Actions.USER_BAN_VOTE_IS_OPENED: self._chat_window.add_user_ban_vote,\n message.Actions.USER_BAN_VOTE_IS_CLOSED: self._chat_window.close_user_ban_vote,\n message.Actions.VOTE_FOR_USER_BAN: self._chat_window.update_user_ban_vote\n }\n\n # Connect main window to the socket listener\n self._chat_window.connect(self._listener, PyQt4.QtCore.SIGNAL('listener_signal'), self._window_listener)\n self._chat_window.show()\n\n sys.exit(app.exec_())\n\n def _window_listener(self, msg):\n \"\"\"\n Some magic to change UI from background thread\n :param msg: message from server\n \"\"\"\n callback = None\n if msg.token:\n try:\n callback = self._requests.pop(msg.token)\n except KeyError:\n self._logger.error(\"Unknown token {0} for action: {0}\".format(msg.token, msg.action))\n else:\n try:\n callback = self._actions[msg.action]\n except KeyError:\n self._logger.error(\"Unknown action: %s\" % msg.action)\n\n if callback:\n if type(msg.arguments) == tuple:\n callback(*msg.arguments)\n else:\n callback(msg.arguments)\n\n def authorize(self, login, password, guest, callback=None):\n \"\"\"\n Authorizes user\n :param callback: Callback\n \"\"\"\n model = models.Authorization()\n model.guest = guest\n model.login = login\n model.password = password\n\n msg = message.Message()\n msg.action = message.Actions.AUTHORIZE_USER\n msg.token = int(uuid.uuid4())\n msg.arguments = model\n if callback:\n self._requests[msg.token] = callback\n self._send_message(self._client_socket, msg)\n\n def register(self, login, password, callback):\n \"\"\"\n Registers user\n :param callback: Callback\n \"\"\"\n model = models.Registration()\n model.login = login\n model.password = password\n\n msg = message.Message()\n msg.action = message.Actions.REGISTER_USER\n msg.token = int(uuid.uuid4())\n msg.arguments = model\n if callback:\n self._requests[msg.token] = callback\n self._send_message(self._client_socket, msg)\n\n def create_chat(self, name, opened, private, password=\"\", callback=None):\n \"\"\"\n Creates new chat\n :param callback: Callback\n \"\"\"\n model = models.ChatCreation()\n model.name = name\n model.opened = opened\n model.private = private\n model.password = password\n\n msg = message.Message()\n msg.action = message.Actions.CREATE_CHAT\n msg.token = int(uuid.uuid4())\n msg.arguments = model\n if callback:\n self._requests[msg.token] = callback\n self._send_message(self._client_socket, msg)\n\n def enter_chat(self, chat_id, password=\"\", callback=None):\n \"\"\"\n Authorizes user in the chat\n :param callback: Callback\n \"\"\"\n model = models.ChatAuthorization()\n model.chat_id = chat_id\n model.password = password\n msg = message.Message()\n msg.action = message.Actions.ENTER_CHAT\n msg.token = int(uuid.uuid4())\n msg.arguments = model\n if callback:\n self._requests[msg.token] = callback\n self._send_message(self._client_socket, msg)\n\n def load_chats(self, callback=None):\n \"\"\"\n Loads list of chats\n :param callback: Callback\n \"\"\"\n msg = message.Message()\n msg.action = message.Actions.CHATS_LIST\n msg.token = int(uuid.uuid4())\n msg.arguments = None\n if callback:\n self._requests[msg.token] = callback\n self._send_message(self._client_socket, msg)\n\n def send_message(self, chat_id, user_message):\n \"\"\"\n Sends user's message\n :param chat_id: Chat id\n :param user_message: User message\n \"\"\"\n msg = message.Message()\n msg.action = message.Actions.USER_MESSAGE\n\n model = models.UserMessage()\n model.chat_id = chat_id\n model.message = user_message\n\n msg.arguments = model\n self._send_message(self._client_socket, msg)\n\n def ban_user(self, chat_id, user_id):\n \"\"\"\n Bans user in the chat\n :param chat_id: Chat id\n :param user_id: Banned user id\n \"\"\"\n msg = message.Message()\n msg.action = message.Actions.BAN_USER\n model = models.Ban()\n model.banned_user_id = user_id\n model.chat_id = chat_id\n msg.arguments = model\n self._send_message(self._client_socket, msg)\n\n def create_ban_vote(self, chat_id, user_id):\n \"\"\"\n Initializes ban vote\n :param chat_id: Chat id\n :param user_id: Id of the user, that must be banned\n \"\"\"\n msg = message.Message()\n msg.action = message.Actions.OPEN_USER_BAN_VOTE\n model = models.Ban()\n model.banned_user_id = user_id\n model.chat_id = chat_id\n msg.arguments = model\n self._send_message(self._client_socket, msg)\n\n def leave_chat(self, chat_id):\n \"\"\"\n Leaves chat\n :param chat_id: Chat id\n \"\"\"\n msg = message.Message()\n msg.action = message.Actions.LEAVE_CHAT\n msg.arguments = chat_id\n self._send_message(self._client_socket, msg)\n\n def make_admin(self, chat_id, user_id):\n \"\"\"\n Makes user admin of the chat\n :param chat_id: Chat id\n :param user_id: User id that must be made admin\n \"\"\"\n msg = message.Message()\n msg.action = message.Actions.MAKE_ADMIN\n model = models.UserChatPair()\n model.user_id = user_id\n model.chat_id = chat_id\n msg.arguments = model\n self._send_message(self._client_socket, msg)\n\n def vote_for_ban(self, chat_id, user_id):\n \"\"\"\n Votes for user's ban\n :param chat_id: Chat id\n :param user_id: Id of the user, that must be banned\n \"\"\"\n msg = message.Message()\n msg.action = message.Actions.VOTE_FOR_USER_BAN\n model = models.UserChatPair()\n model.user_id = user_id\n model.chat_id = chat_id\n msg.arguments = model\n self._send_message(self._client_socket, msg)\n\n def _create_socket(self):\n new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n new_socket.connect((self._config.host, self._config.port))\n new_socket.setblocking(0)\n return new_socket\n\n def _send_message(self, socket, msg):\n try:\n socket.send(message.serialize(msg))\n except Exception as ex:\n self._logger.exception(ex)\n raise ServerUnavailableError()\n\n def listen(self, callback):\n \"\"\"\n Socket listener\n :param callback: Function that is called when new message is received\n \"\"\"\n socket_list = [self._client_socket]\n stop = False\n while not stop:\n # Get the list sockets which are readable\n read_sockets, write_sockets, error_sockets = select.select(socket_list, [], [])\n if read_sockets:\n sock = read_sockets[0]\n # incoming message from remote server\n data = helpers.read_all(sock, self._config.buffer_size)\n if data:\n self._logger.info(data)\n msg = message.deserialize(data)\n else:\n msg = message.Message()\n msg.action = message.Actions.SERVER_MESSAGE\n resp = models.Response()\n resp.error = True\n resp.error_code = message.ErrorCodes.SERVER_IS_UNAVAILABLE\n resp.message = \"Server is unavailable.\"\n msg.arguments = resp\n\n # clear opened sockets\n self._client_socket.close()\n self._requests.clear()\n stop = True\n self._logger.error(\"Server is unavailable.\")\n try:\n callback(msg)\n except Exception as ex:\n self._logger.exception(ex)\n\n\nclass ListenerThread(PyQt4.QtCore.QThread):\n \"\"\"\n Is used to change UI from background thread\n \"\"\"\n\n def __init__(self, target):\n PyQt4.QtCore.QThread.__init__(self)\n self.target = target\n\n def run(self):\n self.target(self.callback)\n\n def callback(self, message):\n self.emit(PyQt4.QtCore.SIGNAL('listener_signal'), message)\n\n\nclass ServerUnavailableError(Exception):\n\n def __init__(self):\n Exception.__init__(self)\n\n\nclass Configuration():\n def __init__(self, file_name):\n self.__config = ConfigParser.RawConfigParser()\n self.__config.read(file_name)\n\n @property\n def _config(self):\n return self.__config\n\n @property\n def buffer_size(self):\n return int(self._config.get('Socket', 'buffer'))\n\n @property\n def port(self):\n return int(self._config.get('Socket', 'port'))\n\n @property\n def host(self):\n return self._config.get('Socket', 'host')\n\n","sub_path":"client/core/chat_client.py","file_name":"chat_client.py","file_ext":"py","file_size_in_byte":12052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"289812730","text":"import os\nimport re\nimport sys\nfrom typing import Dict, Optional\n\n# IMPORTANT: this list needs to be sorted in reverse\nVERSIONS = [\n dict(torch=\"1.11.0\", torchvision=\"0.11.*\", torchtext=\"\"), # nightly\n dict(torch=\"1.10.0\", torchvision=\"0.11.*\", torchtext=\"\"),\n dict(torch=\"1.9.1\", torchvision=\"0.10.1\", torchtext=\"0.10.1\"),\n dict(torch=\"1.9.0\", torchvision=\"0.10.0\", torchtext=\"0.10.0\"),\n dict(torch=\"1.8.2\", torchvision=\"0.9.1\", torchtext=\"0.9.1\"),\n dict(torch=\"1.8.1\", torchvision=\"0.9.1\", torchtext=\"0.9.1\"),\n dict(torch=\"1.8.0\", torchvision=\"0.9.0\", torchtext=\"0.9.0\"),\n dict(torch=\"1.7.1\", torchvision=\"0.8.2\", torchtext=\"0.8.1\"),\n dict(torch=\"1.7.0\", torchvision=\"0.8.1\", torchtext=\"0.8.0\"),\n dict(torch=\"1.6.0\", torchvision=\"0.7.0\", torchtext=\"0.7\"),\n]\n\n\ndef find_latest(ver: str) -> Dict[str, str]:\n # drop all except semantic version\n ver = re.search(r\"([\\.\\d]+)\", ver).groups()[0]\n # in case there remaining dot at the end - e.g \"1.9.0.dev20210504\"\n ver = ver[:-1] if ver[-1] == \".\" else ver\n print(f\"finding ecosystem versions for: {ver}\")\n\n # find first match\n for option in VERSIONS:\n if option[\"torch\"].startswith(ver):\n return option\n\n raise ValueError(f\"Missing {ver} in {VERSIONS}\")\n\n\ndef main(path_req: str, torch_version: Optional[str] = None) -> None:\n if not torch_version:\n import torch\n\n torch_version = torch.__version__\n assert torch_version, f\"invalid torch: {torch_version}\"\n\n with open(path_req) as fp:\n req = fp.read()\n # remove comments\n req = re.sub(rf\"\\s*#.*{os.linesep}\", os.linesep, req)\n\n latest = find_latest(torch_version)\n for lib, version in latest.items():\n replace = f\"{lib}=={version}\" if version else lib\n replace += os.linesep\n req = re.sub(rf\"{lib}[>=]*[\\d\\.]*{os.linesep}\", replace, req)\n\n print(req) # on purpose - to debug\n with open(path_req, \"w\") as fp:\n fp.write(req)\n\n\nif __name__ == \"__main__\":\n main(*sys.argv[1:])\n","sub_path":"requirements/adjust_versions.py","file_name":"adjust_versions.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"622426753","text":"# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# License: GNU General Public License v3. See license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe.utils import getdate, cstr, flt, fmt_money\nfrom frappe import _, _dict\nfrom erpnext.accounts.utils import get_account_currency\n\ndef execute(filters=None):\n\taccount_details = {}\n\n\tif filters and filters.get('print_in_account_currency') and \\\n\t\tnot filters.get('account'):\n\t\tfrappe.throw(_(\"Select an account to print in account currency\"))\n\n\tfor acc in frappe.db.sql(\"\"\"select name, is_group from tabAccount\"\"\", as_dict=1):\n\t\taccount_details.setdefault(acc.name, acc)\n\n\tvalidate_filters(filters, account_details)\n\n\tvalidate_party(filters)\n\n\tfilters = set_account_currency(filters)\n\n\tcolumns = get_columns(filters)\n\n\tres = get_result(filters, account_details)\n\n\treturn columns, res\n\ndef validate_filters(filters, account_details):\n\tif not filters.get('company'):\n\t\tfrappe.throw(_('{0} is mandatory').format(_('Company')))\n\n\tif filters.get(\"account\") and not account_details.get(filters.account):\n\t\tfrappe.throw(_(\"Account {0} does not exists\").format(filters.account))\n\n\tif filters.get(\"account\") and filters.get(\"group_by_account\") \\\n\t\t\tand account_details[filters.account].is_group == 0:\n\t\tfrappe.throw(_(\"Can not filter based on Account, if grouped by Account\"))\n\n\tif filters.get(\"voucher_no\") and filters.get(\"group_by_voucher\"):\n\t\tfrappe.throw(_(\"Can not filter based on Voucher No, if grouped by Voucher\"))\n\n\tif filters.from_date > filters.to_date:\n\t\tfrappe.throw(_(\"From Date must be before To Date\"))\n\n\ndef validate_party(filters):\n\tparty_type, party = filters.get(\"party_type\"), filters.get(\"party\")\n\n\tif party:\n\t\tif not party_type:\n\t\t\tfrappe.throw(_(\"To filter based on Party, select Party Type first\"))\n\t\telif not frappe.db.exists(party_type, party):\n\t\t\tfrappe.throw(_(\"Invalid {0}: {1}\").format(party_type, party))\n\ndef set_account_currency(filters):\n\tif not (filters.get(\"account\") or filters.get(\"party\")):\n\t\treturn filters\n\telse:\n\t\tfilters[\"company_currency\"] = frappe.db.get_value(\"Company\", filters.company, \"default_currency\")\n\t\taccount_currency = None\n\n\t\tif filters.get(\"account\"):\n\t\t\taccount_currency = get_account_currency(filters.account)\n\t\telif filters.get(\"party\"):\n\t\t\tgle_currency = frappe.db.get_value(\"GL Entry\", {\"party_type\": filters.party_type,\n\t\t\t\t\"party\": filters.party, \"company\": filters.company}, \"account_currency\")\n\t\t\tif gle_currency:\n\t\t\t\taccount_currency = gle_currency\n\t\t\telse:\n\t\t\t\taccount_currency = None if filters.party_type == \"Employee\" else \\\n\t\t\t\t\tfrappe.db.get_value(filters.party_type, filters.party, \"default_currency\")\n\n\t\tfilters[\"account_currency\"] = account_currency or filters.company_currency\n\n\t\tif filters.account_currency != filters.company_currency:\n\t\t\tfilters[\"show_in_account_currency\"] = 1\n\n\t\treturn filters\n\ndef get_result(filters, account_details):\n\tgl_entries = get_gl_entries(filters)\n\n\tdata = get_data_with_opening_closing(filters, account_details, gl_entries)\n\n\tresult = get_result_as_list(data, filters)\n\n\treturn result\n\ndef get_gl_entries(filters):\n\tfrom frappe.utils import cint, getdate, formatdate\n\n\tselect_fields = \"\"\", sum(debit_in_account_currency) as debit_in_account_currency,\n\t\tsum(credit_in_account_currency) as credit_in_account_currency\"\"\" \\\n\t\tif filters.get(\"show_in_account_currency\") else \"\"\n\n\tgroup_by_condition = \"group by voucher_type, voucher_no, account, cost_center\" \\\n\t\tif filters.get(\"group_by_voucher\") else \"group by name\"\n\n\ttarget_docs_list = [\"Payment Entry\",\"Purchase Invoice\",\"Expense Claim\",\"Journal Entry\",\n\t\t\"Sales Invoice\",\"Purchase Receipt\",\"Delivery Note\"]\n\tgl_entries = []\n\tfor target_doc in target_docs_list :\n\t\t\n\t\tget_all_docs = frappe.get_list(target_doc,fields=['name'],\n\t\t\tfilters=[\n\t\t\t['docstatus',\"=\", 0],\n\t\t\t['company',\"=\", filters.get('company')],\n\t\t\t[\"posting_date\",\">=\",getdate(filters.get(\"from_date\"))],\n\t\t\t[\"posting_date\",\"<=\",getdate(filters.get(\"to_date\"))]\n\t\t\t])\n\t\tfor doc_name in get_all_docs : \n\t\t\tdoc = frappe.get_doc(target_doc,doc_name[\"name\"])\n\t\t\t\n\t\t\tif target_doc == \"Payment Entry\":\n\t\t\t\tif doc.payment_type in (\"Receive\", \"Pay\") and not doc.get(\"party_account_field\"):\n\t\t\t\t\tdoc.setup_party_account_field()\n\t\t\t\t\n\t\t\t\tdoc.add_party_gl_entries(gl_entries)\n\t\t\t\tdoc.add_bank_gl_entries(gl_entries)\n\t\t\t\tdoc.add_deductions_gl_entries(gl_entries)\t\n\t\t\t\n\t\t\tif target_doc == \"Journal Entry\":\n\t\t\t\tgl_map = []\n\t\t\t\tfor d in doc.get(\"accounts\"):\n\t\t\t\t\tif d.debit or d.credit:\n\t\t\t\t\t\tgl_map.append(\n\t\t\t\t\t\t\tdoc.get_gl_dict({\n\t\t\t\t\t\t\t\t\"account\": d.account,\n\t\t\t\t\t\t\t\t\"party_type\": d.party_type,\n\t\t\t\t\t\t\t\t\"party\": d.party,\n\t\t\t\t\t\t\t\t\"against\": d.against_account,\n\t\t\t\t\t\t\t\t\"debit\": flt(d.debit, d.precision(\"debit\")),\n\t\t\t\t\t\t\t\t\"credit\": flt(d.credit, d.precision(\"credit\")),\n\t\t\t\t\t\t\t\t\"account_currency\": d.account_currency,\n\t\t\t\t\t\t\t\t\"debit_in_account_currency\": flt(d.debit_in_account_currency, d.precision(\"debit_in_account_currency\")),\n\t\t\t\t\t\t\t\t\"credit_in_account_currency\": flt(d.credit_in_account_currency, d.precision(\"credit_in_account_currency\")),\n\t\t\t\t\t\t\t\t\"against_voucher_type\": d.reference_type,\n\t\t\t\t\t\t\t\t\"against_voucher\": d.reference_name,\n\t\t\t\t\t\t\t\t\"remarks\": doc.remark,\n\t\t\t\t\t\t\t\t\"cost_center\": d.cost_center,\n\t\t\t\t\t\t\t\t\"project\": d.project\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)\n\t\t\t\tgl_entries.extend(gl_map)\n\t\t\t\t\n\t\t\tif target_doc in [\"Purchase Receipt\"]:\n\t\t\t\tfrom erpnext.stock import get_warehouse_account_map\n\t\t\t\twarehouse_account = get_warehouse_account_map()\n\t\t\t\tgl_entries.extend(doc.get_gl_entries(warehouse_account))\n\t\t\t\t\n\t\t\tif target_doc in [\"Purchase Invoice\",\"Expense Claim\",\"Sales Invoice\",\"Delivery Note\"]:\n\t\t\t\tgl_entries.extend(doc.get_gl_entries())\n\t\t\t\t\n\tgl_entries1 = frappe.db.sql(\"\"\"\n\t\tselect\n\t\t\tposting_date, account, party_type, party,\n\t\t\tsum(debit) as debit, sum(credit) as credit,\n\t\t\tvoucher_type, voucher_no, cost_center, project,\n\t\t\tagainst_voucher_type, against_voucher,\n\t\t\tremarks, against, is_opening {select_fields}\n\t\tfrom `tabGL Entry`\n\t\twhere company=%(company)s {conditions}\n\t\t{group_by_condition}\n\t\torder by posting_date, account\"\"\"\\\n\t\t.format(select_fields=select_fields, conditions=get_conditions(filters),\n\t\t\tgroup_by_condition=group_by_condition), filters, as_dict=1)\n\n\tif filters.get(\"show_draft\") !=1 and filters.get(\"show_submitted\") != 1 :\n\t\treturn []\n\t\n\telif filters.get(\"show_draft\") == 1 and filters.get(\"show_submitted\") != 1 :\n\t\treturn gl_entries\n\t\n\telif filters.get(\"show_draft\") != 1 and filters.get(\"show_submitted\") == 1 :\n\t\treturn gl_entries1\n\t\n\telif filters.get(\"show_draft\") == 1 and filters.get(\"show_submitted\") == 1 :\n\t\tgl_entries.extend(gl_entries1)\n\t\treturn gl_entries\n\n\t\n\treturn gl_entries\n\ndef get_conditions(filters):\n\tconditions = []\n\tif filters.get(\"account\"):\n\t\tlft, rgt = frappe.db.get_value(\"Account\", filters[\"account\"], [\"lft\", \"rgt\"])\n\t\tconditions.append(\"\"\"account in (select name from tabAccount\n\t\t\twhere lft>=%s and rgt<=%s and docstatus<2)\"\"\" % (lft, rgt))\n\n\tif filters.get(\"voucher_no\"):\n\t\tconditions.append(\"voucher_no=%(voucher_no)s\")\n\n\tif filters.get(\"party_type\"):\n\t\tconditions.append(\"party_type=%(party_type)s\")\n\n\tif filters.get(\"party\"):\n\t\tconditions.append(\"party=%(party)s\")\n\n\tif not (filters.get(\"account\") or filters.get(\"party\") or filters.get(\"group_by_account\")):\n\t\tconditions.append(\"posting_date >=%(from_date)s\")\n\n\tif filters.get(\"project\"):\n\t\tconditions.append(\"project=%(project)s\")\n\n\tfrom frappe.desk.reportview import build_match_conditions\n\tmatch_conditions = build_match_conditions(\"GL Entry\")\n\tif match_conditions: conditions.append(match_conditions)\n\n\treturn \"and {}\".format(\" and \".join(conditions)) if conditions else \"\"\n\ndef get_data_with_opening_closing(filters, account_details, gl_entries):\n\tdata = []\n\tgle_map = initialize_gle_map(gl_entries)\n\n\ttotals, entries = get_accountwise_gle(filters, gl_entries, gle_map)\n\n\t# Opening for filtered account\n\tdata.append(totals.opening)\n\n\tif filters.get(\"group_by_account\"):\n\t\tfor acc, acc_dict in gle_map.items():\n\t\t\tif acc_dict.entries:\n\t\t\t\t# opening\n\t\t\t\tdata.append({})\n\t\t\t\tdata.append(acc_dict.totals.opening)\n\n\t\t\t\tdata += acc_dict.entries\n\n\t\t\t\t# totals\n\t\t\t\tdata.append(acc_dict.totals.total)\n\n\t\t\t\t# closing\n\t\t\t\tdata.append(acc_dict.totals.closing)\n\t\tdata.append({})\n\n\telse:\n\t\tdata += entries\n\n\t# totals\n\tdata.append(totals.total)\n\n\t# closing\n\tdata.append(totals.closing)\n\n\treturn data\n\ndef get_totals_dict():\n\tdef _get_debit_credit_dict(label):\n\t\treturn _dict(\n\t\t\taccount = \"'{0}'\".format(label),\n\t\t\tdebit = 0.0,\n\t\t\tcredit = 0.0,\n\t\t\tdebit_in_account_currency = 0.0,\n\t\t\tcredit_in_account_currency = 0.0\n\t\t)\n\treturn _dict(\n\t\topening = _get_debit_credit_dict(_('Opening')),\n\t\ttotal = _get_debit_credit_dict(_('Total')),\n\t\tclosing = _get_debit_credit_dict(_('Closing (Opening + Total)'))\n\t)\n\ndef initialize_gle_map(gl_entries):\n\tgle_map = frappe._dict()\n\tfor gle in gl_entries:\n\t\tgle_map.setdefault(gle.account, _dict(totals = get_totals_dict(), entries = []))\n\treturn gle_map\n\ndef get_accountwise_gle(filters, gl_entries, gle_map):\n\ttotals = get_totals_dict()\n\tentries = []\n\n\tdef update_value_in_dict(data, key, gle):\n\t\tdata[key].debit += flt(gle.debit)\n\t\tdata[key].credit += flt(gle.credit)\n\n\t\tdata[key].debit_in_account_currency += flt(gle.debit_in_account_currency)\n\t\tdata[key].credit_in_account_currency += flt(gle.credit_in_account_currency)\n\n\n\tfrom_date, to_date = getdate(filters.from_date), getdate(filters.to_date)\n\tfor gle in gl_entries:\n\t\tif gle.posting_date < from_date or cstr(gle.is_opening) == \"Yes\":\n\t\t\tupdate_value_in_dict(gle_map[gle.account].totals, 'opening', gle)\n\t\t\tupdate_value_in_dict(totals, 'opening', gle)\n\t\t\t\n\t\t\tupdate_value_in_dict(gle_map[gle.account].totals, 'closing', gle)\n\t\t\tupdate_value_in_dict(totals, 'closing', gle)\n\n\t\telif gle.posting_date <= to_date:\n\t\t\tupdate_value_in_dict(gle_map[gle.account].totals, 'total', gle)\n\t\t\tupdate_value_in_dict(totals, 'total', gle)\n\t\t\tif filters.get(\"group_by_account\"):\n\t\t\t\tgle_map[gle.account].entries.append(gle)\n\t\t\telse:\n\t\t\t\tentries.append(gle)\n\n\t\t\tupdate_value_in_dict(gle_map[gle.account].totals, 'closing', gle)\n\t\t\tupdate_value_in_dict(totals, 'closing', gle)\n\n\treturn totals, entries\n\ndef get_result_as_list(data, filters):\n\tbalance, balance_in_account_currency = 0, 0\n\tinv_details = get_supplier_invoice_details()\n\n\tfor d in data:\n\t\tif not d.get('posting_date'):\n\t\t\tbalance, balance_in_account_currency = 0, 0\n\n\t\tbalance = get_balance(d, balance, 'debit', 'credit')\n\t\td['balance'] = balance\n\n\t\tif filters.get(\"show_in_account_currency\"):\n\t\t\tbalance_in_account_currency = get_balance(d, balance_in_account_currency,\n\t\t\t\t'debit_in_account_currency', 'credit_in_account_currency')\n\t\t\td['balance_in_account_currency'] = balance_in_account_currency\n\t\telse:\n\t\t\td['debit_in_account_currency'] = d.get('debit', 0)\n\t\t\td['credit_in_account_currency'] = d.get('credit', 0)\n\t\t\td['balance_in_account_currency'] = d.get('balance')\n\n\t\td['account_currency'] = filters.account_currency\n\t\td['bill_no'] = inv_details.get(d.get('against_voucher'), '')\n\n\treturn data\n\ndef get_supplier_invoice_details():\n\tinv_details = {}\n\tfor d in frappe.db.sql(\"\"\" select name, bill_no from `tabPurchase Invoice`\n\t\twhere docstatus = 1 and bill_no is not null and bill_no != '' \"\"\", as_dict=1):\n\t\tinv_details[d.name] = d.bill_no\n\n\treturn inv_details\n\ndef get_balance(row, balance, debit_field, credit_field):\n\tbalance += (row.get(debit_field, 0) - row.get(credit_field, 0))\n\n\treturn balance\n\ndef get_columns(filters):\n\tcolumns = [\n\t\t{\n\t\t\t\"label\": _(\"Posting Date\"),\n\t\t\t\"fieldname\": \"posting_date\",\n\t\t\t\"fieldtype\": \"Date\",\n\t\t\t\"width\": 90\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Account\"),\n\t\t\t\"fieldname\": \"account\",\n\t\t\t\"fieldtype\": \"Link\",\n\t\t\t\"options\": \"Account\",\n\t\t\t\"width\": 180\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Debit\"),\n\t\t\t\"fieldname\": \"debit\",\n\t\t\t\"fieldtype\": \"Float\",\n\t\t\t\"width\": 100\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Credit\"),\n\t\t\t\"fieldname\": \"credit\",\n\t\t\t\"fieldtype\": \"Float\",\n\t\t\t\"width\": 100\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Balance (Dr - Cr)\"),\n\t\t\t\"fieldname\": \"balance\",\n\t\t\t\"fieldtype\": \"Float\",\n\t\t\t\"width\": 130\n\t\t}\n\t]\n\n\tif filters.get(\"show_in_account_currency\"):\n\t\tcolumns.extend([\n\t\t\t{\n\t\t\t\t\"label\": _(\"Debit\") + \" (\" + filters.account_currency + \")\",\n\t\t\t\t\"fieldname\": \"debit_in_account_currency\",\n\t\t\t\t\"fieldtype\": \"Float\",\n\t\t\t\t\"width\": 100\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"label\": _(\"Credit\") + \" (\" + filters.account_currency + \")\",\n\t\t\t\t\"fieldname\": \"credit_in_account_currency\",\n\t\t\t\t\"fieldtype\": \"Float\",\n\t\t\t\t\"width\": 100\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"label\": _(\"Balance\") + \" (\" + filters.account_currency + \")\",\n\t\t\t\t\"fieldname\": \"balance_in_account_currency\",\n\t\t\t\t\"fieldtype\": \"Data\",\n\t\t\t\t\"width\": 100\n\t\t\t}\n\t\t])\n\n\tcolumns.extend([\n\t\t{\n\t\t\t\"label\": _(\"Voucher Type\"),\n\t\t\t\"fieldname\": \"voucher_type\",\n\t\t\t\"width\": 120\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Voucher No\"),\n\t\t\t\"fieldname\": \"voucher_no\",\n\t\t\t\"fieldtype\": \"Dynamic Link\",\n\t\t\t\"options\": \"voucher_type\",\n\t\t\t\"width\": 180\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Against Account\"),\n\t\t\t\"fieldname\": \"against\",\n\t\t\t\"width\": 120\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Party Type\"),\n\t\t\t\"fieldname\": \"party_type\",\n\t\t\t\"width\": 100\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Party\"),\n\t\t\t\"fieldname\": \"party\",\n\t\t\t\"width\": 100\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Project\"),\n\t\t\t\"options\": \"Project\",\n\t\t\t\"fieldname\": \"project\",\n\t\t\t\"width\": 100\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Cost Center\"),\n\t\t\t\"options\": \"Cost Center\",\n\t\t\t\"fieldname\": \"cost_center\",\n\t\t\t\"width\": 100\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Against Voucher Type\"),\n\t\t\t\"fieldname\": \"against_voucher_type\",\n\t\t\t\"width\": 100\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Against Voucher\"),\n\t\t\t\"fieldname\": \"against_voucher\",\n\t\t\t\"fieldtype\": \"Dynamic Link\",\n\t\t\t\"options\": \"against_voucher_type\",\n\t\t\t\"width\": 100\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Supplier Invoice No\"),\n\t\t\t\"fieldname\": \"bill_no\",\n\t\t\t\"fieldtype\": \"Data\",\n\t\t\t\"width\": 100\n\t\t},\n\t\t{\n\t\t\t\"label\": _(\"Remarks\"),\n\t\t\t\"fieldname\": \"remarks\",\n\t\t\t\"width\": 400\n\t\t}\n\t])\n\n\treturn columns\n","sub_path":"reporting/reporting/report/draft_general_ledger/draft_general_ledger2.py","file_name":"draft_general_ledger2.py","file_ext":"py","file_size_in_byte":13711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"388167512","text":"import importlib\nimport json\nimport utility\n\nactions=[\n {\"name\":\"activate\",\"arguments\":[{\"required\":True,\"type\":\"variable\",\"values\":[\"room object\",\"inventory item\"]},{\"required\":False,\"type\":\"variable\",\"values\":[\"inventory item\"]}],\"synonyms\":[\"use\",\"pick\",\"unlock\",\"lock\",\"walk through\",\"open\",\"activate\"]},\n {\"name\":\"look\",\"arguments\":[{\"required\":False,\"type\":\"variable\",\"values\":[\"room object\",\"inventory item\"]}],\"synonyms\":[\"look\",\"walk * to\",\"run * to\",\"search\",\"observe\",\"go * to\"]},\n {\"name\":\"attack\",\"arguments\":[{\"required\":True,\"type\":\"variable\",\"values\":[\"room object\"]}],\"synonyms\":[\"hit\",\"punch\",\"attack\",\"whack\"]},\n {\"name\":\"move\",\"arguments\":[{\"required\":True,\"type\":\"string\",\"values\":[(\"north\",[\"north\",\"northern\",\"up\",\"top\"]),(\"south\",[\"south\",\"southern\",\"lower\",\"bottom\"]),(\"east\",[\"east\",\"eastern\",\"right\"]),(\"south\",[\"west\",\"western\",\"left\",\"sinister\"])]}],\"synonyms\":[\"move\",\"go\",\"walk\",\"run\"]},\n {\"name\":\"create\",\"arguments\":[{\"required\":True,\"type\":\"variable\",\"values\":[\"non object\"]}],\"synonyms\":[\"create\",\"build\",\"add\"]},\n {\"name\":\"edit\",\"arguments\":[],\"synonyms\":[\"edit\",\"editroom\"]},\n {\"name\":\"remove\",\"arguments\":[{\"required\":True,\"type\":\"variable\",\"values\":[\"enviroment object\"]}],\"synonyms\":[\"destroy\",\"remove\",\"delete\"]},\n {\"name\":\"pickup\",\"arguments\":[{\"required\":True,\"type\":\"variable\",\"values\":[\"enviroment item\"]}],\"synonyms\":[\"pickup\",\"take\",\"pick up\"]},\n {\"name\":\"drop\",\"arguments\":[{\"required\":True,\"type\":\"variable\",\"values\":[\"inventory item\"]}],\"synonyms\":[\"drop\",\"let go\"]}\n]\nactionnames={}\nactionids=[]\nactionidspair=[]\ndef bar():#build action reverse search; allows for search action by synonym\n idtuple=[]\n tempids=[]\n tempidspair=[]\n for act in actions:\n for syn in act[\"synonyms\"]:\n tempids.append(syn)\n tempidspair.append(act[\"name\"])\n idtuple.append((len(syn),len(idtuple)))\n idtuple.sort()\n idtuple.reverse()\n for leng,index in idtuple:\n actionids.append(tempids[index])\n actionidspair.append(tempidspair[index])\nbar()\ndef bar2():#build second action reverse search; allows for search index by name\n for i in range(len(actions)):\n actionnames[actions[i][\"name\"]]=i\nbar2()\n\ndef cos(obj,player,layer):#Call Object Script; calls the script of a given enviroment object\n args=[]#initiate \"args\"\n for arg in obj[\"args\"]:#iterate through object arguments\n args.append(obj[arg])#add argument value to \"args\"\n objscr=importlib.import_module(\"objectScripts.\"+obj[\"script\"])#import object creation script\n objscr.main(args,player,layer)#call object script with \"args\"\n\ndef ccs(obj,player,layer):#Call Creation Script; creates an enviroment object and calls its creation script\n f=open(\"objects/\"+obj+\".data\",\"r\")#open object template file\n newobj=json.load(f)#initiate object from template\n f.close()#close object template file\n objscr=importlib.import_module(\"objectScripts.\"+newobj[\"creation\"])#import object script\n newobj=objscr.main(newobj,player,layer)#call object script on object\n return newobj#return the created object\n\ndef runworld(player,layer,request):#directly called by client; processes world interaction #WIP; should check action list for the given action and execute code accordingly. it should then process the passive actions of the other objects in the room.\n playing=True\n if request[\"action\"]==\"activate\":\n postar=[]\n tar={}\n obj,ident=request[\"arguments\"][0]\n for thing in layer[player[\"room\"]][\"contents\"]:\n if thing[\"name\"]==obj:\n postar.append(thing)\n if len(postar)<1:\n print(\"I'm sorry. I didn't understand that.\")\n elif len(postar)==1:\n tar=postar[0]\n else:\n for thing in postar:\n if(thing[\"identifier\"]==ident):\n tar=thing\n cos(tar,player,layer)\n elif request[\"action\"]==\"look\":\n obj,ident=request[\"arguments\"][0]\n if(obj==\"\"):\n print(layer[player[\"room\"]][\"look\"])\n else:\n postar=[]\n tar={}\n obj,ident=request[\"arguments\"][0]\n for thing in layer[player[\"room\"]][\"contents\"]:\n if thing[\"name\"]==obj:\n postar.append(thing)\n if len(postar)<1:\n print(\"I'm sorry. I didn't understand that.\")\n elif len(postar)==1:\n tar=postar[0]\n else:\n for thing in postar:\n if(thing[\"identifier\"]==\"ident\"):\n tar=thing\n print(tar[\"description\"])\n elif request[\"action\"]==\"attack\":\n postar=[]\n tar={}\n obj,ident=request[\"arguments\"][0]\n for thing in layer[player[\"room\"]][\"contents\"]:\n if thing[\"name\"]==obj:\n postar.append(thing)\n if len(postar)<1:\n print(\"I'm sorry. I didn't understand that.\")\n elif len(postar)==1:\n tar=postar[0]\n else:\n for thing in postar:\n if(thing[\"identifier\"]==\"ident\"):\n tar=thing\n tar[\"health\"]-=player[\"attack\"]\n elif request[\"action\"]==\"move\":\n obj,ident=request[\"arguments\"][0]\n newrequest={\"action\":\"activate\",\"arguments\":[(\"door\",obj)]}\n runworld(player,layer,newrequest)\n elif request[\"action\"]==\"stop\":\n playing=False\n elif request[\"action\"]==\"create\":\n arg,ident=request[\"arguments\"][0]\n layer[player[\"room\"]][\"contents\"].append(ccs(arg,player,layer))\n elif request[\"action\"]==\"edit\":\n obj,ident=request[\"arguments\"][0]\n if(obj==\"\"):\n desc=input(\"What would you like as the new room description? (leave blank to not change):\\n\")\n if desc!=\"\":\n layer[player[\"room\"]][\"description\"]=desc\n desc=input(\"What would you like as the new room search description? (leave blank to not change):\\n\")\n if desc!=\"\":\n layer[player[\"room\"]][\"look\"]=desc\n else:\n postar=[]\n tar={}\n for thing in layer[player[\"room\"]][\"contents\"]:\n if thing[\"name\"]==obj:\n postar.append(thing)\n if len(postar)<1:\n print(\"I'm sorry. I didn't understand that.\")\n elif len(postar)==1:\n tar=postar[0]\n else:\n for thing in postar:\n if(thing[\"identifier\"]==\"ident\"):\n tar=thing\n desc=input(\"What you like tike to change the \"+tar[\"name\"]+\"'s name to? (leave blank to not change):\\n\")\n if desc!=\"\":\n tar[\"name\"]=desc\n desc=input(\"What would you like as the new description? (leave blank to not change):\\n\")\n if desc!=\"\":\n tar[\"description\"]=desc\n elif request[\"action\"]==\"remove\":\n postar=[]\n tar={}\n obj,ident=request[\"arguments\"][0]\n for i in range(len(layer[player[\"room\"]][\"contents\"])):\n if layer[player[\"room\"]][\"contents\"][i][\"name\"]==obj:\n postar.append(i)\n if len(postar)<1:\n print(\"I'm sorry. I didn't understand that.\")\n elif len(postar)==1:\n tar=postar[0]\n else:\n for i in postar:\n if(layer[player[\"room\"]][\"contents\"][i][\"identifier\"]==ident):\n tar=i\n objscr=importlib.import_module(\"objectScripts.\"+layer[player[\"room\"]][\"contents\"][tar][\"creation\"])\n objscr.remove(layer[player[\"room\"]][\"contents\"][tar],player,layer)\n del layer[player[\"room\"]][\"contents\"][tar]\n #elif request[\"action\"]==\"pickup\":\n #elif request[\"action\"]==\"drop\":\n return player,layer,playing\n\ndef takeInput(spoken):#directly called by client; parses player input #WIP\n \n# words=spoken.split(\" \")\n# pact=[]\n# parg=[]\n# for word in words:\n# if word in actionids:\n# action=actionidspair[actionids.index(word)]\n# for argword in words:\n# if argword in \n# request={\"action\":\"activate\",\"arguments\":[(\"door\",\"north\")]}#sample ouput; format:{\"action\":\"action identifier\",\"arguments\":[alistofarguments,(\"argument\",\"identifier\"),...]}\n words=spoken.split(\" \")\n if(len(words)>=3):\n request={\"action\":words[0],\"arguments\":[(words[1],words[2])]}\n elif(len(words)==2):\n request={\"action\":words[0],\"arguments\":[(words[1],\"\")]}\n elif(len(words)==1):\n request={\"action\":words[0],\"arguments\":[(\"\",\"\")]}\n \n return request\n\ndef outputText(player,layer):#directly called by client; generates output text\n \n textblock=layer[player[\"room\"]][\"description\"].split(\"&\",1)\n textblock.insert(1,utility.mtlists(layer[player[\"room\"]][\"contents\"]))\n txt=\"\"\n for thing in textblock:\n txt+=thing\n\n return txt\n","sub_path":"MUDthing/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":7729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"325248268","text":"from networking.icmpv6_messages import ICMPv6Messages\n\nclass ICMPv6:\n\n def __init__(self, raw_data):\n\n self.messages = ICMPv6Messages()\n self.icmpv6_data = raw_data[:8]\n self.type = self.icmpv6_data[0]\n self.code = self.icmpv6_data[1]\n self.checksum = self.icmpv6_data[2] << 8 | self.icmpv6_data[3]\n self.message_body = self.icmpv6_data[5:8]\n self.data = raw_data[8:]\n\n def __str__(self):\n result = '\\t - ICMPv6 Packet:\\n'\n result += f'\\t\\t - Type: {self.type}, Type Name: {self.messages.icmp6_types[self.type]}\\n'\n result += f'\\t\\t - Code: {self.code}'\n try:\n result += f'\\t\\t - Code Name: {self.messages.icmp6_codes[self.type][self.code]}\\n'\n except:\n result += '\\n'\n result += f'\\t\\t - Checksum: {self.checksum}\\n'\n result += f'\\t\\t - ICMPv6 Data: {self.data}\\n'\n\n return result","sub_path":"networking/icmpv6.py","file_name":"icmpv6.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"252486950","text":"# MIT License\n#\n# Copyright (c) 2019 Anderson Vitor Bento\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport csv\nfrom os import walk, path, remove\nfrom tempfile import NamedTemporaryFile\nimport shutil\n\nclass CSVbase():\n\n def __init__(self, Path = '.'):\n self.path = Path + '/'\n if not path.exists(self.path):\n print('\\x1b[41m\\x1b[37m', 'Database root folder not exists! Please create a folder named \"' + Path + '\"', '\\x1b[0m')\n return None\n print('\\x1b[42m\\x1b[37m', 'Database initialized with success!', '\\x1b[0m')\n return None\n\n def getPath(self):\n return self.path\n\n def checkFile(self, table_name = ''):\n return path.exists(self.path + table_name + '.csv')\n \n def createTable(self, table_name, fields):\n with open(self.path + table_name + '.csv', mode='w+') as file:\n writer = csv.writer(file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n writer.writerow(fields)\n \n def dropTable(self,table_name):\n try:\n remove(self.path + table_name + '.csv')\n return 'Table removed with success!'\n except:\n return 'Table not removed!'\n\n def create(self, table_name, data):\n \n if not self.checkFile(table_name): return 'table not exists'\n \n fields = self.findFields(table_name)['fields']\n with open(self.path + table_name + '.csv', mode='a+') as file:\n writer = csv.DictWriter(file, fieldnames=fields)\n row = {}\n for i in fields:\n try:\n row = {**row, i: data[i]}\n except:\n pass\n writer.writerow(row)\n return 'created with success!'\n \n def read(self, table_name, conditions = None):\n \n if not self.checkFile(table_name): return 'table not exists'\n\n conds_type = []\n conds_value = []\n if conditions:\n for i in conditions:\n conds_type.append(i)\n conds_value.append(conditions[i])\n\n output = []\n with open(self.path + table_name + '.csv', mode='r') as file:\n reader = csv.DictReader(file, delimiter=',')\n for row in reader:\n x = True\n for i in range(len(conds_type)):\n try:\n x = x and row[conds_type[i]] == conds_value[i]\n except:\n pass\n if x:\n output.append(row)\n return output\n\n def update(self, table_name, conditions, newElements):\n \n if not self.checkFile(table_name): return 'table not exists'\n\n conds_type = []\n conds_value = []\n if conditions:\n for i in conditions:\n conds_type.append(i)\n conds_value.append(conditions[i])\n \n newFile = NamedTemporaryFile(mode='w', delete=False)\n\n Fields = self.findFields(table_name)\n fields = Fields['fields']\n fieldsDict = Fields['fieldsDict']\n updatedStatus = 'row not found!'\n with open(self.path + table_name + '.csv', 'r', newline='') as oldFile, newFile:\n reader = csv.DictReader(oldFile)\n writer = csv.DictWriter(newFile, fieldnames=fields)\n writer.writerow(fieldsDict)\n for row in reader:\n x = True\n for i in range(len(conds_type)):\n try:\n x = x and row[conds_type[i]] == conds_value[i]\n except:\n pass\n if x:\n copy = {**newElements}\n for i in copy:\n try:\n if(fieldsDict[i]):\n pass \n except:\n del newElements[i]\n row = { **row, **newElements }\n updatedStatus = 'updated with success!'\n writer.writerow(row)\n\n shutil.move(newFile.name, self.path + table_name + '.csv')\n return updatedStatus\n\n def delete(self, table_name, conditions):\n \n if not self.checkFile(table_name): return 'table not exists'\n\n conds_type = []\n conds_value = []\n if conditions:\n for i in conditions:\n conds_type.append(i)\n conds_value.append(conditions[i])\n \n newFile = NamedTemporaryFile(mode='w', delete=False)\n\n Fields = self.findFields(table_name)\n fields = Fields['fields']\n fieldsDict = Fields['fieldsDict']\n\n with open(self.path + table_name + '.csv', 'r', newline='') as oldFile, newFile:\n reader = csv.DictReader(oldFile)\n writer = csv.DictWriter(newFile, fieldnames=fields)\n writer.writerow(fieldsDict)\n for row in reader:\n x = True\n for i in range(len(conds_type)):\n try:\n x = x and row[conds_type[i]] == conds_value[i]\n except:\n pass\n if not x:\n writer.writerow(row)\n \n\n shutil.move(newFile.name, self.path + table_name + '.csv')\n return 'removed with success!'\n\n def listTables(self,p = '', extension = True):\n foo = []\n for (dirpath, dirnames, filenames) in walk(\"./\" + self.path + p):\n if (not extension):\n for i in range(len(filenames)):\n filenames[i] = filenames[i].split(\".csv\")[0]\n foo.extend(filenames)\n break\n return foo\t\n\n def findFields(self, table_name):\n fields = []\n fieldsDict = {}\n\n with open(self.path + table_name + '.csv', mode='r') as file:\n reader = csv.reader(file, delimiter=',')\n for row in reader:\n for field in row:\n fields.append(field)\n fieldsDict = {\n **fieldsDict,\n field: field\n }\n break\n \n return { 'fields': fields, 'fieldsDict': fieldsDict }\n\n def readAll(self, table_name, type=None):\n data = self.read(table_name)\n fields = self.findFields(table_name)['fields']\n s = dict()\n for column in fields:\n s[column] = []\n for row in data:\n for column in fields:\n if type == float:\n s[column].append(float(row[column]))\n elif type == int:\n s[column].append(int(float(row[column])))\n else:\n s[column].append(row[column])\n return s","sub_path":"csvbase/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"157866709","text":"#!/usr/bin/env python3\nimport numpy as np\nimport tensorflow as tf\n\nclass MNISTVectorLoader(object):\n def __init__(self, seed):\n # Load full MNIST, merge train set and test set\n (X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()\n self.X = np.concatenate((X_train, X_test), axis=0)\n self.y = np.concatenate((y_train, y_test), axis=0)\n \n # Transform the features in vector \n self.X = self.X.astype(np.float32).reshape(-1, 28*28) / 255.0\n self.y = self.y.astype(np.int32)\n \n # Shuffle the data\n np.random.seed(seed=seed)\n N = self.X.shape[0]\n shuffle_index = np.random.permutation(N)\n self.X = self.X[shuffle_index, :] \n self.y = self.y[shuffle_index]\n \n def samples(self, N):\n if N < 1:\n return None\n elif N > self.X.shape[0]:\n return (self.X, self.y)\n else:\n return (self.X[:N,:], self.y[:N])\n\nclass MNISTImageLoader(object):\n def __init__(self, seed):\n # Load full MNIST, merge train set and test set\n (X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()\n self.X = np.expand_dims(np.concatenate((X_train, X_test), axis=0), axis=3)\n self.y = np.concatenate((y_train, y_test), axis=0) \n \n # Shuffle the data\n np.random.seed(seed=seed)\n N = self.X.shape[0]\n shuffle_index = np.random.permutation(N)\n self.X = self.X[shuffle_index, :, :] \n self.y = self.y[shuffle_index]\n \n def samples(self, N):\n if N < 1:\n return None\n elif N > self.X.shape[0]:\n return (self.X, self.y)\n else:\n return (self.X[:N,:], self.y[:N])\n \nclass MNISTContestLoader(object):\n def __init__(self):\n # Load full MNIST, merge train set and test set\n (X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()\n \n self.X_train = np.expand_dims(X_train, axis=3)\n self.y_train = y_train \n \n self.X_test = np.expand_dims(X_test, axis=3)\n self.y_test = y_test\n \n def get_training_set(self):\n return (self.X_train, self.y_train)\n \n def get_testing_set(self):\n return (self.X_test, self.y_test)\n \nimport requests\ntry:\n from tqdm import tqdm\nexcept ImportError:\n tqdm = lambda x, total, unit: x # If tqdm doesn't exist, replace it with a function that does nothing\n print('**** Could not import tqdm. Please install tqdm for download progressbars! (pip install tqdm) ****')\n \nclass KMNISTContestLoader(object):\n \n def __init__(self):\n \n self.filelist = ['http://codh.rois.ac.jp/kmnist/dataset/kmnist/kmnist-train-imgs.npz',\n 'http://codh.rois.ac.jp/kmnist/dataset/kmnist/kmnist-train-labels.npz',\n 'http://codh.rois.ac.jp/kmnist/dataset/kmnist/kmnist-test-imgs.npz',\n 'http://codh.rois.ac.jp/kmnist/dataset/kmnist/kmnist-test-labels.npz']\n \n self.download_list()\n \n self.X_train = np.expand_dims(np.load('kmnist-train-imgs.npz')['arr_0'],3)\n self.X_test = np.expand_dims(np.load('kmnist-test-imgs.npz')['arr_0'],3)\n self.y_train = np.load('kmnist-train-labels.npz')['arr_0']\n self.y_test = np.load('kmnist-test-labels.npz')['arr_0']\n \n # Download a list of files\n def download_list(self):\n for url in self.filelist:\n path = url.split('/')[-1]\n r = requests.get(url, stream=True)\n with open(path, 'wb') as f:\n total_length = int(r.headers.get('content-length'))\n print('Downloading {} - {:.1f} MB'.format(path, (total_length / 1024000)))\n for chunk in tqdm(r.iter_content(chunk_size=1024), total=int(total_length / 1024) + 1, unit=\"KB\"):\n if chunk:\n f.write(chunk)\n \n print('All dataset files downloaded!')\n\n def get_training_set(self):\n return (self.X_train, self.y_train)\n \n def get_testing_set(self):\n return (self.X_test, self.y_test)\n \n# Main\nif __name__ == \"__main__\":\n mnist_vector_loader = MNISTVectorLoader(42)\n X, y = mnist_vector_loader.samples(10)\n mnist_image_loader = MNISTImageLoader(42)\n X, y = mnist_image_loader.samples(10)","sub_path":"Machine_learning/day3/mnist_loader.py","file_name":"mnist_loader.py","file_ext":"py","file_size_in_byte":4483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"202089525","text":"import os\nimport glob\nfrom video import VideoFile\n\nresult = []\nfor x in os.walk('/mnt/d/Dizi'):\n for y in glob.glob(os.path.join(x[0], '*.mkv')):\n result.append(y)\nfor vf in result:\n in_vid = VideoFile(vf)\n if in_vid.format_name != '.mp4' or \\\n in_vid.height > 480 or \\\n in_vid.width > 840 or \\\n in_vid.bit_rate > 768:\n in_vid.convert()\n ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"571380415","text":"#ouvrir un fichier data.txt\n#lire les valeurs\n#mettre les valeurs dans un dictionnaire\n#trier le dictionnaire par valeur\nimport re\n\nfile = open('data.txt', 'r')\n#print(file.read())\n\nList = file.read()\nregex = r\"(\\w*),(.*)\\n?\"\n\ntest_str = (\"valeur, 456\\nvaleur, 32\\nvaleur, 5\")\n\nmatches = re.finditer(regex, test_str)\nDickus = dict()\nfor matchNum, match in enumerate(matches):\n matchNum = matchNum + 1\n\n for groupNum in range(0, len(match.groups())):\n groupNum = groupNum + 1\n\n print(\"Group {groupNum} found: {group}\".format(groupNum=groupNum, group=match.group(groupNum)))\n if groupNum == 2:\n a = match.group(groupNum - 1)\n b = match.group(groupNum)\n print(a,',',b)\n Dickus[a] = b\n\nprint(sorted(Dickus))\n\nfile.close()","sub_path":"exemple_4_OT.py","file_name":"exemple_4_OT.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"478160916","text":"from Tkinter import *\nimport os\nimport time\nimport math\nimport random\n\nX_COUNT = 3\nY_COUNT = 3\n\nERROR = -1\nRET_OK = 0\nclass smile_game():\n def __init__(self):\n self.pix = 200\n self.width_new = self.pix\n self.height_new = self.pix\n self.subsample = int(math.ceil(1500/self.pix)) + 1\n self.top_margin = 10\n self.left_margin = 10\n self.right_x = 0\n self.right_y = 0\n self.positive_faces = 8\n self.negative_faces = 11\n self.count = 0\n self.count_success = 0\n self.start_time = 0\n self.path_top = os.path.abspath('.')\n print(\"path:\",self.path_top)\n\n def show_new(self):\n self.right_x = random.randint(0, X_COUNT - 1)\n self.right_y = random.randint(0, Y_COUNT - 1)\n\n for x in range(0, X_COUNT):\n for y in range(0, Y_COUNT):\n if x == self.right_x and y == self.right_y:\n ret, image = self.get_positive_face()\n if ret == ERROR:\n return ERROR\n else:\n ret, image = self.get_negative_face()\n if ret == ERROR:\n return ERROR\n self.cv.create_image(((x * 2 + 1) * self.width_new / 2 + self.left_margin, \\\n (y * 2 + 1) * self.height_new / 2 + self.top_margin), image=image)\n return RET_OK\n\n\n def button_callback(self,event):\n print (\"clicked at\", event.x, event.y)\n self.count += 1\n self.x_num = math.floor(event.x / self.width_new)\n self.y_num = math.floor(event.y / self.height_new)\n if self.x_num == self.right_x and self.y_num == self.right_y:\n self.count_success += 1\n time.sleep(0.3)\n self.cv.delete(\"all\")\n self.show_new()\n\n\n def motion_callback(self,event):\n self.x_num = math.floor(event.x / self.width_new)\n self.y_num = math.floor(event.y / self.height_new)\n #print(\"right\", self.right_x, self.right_y)\n #print(\"now\", self.x_num, self.y_num)\n\n if self.x_num == self.right_x and self.y_num == self.right_y:\n self.draw_outline(self.x_num, self.y_num, \"green\")\n else:\n self.draw_outline(self.x_num, self.y_num, \"red\")\n\n\n def draw_outline(self, num_x, num_y, color):\n self.cv.delete(\"rectangle\")\n if num_x > X_COUNT - 1 or num_y > Y_COUNT - 1:\n return\n tangle = self.cv.create_rectangle(num_x * self.width_new + self.left_margin, num_y * self.height_new + self.top_margin, \\\n (num_x + 1) * self.width_new + self.left_margin, (num_y + 1) * self.height_new + self.top_margin, \\\n outline=color, tags=(\"rectangle\"))\n\n\n def get_positive_face(self):\n positive_count = len(self.imgs_positive)\n if positive_count == 0:\n return ERROR, \"\"\n positive_num = random.randint(0, positive_count - 1)\n return RET_OK, self.imgs_positive[positive_num]\n\n\n def get_negative_face(self):\n negative_count = len(self.imgs_negative)\n if negative_count == 0:\n return ERROR, \"\"\n negative_num = random.randint(0, negative_count - 1)\n return RET_OK, self.imgs_negative[negative_num]\n\n\n def init_faces(self):\n self.imgs_positive=[]\n self.imgs_negative=[]\n for i in range(0, self.positive_faces):\n img = PhotoImage(file= str(self.path_top) + '/positive_pics/' + 'positive_' + str(i) + '.gif')\n img = img.subsample(self.subsample)\n self.imgs_positive.append(img )\n\n for i in range(0, self.negative_faces):\n img = PhotoImage(file= str(self.path_top) + '/negative_pics/' + 'negative_' + str(i) + '.gif')\n img = img.subsample(self.subsample)\n self.imgs_negative.append(img)\n\n\n def __show(self, text):\n ## First, Time!\n now_time = time.time()\n dur = now_time - self.start_time\n dur = math.ceil(dur)\n dur_str = \"You have Played: \" + str(dur) + \" seconds\"\n\n count_success_str = \"You have succeed: \" + str(self.count_success) + \" times\"\n count_str = \"You have Played: \" + str(self.count) + \" times\"\n\n string = dur_str + '\\n' + count_success_str + '\\n' + count_str\n\n text.delete(1.0, 'end')\n text.insert('end', string)\n text.after(self.delay, self.__show, text)\n\n def game(self):\n self.root = Tk()\n self.cv = Canvas(self.root, bg='white', width=self.width_new * X_COUNT + self.left_margin, height=self.height_new * Y_COUNT + self.top_margin)\n self.init_faces()\n\n self.show_new()\n self.cv.bind(\"\", self.button_callback)\n self.cv.bind(\"\", self.motion_callback)\n self.cv.pack()\n\n #imgs_negative = PhotoImage(file='./positive_0.gif')\n #img = imgs_negative.subsample(10)\n #self.cv.create_image(100,100,image = img)\n\n self.delay = 200\n self.text = Text(self.root)\n self.text.pack()\n self.__show(self.text, )\n self.start_time = time.time()\n\n self.root.mainloop()\n\n\nif __name__==\"__main__\":\n game = smile_game()\n game.game()\n","sub_path":"smile_game/smile_game.py","file_name":"smile_game.py","file_ext":"py","file_size_in_byte":5267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"296723528","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\nfrom app_utils.mongo_util import insert_to_mongo_many\nfrom app_utils.mongo_util import upsert_set_to_mongo\nfrom app_utils.mongo_util import mongoClient\nfrom app_utils.requests_util import getResponseNoSession\nfrom app_utils.requests_util import getResponseUseSession\nfrom app_utils.requests_util import getSdutSessionLogined\nimport time\nimport pymongo\nimport app_utils.static_parameter as STP\nfrom app_utils.debug import debugput\n\n\ndef updateSDUTOJ_USER():\n __get_user_base_url = STP.USER_API_BASE_URL\n __get_user_option = {\n 'uid': '0',\n 'cmp': 'g',\n 'limit': '1000',\n 'order': 'ASC',\n }\n client = mongoClient()\n collection = client[STP.DBNAME][STP.SDUTOJ_USER]\n _top = collection.find().sort([('uid', -1)])\n if not _top.count() == 0:\n __get_user_option['uid'] = _top[0]['uid']\n # __get_solution_option['runid'] = collection.find_one()['uid']\n __response = getResponseNoSession(\n __get_user_base_url, para=__get_user_option, site='getting user list')\n while __response.status_code != 200:\n __response = getResponseNoSession(\n __get_user_base_url, para=__get_user_option, site='getting user list')\n debugput(__get_user_option)\n while __response.text != '[]':\n # print __response.url\n temp__submit_dict_list = json.loads(__response.text)\n\n insert_to_mongo_many(temp__submit_dict_list,\n STP.DBNAME, STP.SDUTOJ_USER)\n __get_user_option['uid'] = temp__submit_dict_list[-1]['uid']\n debugput(__get_user_option)\n # print temp__submit_dict_list[-1]['runid']\n __response = getResponseNoSession(\n __get_user_base_url, para=__get_user_option, site='getting user list')\n while __response.status_code != 200:\n __response = getResponseNoSession(\n __get_user_base_url, para=__get_user_option, site='getting user list')\n client.close()\n\n\ndef update():\n starttime = time.time()\n updateSDUTOJ_USER()\n endtime = time.time()\n usetime = endtime-starttime\n debugput(\"updata user time : \"+str(usetime)+\"S\")\n","sub_path":"app_spiders/_user_spider.py","file_name":"_user_spider.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"97670145","text":"class Room:\n def __init__(self, slug, name, desc, dark=False, dark_desc=\"\", no_mobs=False, no_drop=False, init_items=[]):\n self.slug = slug\n self.name = name\n self.desc = desc\n self.dark = dark\n self.dark_desc = dark_desc\n self.no_mobs = no_mobs\n self.no_drop = no_drop\n self.items = init_items\n\n def __str__(self):\n return self.name\n\n def add_item(self, item):\n self.items.append(item)\n\n def remove_item(self, item):\n if item in self.items:\n if \"obtainable\" in item.tags:\n self.items.remove(item)\n return True\n else:\n print(\"You decide to leave it there.\\n\")\n return False\n else:\n return False","sub_path":"src/room.py","file_name":"room.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"454340607","text":"# simple script to plot xy data with two y axes\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ntime, Qin, Pin = np.loadtxt('/home/cmerl/Desktop/AllData.txt', usecols=(0, 5, 6), unpack=True)\n\t \nfig, ax1 = plt.subplots()\nax1.plot(time, Pin)\nax1.set_xlabel('time (s)')\nax1.set_ylabel('Pressure')\n\nax2 = ax1.twinx()\nax2.plot(time, Qin)\nax2.set_ylabel('Flow')\n\nplt.show()\n","sub_path":"xyplot_2.py","file_name":"xyplot_2.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"293196028","text":"#!/usr/bin/env python\n\n\"\"\"\nThis is a test bed script to plot imported signals in both time and frequency domain.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom siggens import one_pulse as gen\n\n# simulation parameters\nf_sampl = 100e3 \t# sampling frequency in kHz\nT_int = 1 \t\t\t# entire signal length in ms\nf_IF = 10.7e3 \t\t# IF frequency in kHz\n\nchr = 1.023e3 \t\t# chip rate in kbps\n#\tfs = 10e3\n#\tN = 1e5\namp = 2*np.sqrt(2)\n#\tfreq = 1270.0\nnoise_power = 0.001 * f_sampl / 2\n#\ttime = np.arange(N) / fs\n\nt = np.arange(0,T_int,1/f_sampl)\n\n\ny = gen.square_p(t,.1,.2)\n\n\nplt.plot(t, y)\nplt.grid(True)\nplt.show()\n\n\n","sub_path":"report/latex/ch_01/src/testbed.py","file_name":"testbed.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"9615055","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\nfrom PySide import QtGui, QtCore\nfrom imgZoo.imagenesZoo import Ui_ImagenesZoo\n\nclass ImgZoo(QtGui.QWidget):\n\n\tdef __init__(self, parent = None):\n\t\tQtGui.QWidget.__init__(self, parent)\n\t\tself.ui = Ui_ImagenesZoo()\n\t\tself.ui.setupUi(self)\n\n\t\tself.ui.labelImagen1.setVisible(True)\n\t\tself.ui.labelImagen2.setVisible(False)\n\n\t\tself.ui.botonSiguiente.clicked.connect(self.mov_derecha)\n\t\tself.ui.botonAnterior.clicked.connect(self.mov_izquierda)\n\n\tdef mov_derecha(self):\n\t\tself.ui.labelImagen1.setVisible(False)\n\t\tself.ui.labelImagen2.setVisible(True)\n\n\tdef mov_izquierda(self):\n\t\tself.ui.labelImagen2.setVisible(False)\n\t\tself.ui.labelImagen1.setVisible(True)\n\n\n\nif __name__ == '__main__':\n\tapp = QtGui.QApplication(sys.argv)\n\tex = ImgZoo()\n\tex.show()\n\tsys.exit(app.exec_())","sub_path":"ctrl_imagenesZoo.py","file_name":"ctrl_imagenesZoo.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"237342481","text":"import json\n\nartists_in = open('artists.csv', 'r+').readlines()\n\nmodel_fixes = []\npk_count = 1\n\nfor line in artists_in:\n artist = line.split(\",\", 1)[1].strip()\n pk = pk_count\n pk_count += 1\n fix_dict = dict()\n fix_dict['model'] = \"music_recommender.artist\"\n fix_dict['pk'] = pk\n fix_dict['fields'] = {}\n fix_dict['fields']['name'] = artist\n print(fix_dict)\n model_fixes += [fix_dict]\n\nfixes = json.dumps(model_fixes)\nwith open(\"artists_fixture.json\", 'w+') as artists_out:\n artists_out.write(fixes)\n artists_out.close()\n","sub_path":"database_init/create_fixture.py","file_name":"create_fixture.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"308339485","text":"# -*- coding: utf-8 -*-\n\nfrom dp_tornado.engine.controller import Controller as dpController\nimport requests\n\n\nclass VodController(dpController):\n\n def post(self):\n url = \"http://api.fnup.com/Liveservice/mobile/getvodfiles.asp\"\n\n data = {\n 'bRoom': self.get_argument(\"room_no\"),\n 'site_id': \"general\",\n 'platform': \"ad\"\n }\n\n r = requests.post(url, data=data)\n\n return self.write(r.content)","sub_path":"controller/mobile/call/vod/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"163310599","text":"string1 = input(\"Enter a string: \")\n\n\n# answer with strings\ndef delete_spaces(string):\n string2 = string.split(\" \")\n string3=\"\"\n #string2.strip() // not working\n #string2.replace(\" \", \"\") // not working too\n for i in string2:\n if i != '':\n string3 += i + ' '\n return string3\n\n\nprint(delete_spaces(string1))\n\n\n# answer with arrays\n#def delete_spaces(string):\n# string2 = string.split(\" \")\n # array = []\n # for i in string2:\n # if i != '':\n # array.append(i)\n #return ' '.join(array)\n\n\n#print(delete_spaces(string1))","sub_path":"hw_5/hw_5_2.py","file_name":"hw_5_2.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"231429097","text":"#!/usr/bin/python\n# Copyright 2017-2020 IBM Corp. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\n# For information on the format of the ANSIBLE_METADATA, DOCUMENTATION,\n# EXAMPLES, and RETURN strings, see\n# http://docs.ansible.com/ansible/dev_guide/developing_modules_documenting.html\n\nANSIBLE_METADATA = {\n 'metadata_version': '1.1',\n 'status': ['stableinterface'],\n 'supported_by': 'community',\n 'shipped_by': 'other',\n 'other_repo_url': 'https://github.com/zhmcclient/zhmc-ansible-modules'\n}\n\nDOCUMENTATION = \"\"\"\n---\nmodule: zhmc_partition\nversion_added: \"2.9.0\"\nshort_description: Create partitions\ndescription:\n - Gather facts about a partition of a CPC (Z system), including its HBAs,\n NICs, and virtual functions.\n - Create, update, or delete a partition. The HBAs, NICs, and virtual\n functions of the partition are managed by separate Ansible modules.\n - Start or stop a partition.\nseealso:\n - module: zhmc_hba\n - module: zhmc_nic\n - module: zhmc_virtual_function\nauthor:\n - Andreas Maier (@andy-maier)\n - Andreas Scheuring (@scheuran)\n - Juergen Leopold (@leopoldjuergen)\nrequirements:\n - Access to the WS API of the HMC of the targeted Z system\n (see :term:`HMC API`). The targeted Z system must be in the Dynamic\n Partition Manager (DPM) operational mode.\noptions:\n hmc_host:\n description:\n - The hostname or IP address of the HMC.\n type: str\n required: true\n hmc_auth:\n description:\n - The authentication credentials for the HMC, as a dictionary of userid,\n password.\n type: dict\n required: true\n suboptions:\n userid:\n description:\n - The userid (username) for authenticating with the HMC.\n type: str\n required: true\n password:\n description:\n - The password for authenticating with the HMC.\n type: str\n required: true\n cpc_name:\n description:\n - The name of the CPC with the target partition.\n type: str\n required: true\n name:\n description:\n - The name of the target partition.\n type: str\n required: true\n state:\n description:\n - \"The desired state for the partition. All states are fully idempotent\n within the limits of the properties that can be changed:\"\n - \"* C(absent): Ensures that the partition does not exist in the specified\n CPC.\"\n - \"* C(stopped): Ensures that the partition exists in the specified CPC,\n has the specified properties, and is in the 'stopped' status.\"\n - \"* C(active): Ensures that the partition exists in the specified CPC,\n has the specified properties, and is in the 'active' or 'degraded'\n status.\"\n - \"* C(facts): Returns the partition properties and the properties of its\n child resources (HBAs, NICs, and virtual functions).\"\n type: str\n required: true\n choices: ['absent', 'stopped', 'active', 'facts']\n properties:\n description:\n - \"Dictionary with input properties for the partition, for\n C(state=stopped) and C(state=active). Key is the property name with\n underscores instead of hyphens, and value is the property value in\n YAML syntax. Integer properties may also be provided as decimal\n strings. Will be ignored for C(state=absent).\"\n - \"The possible input properties in this dictionary are the properties\n defined as writeable in the data model for Partition resources\n (where the property names contain underscores instead of hyphens),\n with the following exceptions:\"\n - \"* C(name): Cannot be specified because the name has already been\n specified in the C(name) module parameter.\"\n - \"* C(type): Cannot be changed once the partition exists, because\n updating it is not supported.\"\n - \"* C(boot_storage_device): Cannot be specified because this information\n is specified using the artificial property C(boot_storage_hba_name).\"\n - \"* C(boot_network_device): Cannot be specified because this information\n is specified using the artificial property C(boot_network_nic_name).\"\n - \"* C(boot_storage_hba_name): The name of the HBA whose URI is used to\n construct C(boot_storage_device). Specifying it requires that the\n partition exists.\"\n - \"* C(boot_network_nic_name): The name of the NIC whose URI is used to\n construct C(boot_network_device). Specifying it requires that the\n partition exists.\"\n - \"* C(crypto_configuration): The crypto configuration for the partition,\n in the format of the C(crypto-configuration) property of the\n partition (see :term:`HMC API` for details), with the exception that\n adapters are specified with their names in field\n C(crypto_adapter_names) instead of their URIs in field\n C(crypto_adapter_uris). If the C(crypto_adapter_names) field is null,\n all crypto adapters of the CPC will be used.\"\n - \"Properties omitted in this dictionary will remain unchanged when the\n partition already exists, and will get the default value defined in\n the data model for partitions in the :term:`HMC API` when the partition\n is being created.\"\n type: dict\n required: false\n default: null\n expand_storage_groups:\n description:\n - \"Boolean that controls whether the returned partition contains\n an additional artificial property 'storage-groups' that is the list\n of storage groups attached to the partition, with properties as\n described for the zhmc_storage_group module with expand=true.\"\n required: false\n type: bool\n default: false\n expand_crypto_adapters:\n description:\n - \"Boolean that controls whether the returned partition contains\n an additional artificial property 'crypto-adapters' in its\n 'crypto-configuration' property that is the list\n of crypto adapters attached to the partition, with properties as\n described for the zhmc_adapter module.\"\n required: false\n type: bool\n default: false\n log_file:\n description:\n - \"File path of a log file to which the logic flow of this module as well\n as interactions with the HMC are logged. If null, logging will be\n propagated to the Python root logger.\"\n type: str\n required: false\n default: null\n _faked_session:\n description:\n - \"An internal parameter used for testing the module.\"\n required: false\n type: raw\n default: null\n\"\"\"\n\nEXAMPLES = \"\"\"\n---\n# Note: The following examples assume that some variables named 'my_*' are set.\n\n# Because configuring LUN masking in the SAN requires the host WWPN, and the\n# host WWPN is automatically assigned and will be known only after an HBA has\n# been added to the partition, the partition needs to be created in stopped\n# state. Also, because the HBA has not yet been created, the boot\n# configuration cannot be done yet:\n- name: Ensure the partition exists and is stopped\n zhmc_partition:\n hmc_host: \"{{ my_hmc_host }}\"\n hmc_auth: \"{{ my_hmc_auth }}\"\n cpc_name: \"{{ my_cpc_name }}\"\n name: \"{{ my_partition_name }}\"\n state: stopped\n properties:\n description: \"zhmc Ansible modules: Example partition 1\"\n ifl_processors: 2\n initial_memory: 1024\n maximum_memory: 1024\n register: part1\n\n# After an HBA has been added (see Ansible module zhmc_hba), and LUN masking\n# has been configured in the SAN, and a bootable image is available at the\n# configured LUN and target WWPN, the partition can be configured for boot\n# from the FCP LUN and can be started:\n- name: Configure boot device and start the partition\n zhmc_partition:\n hmc_host: \"{{ my_hmc_host }}\"\n hmc_auth: \"{{ my_hmc_auth }}\"\n cpc_name: \"{{ my_cpc_name }}\"\n name: \"{{ my_partition_name }}\"\n state: active\n properties:\n boot_device: storage-adapter\n boot_storage_device_hba_name: hba1\n boot_logical_unit_number: 00000000001\n boot_world_wide_port_name: abcdefabcdef\n register: part1\n\n- name: Ensure the partition does not exist\n zhmc_partition:\n hmc_host: \"{{ my_hmc_host }}\"\n hmc_auth: \"{{ my_hmc_auth }}\"\n cpc_name: \"{{ my_cpc_name }}\"\n name: \"{{ my_partition_name }}\"\n state: absent\n\n- name: Define crypto configuration\n zhmc_partition:\n hmc_host: \"{{ my_hmc_host }}\"\n hmc_auth: \"{{ my_hmc_auth }}\"\n cpc_name: \"{{ my_cpc_name }}\"\n name: \"{{ my_partition_name }}\"\n state: active\n properties:\n crypto_configuration:\n crypto_adapter_names:\n - adapter1\n - adapter2\n crypto_domain_configurations:\n - domain_index: 0\n access_mode: control-usage\n - domain_index: 1\n access_mode: control\n register: part1\n\n- name: Gather facts about a partition\n zhmc_partition:\n hmc_host: \"{{ my_hmc_host }}\"\n hmc_auth: \"{{ my_hmc_auth }}\"\n cpc_name: \"{{ my_cpc_name }}\"\n name: \"{{ my_partition_name }}\"\n state: facts\n expand_storage_groups: true\n expand_crypto_adapters: true\n register: part1\n\n\"\"\"\n\nRETURN = \"\"\"\nchanged:\n description: Indicates if any change has been made by the module.\n For C(state=facts), always will be false.\n returned: always\n type: bool\nmsg:\n description: An error message that describes the failure.\n returned: failure\n type: str\npartition:\n description:\n - \"For C(state=absent), an empty dictionary.\"\n - \"For C(state=stopped|active|facts), the resource properties of the\n partition after any changes, including its child resources as described\n below.\"\n returned: success\n type: dict\n contains:\n name:\n description: \"Partition name\"\n type: str\n \"{property}\":\n description: \"Additional properties of the partition, as described in\n the data model of the 'Partition' object in the :term:`HMC API` book.\n The property names have hyphens (-) as described in that book.\"\n hbas:\n description: \"HBAs of the partition. If the CPC does not have the\n storage-management feature enabled (ie. before z15), the list is\n empty.\"\n type: list\n elements: dict\n contains:\n name:\n description: \"HBA name\"\n type: str\n \"{property}\":\n description: \"Additional properties of the HBA, as described in the\n data model of the 'HBA' element object of the 'Partition' object\n in the :term:`HMC API` book.\n The property names have hyphens (-) as described in that book.\"\n nics:\n description: \"NICs of the partition.\"\n type: list\n elements: dict\n contains:\n name:\n description: \"NIC name\"\n type: str\n \"{property}\":\n description: \"Additional properties of the NIC, as described in the\n data model of the 'NIC' element object of the 'Partition' object\n in the :term:`HMC API` book.\n The property names have hyphens (-) as described in that book.\"\n virtual-functions:\n description: \"Virtual functions of the partition.\"\n type: list\n elements: dict\n contains:\n name:\n description: \"Virtual function name\"\n type: str\n \"{property}\":\n description: \"Additional properties of the virtual function, as\n described in the data model of the 'Virtual Function' element\n object of the 'Partition' object in the :term:`HMC API` book.\n The property names have hyphens (-) as described in that book.\"\n sample:\n {\n \"acceptable-status\": [\n \"active\"\n ],\n \"access-basic-counter-set\": true,\n \"access-basic-sampling\": false,\n \"access-coprocessor-group-set\": false,\n \"access-crypto-activity-counter-set\": true,\n \"access-diagnostic-sampling\": false,\n \"access-extended-counter-set\": true,\n \"access-global-performance-data\": true,\n \"access-problem-state-counter-set\": true,\n \"auto-start\": false,\n \"autogenerate-partition-id\": true,\n \"available-features-list\": [\n {\n \"description\": \"The DPM storage management approach in which\n FCP and FICON storage resources are defined in Storage\n Groups, which are attached to Partitions.\",\n \"name\": \"dpm-storage-management\",\n \"state\": true\n }\n ],\n \"boot-configuration-selector\": 0,\n \"boot-device\": \"none\",\n \"boot-ftp-host\": null,\n \"boot-ftp-insfile\": null,\n \"boot-ftp-username\": null,\n \"boot-iso-image-name\": null,\n \"boot-iso-ins-file\": null,\n \"boot-logical-unit-number\": \"\",\n \"boot-network-device\": null,\n \"boot-os-specific-parameters\": \"\",\n \"boot-record-lba\": \"0\",\n \"boot-removable-media\": null,\n \"boot-removable-media-type\": null,\n \"boot-storage-device\": null,\n \"boot-storage-volume\": null,\n \"boot-timeout\": 60,\n \"boot-world-wide-port-name\": \"\",\n \"class\": \"partition\",\n \"cp-absolute-processor-capping\": false,\n \"cp-absolute-processor-capping-value\": 1.0,\n \"cp-processing-weight-capped\": false,\n \"cp-processors\": 0,\n \"crypto-configuration\": {\n \"crypto-adapter-uris\": [\n \"/api/adapters/f1b97ed8-e578-11e8-a87c-00106f239c31\",\n ],\n \"crypto-domain-configurations\": [\n {\n \"access-mode\": \"control-usage\",\n \"domain-index\": 2\n }\n ]\n },\n \"current-cp-processing-weight\": 1,\n \"current-ifl-processing-weight\": 1,\n \"degraded-adapters\": [],\n \"description\": \"Colo dev partition\",\n \"has-unacceptable-status\": false,\n \"hba-uris\": [],\n \"hbas\": [],\n \"ifl-absolute-processor-capping\": false,\n \"ifl-absolute-processor-capping-value\": 1.0,\n \"ifl-processing-weight-capped\": false,\n \"ifl-processors\": 12,\n \"initial-cp-processing-weight\": 100,\n \"initial-ifl-processing-weight\": 120,\n \"initial-memory\": 102400,\n \"ipl-load-parameter\": \"\",\n \"is-locked\": false,\n \"maximum-cp-processing-weight\": 999,\n \"maximum-ifl-processing-weight\": 999,\n \"maximum-memory\": 102400,\n \"minimum-cp-processing-weight\": 1,\n \"minimum-ifl-processing-weight\": 1,\n \"name\": \"CSPF1\",\n \"nic-uris\": [\n \"/api/partitions/32323df4-f433-11ea-b67c-00106f239d19/nics/5956e97a-f433-11ea-b67c-00106f239d19\"\n ],\n \"nics\": [\n {\n \"adapter-id\": \"128\",\n \"adapter-name\": \"OSD_128_MGMT_NET2_30\",\n \"adapter-port\": 0,\n \"class\": \"nic\",\n \"description\": \"HAMGMT\",\n \"device-number\": \"0004\",\n \"element-id\": \"5956e97a-f433-11ea-b67c-00106f239d19\",\n \"element-uri\": \"/api/partitions/32323df4-f433-11ea-b67c-00106f239d19/nics/5956e97a-f433-11ea-b67c-00106f239d19\",\n \"mac-address\": \"02:d2:4d:80:b9:88\",\n \"name\": \"HAMGMT0\",\n \"parent\": \"/api/partitions/32323df4-f433-11ea-b67c-00106f239d19\",\n \"ssc-ip-address\": null,\n \"ssc-ip-address-type\": null,\n \"ssc-management-nic\": false,\n \"ssc-mask-prefix\": null,\n \"type\": \"osd\",\n \"virtual-switch-uri\": \"/api/virtual-switches/db2f0bec-e578-11e8-bd0a-00106f239c31\",\n \"vlan-id\": null,\n \"vlan-type\": null\n }\n ],\n \"object-id\": \"32323df4-f433-11ea-b67c-00106f239d19\",\n \"object-uri\": \"/api/partitions/32323df4-f433-11ea-b67c-00106f239d19\",\n \"os-name\": \"SSC\",\n \"os-type\": \"SSC\",\n \"os-version\": \"3.13.0\",\n \"parent\": \"/api/cpcs/66942455-4a14-3f99-8904-3e7ed5ca28d7\",\n \"partition-id\": \"08\",\n \"permit-aes-key-import-functions\": true,\n \"permit-cross-partition-commands\": false,\n \"permit-des-key-import-functions\": true,\n \"processor-management-enabled\": false,\n \"processor-mode\": \"shared\",\n \"reserve-resources\": false,\n \"reserved-memory\": 0,\n \"short-name\": \"CSPF1\",\n \"ssc-boot-selection\": \"appliance\",\n \"ssc-dns-servers\": [\n \"8.8.8.8\"\n ],\n \"ssc-host-name\": \"cpca-cspf1\",\n \"ssc-ipv4-gateway\": null,\n \"ssc-ipv6-gateway\": null,\n \"ssc-master-userid\": \"hmREST\",\n \"status\": \"active\",\n \"storage-group-uris\": [\n \"/api/storage-groups/4947c6d0-f433-11ea-8f73-00106f239d19\"\n ],\n \"threads-per-processor\": 2,\n \"type\": \"ssc\",\n \"virtual-function-uris\": [],\n \"virtual-functions\": []\n }\n\"\"\"\n\nfrom collections import OrderedDict # noqa: E402\nimport logging # noqa: E402\nimport traceback # noqa: E402\nfrom ansible.module_utils.basic import AnsibleModule # noqa: E402\nfrom operator import itemgetter # noqa: E402\n\nfrom ..module_utils.common import log_init, Error, ParameterError, \\\n StatusError, stop_partition, start_partition, \\\n wait_for_transition_completion, eq_hex, get_hmc_auth, get_session, \\\n to_unicode, process_normal_property, missing_required_lib # noqa: E402\n\ntry:\n import requests.packages.urllib3\n IMP_URLLIB3 = True\nexcept ImportError:\n IMP_URLLIB3 = False\n IMP_URLLIB3_ERR = traceback.format_exc()\n\ntry:\n import zhmcclient\n IMP_ZHMCCLIENT = True\nexcept ImportError:\n IMP_ZHMCCLIENT = False\n IMP_ZHMCCLIENT_ERR = traceback.format_exc()\n\n# Python logger name for this module\nLOGGER_NAME = 'zhmc_partition'\n\nLOGGER = logging.getLogger(LOGGER_NAME)\n\n# Dictionary of properties of partition resources, in this format:\n# name: (allowed, create, update, update_while_active, eq_func, type_cast)\n# where:\n# name: Name of the property according to the data model, with hyphens\n# replaced by underscores (this is how it is or would be specified in\n# the 'properties' module parameter).\n# allowed: Indicates whether it is allowed in the 'properties' module\n# parameter.\n# create: Indicates whether it can be specified for the \"Create Partition\"\n# operation.\n# update: Indicates whether it can be specified for the \"Update Partition\n# Properties\" operation (at all).\n# update_while_active: Indicates whether it can be specified for the \"Update\n# Partition Properties\" operation while the partition is active. None means\n# \"not applicable\" (i.e. update=False).\n# eq_func: Equality test function for two values of the property; None means\n# to use Python equality.\n# type_cast: Type cast function for an input value of the property; None\n# means to use it directly. This can be used for example to convert\n# integers provided as strings by Ansible back into integers (that is a\n# current deficiency of Ansible).\nZHMC_PARTITION_PROPERTIES = {\n\n # create-only properties:\n 'type': (True, True, False, None, None, None), # cannot change type\n\n # update-only properties:\n 'boot_network_device': (\n False, False, True, True, None, None), # via boot_network_nic_name\n 'boot_network_nic_name': (\n True, False, True, True, None, to_unicode), # artificial property\n 'boot_storage_device': (\n False, False, True, True, None, None), # via boot_storage_hba_name\n 'boot_storage_hba_name': (\n True, False, True, True, None, to_unicode), # artificial property\n 'crypto_configuration': (\n True, False, False, None, None,\n None), # Contains artificial properties, type_cast ignored\n 'acceptable_status': (True, False, True, True, None, None),\n 'processor_management_enabled': (True, False, True, True, None, None),\n 'ifl_absolute_processor_capping': (True, False, True, True, None, None),\n 'ifl_absolute_processor_capping_value': (\n True, False, True, True, None, float),\n 'ifl_processing_weight_capped': (True, False, True, True, None, None),\n 'minimum_ifl_processing_weight': (True, False, True, True, None, int),\n 'maximum_ifl_processing_weight': (True, False, True, True, None, int),\n 'initial_ifl_processing_weight': (True, False, True, True, None, int),\n 'cp_absolute_processor_capping': (True, False, True, True, None, None),\n 'cp_absolute_processor_capping_value': (\n True, False, True, True, None, float),\n 'cp_processing_weight_capped': (True, False, True, True, None, None),\n 'minimum_cp_processing_weight': (True, False, True, True, None, int),\n 'maximum_cp_processing_weight': (True, False, True, True, None, int),\n 'initial_cp_processing_weight': (True, False, True, True, None, int),\n 'boot_logical_unit_number': (True, False, True, True, eq_hex, None),\n 'boot_world_wide_port_name': (True, False, True, True, eq_hex, None),\n 'boot_os_specific_parameters': (True, False, True, True, None, to_unicode),\n 'boot_iso_ins_file': (True, False, True, True, None, to_unicode),\n 'ssc_boot_selection': (True, False, True, True, None, None),\n\n # create+update properties:\n 'name': (\n False, True, True, True, None, None), # provided in 'name' module parm\n 'description': (True, True, True, True, None, to_unicode),\n 'short_name': (True, True, True, False, None, None),\n 'partition_id': (True, True, True, False, None, None),\n 'autogenerate_partition_id': (True, True, True, False, None, None),\n 'ifl_processors': (True, True, True, True, None, int),\n 'cp_processors': (True, True, True, True, None, int),\n 'processor_mode': (True, True, True, False, None, None),\n 'initial_memory': (True, True, True, True, None, int),\n 'maximum_memory': (True, True, True, False, None, int),\n 'reserve_resources': (True, True, True, True, None, None),\n 'boot_device': (True, True, True, True, None, None),\n 'boot_timeout': (True, True, True, True, None, int),\n 'boot_ftp_host': (True, True, True, True, None, to_unicode),\n 'boot_ftp_username': (True, True, True, True, None, to_unicode),\n 'boot_ftp_password': (True, True, True, True, None, to_unicode),\n 'boot_ftp_insfile': (True, True, True, True, None, to_unicode),\n 'boot_removable_media': (True, True, True, True, None, to_unicode),\n 'boot_removable_media_type': (True, True, True, True, None, None),\n 'boot_configuration_selector': (True, True, True, True, None, int),\n 'boot_record_lba': (True, True, True, True, None, None),\n 'access_global_performance_data': (True, True, True, True, None, None),\n 'permit_cross_partition_commands': (True, True, True, True, None, None),\n 'access_basic_counter_set': (True, True, True, True, None, None),\n 'access_problem_state_counter_set': (True, True, True, True, None, None),\n 'access_crypto_activity_counter_set': (True, True, True, True, None, None),\n 'access_extended_counter_set': (True, True, True, True, None, None),\n 'access_coprocessor_group_set': (True, True, True, True, None, None),\n 'access_basic_sampling': (True, True, True, True, None, None),\n 'access_diagnostic_sampling': (True, True, True, True, None, None),\n 'permit_des_key_import_functions': (True, True, True, True, None, None),\n 'permit_aes_key_import_functions': (True, True, True, True, None, None),\n 'ssc_host_name': (True, True, True, True, None, to_unicode),\n 'ssc_ipv4_gateway': (True, True, True, True, None, to_unicode),\n 'ssc_dns_servers': (True, True, True, True, None, to_unicode),\n 'ssc_master_userid': (True, True, True, True, None, to_unicode),\n 'ssc_master_pw': (True, True, True, True, None, to_unicode),\n\n # read-only properties:\n 'object_uri': (False, False, False, None, None, None),\n 'object_id': (False, False, False, None, None, None),\n 'parent': (False, False, False, None, None, None),\n 'class': (False, False, False, None, None, None),\n 'status': (False, False, False, None, None, None),\n 'has_unacceptable_status': (False, False, False, None, None, None),\n 'is_locked': (False, False, False, None, None, None),\n 'os_name': (False, False, False, None, None, None),\n 'os_type': (False, False, False, None, None, None),\n 'os_version': (False, False, False, None, None, None),\n 'degraded_adapters': (False, False, False, None, None, None),\n 'current_ifl_processing_weight': (False, False, False, None, None, None),\n 'current_cp_processing_weight': (False, False, False, None, None, None),\n 'reserved_memory': (False, False, False, None, None, None),\n 'auto_start': (False, False, False, None, None, None),\n 'boot_iso_image_name': (False, False, False, None, None, None),\n 'threads_per_processor': (False, False, False, None, None, None),\n 'virtual_function_uris': (False, False, False, None, None, None),\n 'nic_uris': (False, False, False, None, None, None),\n 'hba_uris': (False, False, False, None, None, None),\n}\n\n\ndef process_properties(cpc, partition, params):\n \"\"\"\n Process the properties specified in the 'properties' module parameter,\n and return two dictionaries (create_props, update_props) that contain\n the properties that can be created, and the properties that can be updated,\n respectively. If the resource exists, the input property values are\n compared with the existing resource property values and the returned set\n of properties is the minimal set of properties that need to be changed.\n\n - Underscores in the property names are translated into hyphens.\n - The presence of read-only properties, invalid properties (i.e. not\n defined in the data model for partitions), and properties that are not\n allowed because of restrictions or because they are auto-created from\n an artificial property is surfaced by raising ParameterError.\n - The properties resulting from handling artificial properties are\n added to the returned dictionaries.\n\n Parameters:\n\n cpc (zhmcclient.Cpc): CPC with the partition to be updated, and\n with the adapters to be used for the partition.\n\n partition (zhmcclient.Partition): Partition to be updated with the full\n set of current properties, or `None` if it did not previously exist.\n\n params (dict): Module input parameters.\n\n Returns:\n tuple of (create_props, update_props, stop, crypto_changes), where:\n * create_props: dict of properties for\n zhmcclient.PartitionManager.create()\n * update_props: dict of properties for\n zhmcclient.Partition.update_properties()\n * stop (bool): Indicates whether some update properties require the\n partition to be stopped when doing the update.\n * crypto_changes (tuple): Changes to the crypto configuration if any\n (or `None` if no changes were specified), as a tuple of:\n * remove_adapters: List of Adapter objects to be removed\n * remove_domain_indexes: List of domain indexes to be removed\n * add_adapters: List of Adapter objects to be added\n * add_domain_configs: List of domain configs to be added (dict of\n 'domain-index', 'access-mode')\n * change_domain_configs: List of domain configs for changing the\n access mode of existing domain indexes.\n\n Raises:\n ParameterError: An issue with the module parameters.\n \"\"\"\n create_props = {}\n update_props = {}\n stop = False\n crypto_changes = None\n\n # handle 'name' property\n part_name = to_unicode(params['name'])\n create_props['name'] = part_name\n # We looked up the partition by name, so we will never have to update\n # the partition name\n\n # handle the other properties\n input_props = params.get('properties', {})\n if input_props is None:\n input_props = {}\n for prop_name in input_props:\n\n if prop_name not in ZHMC_PARTITION_PROPERTIES:\n raise ParameterError(\n \"Property {0!r} is not defined in the data model for \"\n \"partitions.\".format(prop_name))\n\n allowed, create, update, update_while_active, eq_func, type_cast = \\\n ZHMC_PARTITION_PROPERTIES[prop_name]\n\n if not allowed:\n raise ParameterError(\n \"Property {0!r} is not allowed in the 'properties' module \"\n \"parameter.\".format(prop_name))\n\n if prop_name == 'boot_storage_hba_name':\n # Process this artificial property\n\n if not partition:\n raise ParameterError(\n \"Artificial property {0!r} can only be specified when the \"\n \"partition previously exists.\".format(prop_name))\n\n if partition.hbas is None:\n raise ParameterError(\n \"Artificial property {0!r} can only be specified when the \"\n \"'dpm-storage-management' feature is disabled.\".\n format(prop_name))\n\n hba_name = input_props[prop_name]\n if type_cast:\n hba_name = type_cast(hba_name)\n\n try:\n hba = partition.hbas.find(name=hba_name)\n except zhmcclient.NotFound:\n raise ParameterError(\n \"Artificial property {0!r} does not name an existing HBA: \"\n \"{1!r}\".format(prop_name, hba_name))\n\n hmc_prop_name = 'boot-storage-device'\n if partition.properties.get(hmc_prop_name) != hba.uri:\n update_props[hmc_prop_name] = hba.uri\n if not update_while_active:\n raise AssertionError()\n\n elif prop_name == 'boot_network_nic_name':\n # Process this artificial property\n\n if not partition:\n raise ParameterError(\n \"Artificial property {0!r} can only be specified when the \"\n \"partition previously exists.\".format(prop_name))\n\n nic_name = input_props[prop_name]\n if type_cast:\n nic_name = type_cast(nic_name)\n\n try:\n nic = partition.nics.find(name=nic_name)\n except zhmcclient.NotFound:\n raise ParameterError(\n \"Artificial property {0!r} does not name an existing NIC: \"\n \"{1!r}\".format(prop_name, nic_name))\n\n hmc_prop_name = 'boot-network-device'\n if partition.properties.get(hmc_prop_name) != nic.uri:\n update_props[hmc_prop_name] = nic.uri\n if not update_while_active:\n raise AssertionError()\n\n elif prop_name == 'crypto_configuration':\n # Process this artificial property\n\n crypto_config = input_props[prop_name]\n\n if not isinstance(crypto_config, dict):\n raise ParameterError(\n \"Artificial property {0!r} is not a dictionary: {1!r}.\".\n format(prop_name, crypto_config))\n\n if partition:\n hmc_prop_name = 'crypto-configuration'\n current_crypto_config = partition.properties.get(hmc_prop_name)\n else:\n current_crypto_config = None\n\n # Determine adapter changes\n try:\n adapter_field_name = 'crypto_adapter_names'\n adapter_names = crypto_config[adapter_field_name]\n except KeyError:\n raise ParameterError(\n \"Artificial property {0!r} does not have required field \"\n \"{1!r}.\".format(prop_name, adapter_field_name))\n adapter_uris = set()\n adapter_dict = {} # adapters by uri\n if adapter_names is None:\n # Default: Use all crypto adapters of the CPC\n adapters = cpc.adapters.findall(type='crypto')\n for adapter in adapters:\n adapter_dict[adapter.uri] = adapter\n adapter_uris.add(adapter.uri)\n else:\n for adapter_name in adapter_names:\n try:\n adapter = cpc.adapters.find(name=adapter_name,\n type='crypto')\n except zhmcclient.NotFound:\n raise ParameterError(\n \"Artificial property {0!r} does not specify the \"\n \"name of an existing crypto adapter in its {1!r} \"\n \"field: {2!r}\".\n format(prop_name, adapter_field_name,\n adapter_name))\n adapter_dict[adapter.uri] = adapter\n adapter_uris.add(adapter.uri)\n if current_crypto_config:\n current_adapter_uris = set(\n current_crypto_config['crypto-adapter-uris'])\n else:\n current_adapter_uris = set()\n if adapter_uris != current_adapter_uris:\n add_adapter_uris = adapter_uris - current_adapter_uris\n # Result: List of adapters to be added:\n add_adapters = [adapter_dict[uri] for uri in add_adapter_uris]\n remove_adapter_uris = current_adapter_uris - adapter_uris\n for uri in remove_adapter_uris:\n adapter = cpc.adapters.find(**{'object-uri': uri})\n # We assume the current crypto config lists only valid URIs\n adapter_dict[adapter.uri] = adapter\n # Result: List of adapters to be removed:\n remove_adapters = \\\n [adapter_dict[uri] for uri in remove_adapter_uris]\n else:\n # Result: List of adapters to be added:\n add_adapters = []\n # Result: List of adapters to be removed:\n remove_adapters = []\n\n # Determine domain config changes.\n try:\n config_field_name = 'crypto_domain_configurations'\n domain_configs = crypto_config[config_field_name]\n except KeyError:\n raise ParameterError(\n \"Artificial property {0!r} does not have required field \"\n \"{1!r}.\".format(prop_name, config_field_name))\n di_field_name = 'domain_index'\n am_field_name = 'access_mode'\n domain_indexes = set()\n for dc in domain_configs:\n try:\n # Convert to integer in case the domain index is provided\n # as a string:\n domain_index = int(dc[di_field_name])\n except KeyError:\n raise ParameterError(\n \"Artificial property {0!r} does not have required \"\n \"sub-field {1!r} in one of its {2!r} fields.\".\n format(prop_name, di_field_name, config_field_name))\n domain_indexes.add(domain_index)\n current_access_mode_dict = {} # dict: acc.mode by dom.index\n if current_crypto_config:\n current_domain_configs = \\\n current_crypto_config['crypto-domain-configurations']\n di_prop_name = 'domain-index'\n am_prop_name = 'access-mode'\n for dc in current_domain_configs:\n # Here the domain index is always an integer because it is\n # returned from the HMC that way, so no type cast needed.\n current_access_mode_dict[dc[di_prop_name]] = \\\n dc[am_prop_name]\n current_domain_indexes = \\\n set(current_access_mode_dict)\n # Result: List of domain indexes to be removed:\n remove_domain_indexes = \\\n list(current_domain_indexes - domain_indexes)\n # Building result: List of domain configs to be added:\n add_domain_configs = []\n # Building result: List of domain configs to be changed:\n change_domain_configs = []\n for dc in domain_configs:\n # Convert to integer in case the domain index is provided\n # as a string:\n domain_index = int(dc[di_field_name])\n try:\n access_mode = dc[am_field_name]\n except KeyError:\n raise ParameterError(\n \"Artificial property {0!r} does not have required \"\n \"sub-field {1!r} in one of its {2!r} fields.\".\n format(prop_name, am_field_name, config_field_name))\n hmc_domain_config = {\n 'domain-index': domain_index,\n 'access-mode': access_mode,\n }\n if domain_index not in current_access_mode_dict:\n # Domain is not included yet\n add_domain_configs.append(hmc_domain_config)\n elif access_mode != current_access_mode_dict[domain_index]:\n # Domain is included but access mode needs to be changed\n change_domain_configs.append(hmc_domain_config)\n\n crypto_changes = (remove_adapters, remove_domain_indexes,\n add_adapters, add_domain_configs,\n change_domain_configs)\n\n else:\n # Process a normal (= non-artificial) property\n if prop_name == 'ssc_ipv4_gateway':\n # Undo conversion from None to empty string in Ansible\n if input_props[prop_name] == '':\n input_props[prop_name] = None\n _create_props, _update_props, _stop = process_normal_property(\n prop_name, ZHMC_PARTITION_PROPERTIES, input_props, partition)\n create_props.update(_create_props)\n update_props.update(_update_props)\n if _stop:\n stop = True\n\n return create_props, update_props, stop, crypto_changes\n\n\ndef change_crypto_config(partition, crypto_changes, check_mode):\n \"\"\"\n Change the crypto configuration of the partition as specified.\n\n Returns whether the crypto configuration has or would have changed.\n \"\"\"\n\n remove_adapters, remove_domain_indexes, \\\n add_adapters, add_domain_configs, \\\n change_domain_configs = crypto_changes\n\n changed = False\n\n # We process additions first, in order to avoid\n # HTTPError 409,111 (At least one 'usage' required).\n if add_adapters or add_domain_configs:\n if not check_mode:\n partition.increase_crypto_config(add_adapters,\n add_domain_configs)\n changed = True\n\n if change_domain_configs:\n # We process changes that set access mode 'control-usage' first,\n # in order to avoid HTTPError 409,111 (At least one 'usage' required).\n for domain_config in sorted(change_domain_configs,\n key=itemgetter('access-mode'),\n reverse=True):\n domain_index = domain_config['domain-index']\n access_mode = domain_config['access-mode']\n if not check_mode:\n partition.change_crypto_domain_config(domain_index,\n access_mode)\n changed = True\n\n if remove_adapters or remove_domain_indexes:\n if not check_mode:\n partition.decrease_crypto_config(remove_adapters,\n remove_domain_indexes)\n changed = True\n\n return changed\n\n\ndef add_artificial_properties(\n partition, expand_storage_groups, expand_crypto_adapters):\n \"\"\"\n Add artificial properties to the partition object.\n\n Upon return, the properties of the partition object have been\n extended by these artificial properties:\n\n * 'hbas': List of Hba objects of the partition.\n\n * 'nics': List of Nic objects of the partition, with their properties\n and these artificial properties:\n\n * 'adapter-name'\n * 'adapter-port'\n * 'adapter-id'\n\n * 'virtual-functions': List of VirtualFunction objects of the partition.\n\n and if expand_storage_groups is True:\n\n * 'storage-groups': List of StorageGroup objects representing the\n storage groups attached to the partition, with their properties\n and these artificial properties:\n\n * 'candidate-adapter-ports': List of Port objects representing the\n candidate adapter ports of the storage group, with their properties\n and these artificial properties:\n\n - 'parent-adapter': Adapter object of the port.\n\n * 'storage-volumes': List of StorageVolume objects of the storage\n group.\n\n * 'virtual-storage-resources': List of VirtualStorageResource objects\n of the storage group.\n\n and if expand_crypto_adapters is True:\n\n * 'crypto-adapters' in 'crypto-configuration': List of Adapter objects\n representing the crypto adapters assigned to the partition.\n \"\"\"\n cpc = partition.manager.cpc\n console = cpc.manager.console\n session = cpc.manager.client.session\n\n # Get the HBA child elements of the partition\n hbas_prop = list()\n if partition.hbas is not None:\n for hba in partition.hbas.list(full_properties=True):\n hbas_prop.append(hba.properties)\n partition.properties['hbas'] = hbas_prop\n\n # Get the NIC child elements of the partition\n nics_prop = list()\n for nic in partition.nics.list(full_properties=True):\n nic_props = OrderedDict()\n nic_props.update(nic.properties)\n # Add artificial properties adapter-name/-port/-id:\n vswitch_uri = nic.prop(\"virtual-switch-uri\", None)\n if vswitch_uri:\n # OSA, Hipersockets\n vswitch = cpc.virtual_switches.find(**{'object-uri': vswitch_uri})\n adapter_uri = vswitch.get_property('backing-adapter-uri')\n adapter_port = vswitch.get_property('port')\n adapter = cpc.adapters.find(**{'object-uri': adapter_uri})\n nic_props['adapter-name'] = adapter.name\n nic_props['adapter-port'] = adapter_port\n nic_props['adapter-id'] = adapter.get_property('adapter-id')\n else:\n # RoCE, CNA\n port_uri = nic.prop(\"network-adapter-port-uri\", None)\n port_props = session.get(port_uri)\n adapter_uri = port_props['parent']\n adapter = cpc.adapters.find(**{'object-uri': adapter_uri})\n nic_props['adapter-name'] = adapter.name\n nic_props['adapter-port'] = port_props['index']\n nic_props['adapter-id'] = adapter.get_property('adapter-id')\n nics_prop.append(nic_props)\n partition.properties['nics'] = nics_prop\n\n # Get the VF child elements of the partition\n vf_prop = list()\n for vf in partition.virtual_functions.list(full_properties=True):\n vf_prop.append(vf.properties)\n partition.properties['virtual-functions'] = vf_prop\n\n if expand_storage_groups:\n sg_prop = list()\n for sg_uri in partition.properties['storage-group-uris']:\n storage_group = console.storage_groups.resource_object(sg_uri)\n storage_group.pull_full_properties()\n sg_prop.append(storage_group.properties)\n\n # Candidate adapter ports and their adapters (full set of props)\n caps_prop = list()\n for cap in storage_group.list_candidate_adapter_ports(\n full_properties=True):\n adapter = cap.manager.adapter\n adapter.pull_full_properties()\n cap.properties['parent-adapter'] = adapter.properties\n caps_prop.append(cap.properties)\n storage_group.properties['candidate-adapter-ports'] = caps_prop\n\n # Storage volumes (full set of properties).\n # Note: We create the storage volumes from the\n # 'storage-volume-uris' property, because the 'List Storage\n # Volumes of a Storage Group' operation returns an empty list for\n # auto-discovered volumes.\n svs_prop = list()\n sv_uris = storage_group.get_property('storage-volume-uris')\n for sv_uri in sv_uris:\n sv = storage_group.storage_volumes.resource_object(sv_uri)\n sv.pull_full_properties()\n svs_prop.append(sv.properties)\n storage_group.properties['storage-volumes'] = svs_prop\n\n # Virtual storage resources (full set of properties).\n vsrs_prop = list()\n vsr_uris = storage_group.get_property(\n 'virtual-storage-resource-uris')\n for vsr_uri in vsr_uris:\n vsr = storage_group.virtual_storage_resources.resource_object(\n vsr_uri)\n vsr.pull_full_properties()\n vsrs_prop.append(vsr.properties)\n storage_group.properties['virtual-storage-resources'] = vsrs_prop\n\n partition.properties['storage-groups'] = sg_prop\n\n if expand_crypto_adapters:\n\n cc = partition.properties['crypto-configuration']\n if cc:\n ca_prop = list()\n for ca_uri in cc['crypto-adapter-uris']:\n ca = cpc.adapters.resource_object(ca_uri)\n ca.pull_full_properties()\n ca_prop.append(ca.properties)\n cc['crypto-adapters'] = ca_prop\n\n\ndef ensure_active(params, check_mode):\n \"\"\"\n Ensure that the partition exists, is active or degraded, and has the\n specified properties.\n\n Raises:\n ParameterError: An issue with the module parameters.\n StatusError: An issue with the partition status.\n zhmcclient.Error: Any zhmcclient exception can happen.\n \"\"\"\n\n host = params['hmc_host']\n userid, password = get_hmc_auth(params['hmc_auth'])\n cpc_name = params['cpc_name']\n partition_name = params['name']\n expand_storage_groups = params['expand_storage_groups']\n expand_crypto_adapters = params['expand_crypto_adapters']\n _faked_session = params.get('_faked_session', None)\n\n changed = False\n result = {}\n\n try:\n session = get_session(_faked_session, host, userid, password)\n client = zhmcclient.Client(session)\n cpc = client.cpcs.find(name=cpc_name)\n # The default exception handling is sufficient for the above.\n\n try:\n partition = cpc.partitions.find(name=partition_name)\n partition.pull_full_properties()\n except zhmcclient.NotFound:\n partition = None\n\n if not partition:\n # It does not exist. Create it and update it if there are\n # update-only properties.\n if not check_mode:\n create_props, update_props, stop, crypto_changes = \\\n process_properties(cpc, partition, params)\n partition = cpc.partitions.create(create_props)\n update2_props = {}\n for name in update_props:\n if name not in create_props:\n update2_props[name] = update_props[name]\n if update2_props:\n partition.update_properties(update2_props)\n # We refresh the properties after the update, in case an\n # input property value gets changed (for example, the\n # partition does that with memory properties).\n partition.pull_full_properties()\n if crypto_changes:\n change_crypto_config(partition, crypto_changes, check_mode)\n else:\n # TODO: Show props in module result also in check mode.\n pass\n changed = True\n else:\n # It exists. Stop if needed due to property update requirements,\n # or wait for an updateable partition status, and update its\n # properties.\n create_props, update_props, stop, crypto_changes = \\\n process_properties(cpc, partition, params)\n if update_props:\n if not check_mode:\n if stop:\n stop_partition(partition, check_mode)\n else:\n wait_for_transition_completion(partition)\n partition.update_properties(update_props)\n # We refresh the properties after the update, in case an\n # input property value gets changed (for example, the\n # partition does that with memory properties).\n partition.pull_full_properties()\n else:\n # TODO: Show updated props in mod.result also in chk.mode\n pass\n changed = True\n if crypto_changes:\n changed |= change_crypto_config(partition, crypto_changes,\n check_mode)\n\n if partition:\n changed |= start_partition(partition, check_mode)\n\n if partition and not check_mode:\n partition.pull_full_properties()\n status = partition.get_property('status')\n if status not in ('active', 'degraded'):\n raise StatusError(\n \"Could not get partition {0!r} into an active state, \"\n \"status is: {1!r}\".format(partition.name, status))\n\n if partition:\n add_artificial_properties(\n partition, expand_storage_groups, expand_crypto_adapters)\n result = partition.properties\n\n return changed, result\n\n finally:\n session.logoff()\n\n\ndef ensure_stopped(params, check_mode):\n \"\"\"\n Ensure that the partition exists, is stopped, and has the specified\n properties.\n\n Raises:\n ParameterError: An issue with the module parameters.\n StatusError: An issue with the partition status.\n zhmcclient.Error: Any zhmcclient exception can happen.\n \"\"\"\n\n host = params['hmc_host']\n userid, password = get_hmc_auth(params['hmc_auth'])\n cpc_name = params['cpc_name']\n partition_name = params['name']\n expand_storage_groups = params['expand_storage_groups']\n expand_crypto_adapters = params['expand_crypto_adapters']\n _faked_session = params.get('_faked_session', None)\n\n changed = False\n result = {}\n\n try:\n session = get_session(_faked_session, host, userid, password)\n client = zhmcclient.Client(session)\n cpc = client.cpcs.find(name=cpc_name)\n # The default exception handling is sufficient for the above.\n\n try:\n partition = cpc.partitions.find(name=partition_name)\n partition.pull_full_properties()\n except zhmcclient.NotFound:\n partition = None\n\n if not partition:\n # It does not exist. Create it and update it if there are\n # update-only properties.\n if not check_mode:\n create_props, update_props, stop, crypto_changes = \\\n process_properties(cpc, partition, params)\n partition = cpc.partitions.create(create_props)\n update2_props = {}\n for name in update_props:\n if name not in create_props:\n update2_props[name] = update_props[name]\n if update2_props:\n partition.update_properties(update2_props)\n if crypto_changes:\n change_crypto_config(partition, crypto_changes, check_mode)\n changed = True\n else:\n # It exists. Stop it and update its properties.\n create_props, update_props, stop, crypto_changes = \\\n process_properties(cpc, partition, params)\n changed |= stop_partition(partition, check_mode)\n if update_props:\n if not check_mode:\n partition.update_properties(update_props)\n changed = True\n if crypto_changes:\n changed |= change_crypto_config(partition, crypto_changes,\n check_mode)\n\n if partition and not check_mode:\n partition.pull_full_properties()\n status = partition.get_property('status')\n if status not in ('stopped'):\n raise StatusError(\n \"Could not get partition {0!r} into a stopped state, \"\n \"status is: {1!r}\".format(partition.name, status))\n\n if partition:\n add_artificial_properties(\n partition, expand_storage_groups, expand_crypto_adapters)\n result = partition.properties\n\n return changed, result\n\n finally:\n session.logoff()\n\n\ndef ensure_absent(params, check_mode):\n \"\"\"\n Ensure that the partition does not exist.\n\n Raises:\n ParameterError: An issue with the module parameters.\n StatusError: An issue with the partition status.\n zhmcclient.Error: Any zhmcclient exception can happen.\n \"\"\"\n\n host = params['hmc_host']\n userid, password = get_hmc_auth(params['hmc_auth'])\n cpc_name = params['cpc_name']\n partition_name = params['name']\n _faked_session = params.get('_faked_session', None)\n\n changed = False\n result = {}\n\n try:\n session = get_session(_faked_session, host, userid, password)\n client = zhmcclient.Client(session)\n cpc = client.cpcs.find(name=cpc_name)\n # The default exception handling is sufficient for the above.\n\n try:\n partition = cpc.partitions.find(name=partition_name)\n except zhmcclient.NotFound:\n return changed, result\n\n if not check_mode:\n stop_partition(partition, check_mode)\n partition.delete()\n changed = True\n\n return changed, result\n\n finally:\n session.logoff()\n\n\ndef facts(params, check_mode):\n \"\"\"\n Return partition facts.\n\n Raises:\n ParameterError: An issue with the module parameters.\n zhmcclient.Error: Any zhmcclient exception can happen.\n \"\"\"\n\n host = params['hmc_host']\n userid, password = get_hmc_auth(params['hmc_auth'])\n cpc_name = params['cpc_name']\n partition_name = params['name']\n expand_storage_groups = params['expand_storage_groups']\n expand_crypto_adapters = params['expand_crypto_adapters']\n _faked_session = params.get('_faked_session', None)\n\n changed = False\n result = {}\n\n try:\n # The default exception handling is sufficient for this code\n\n session = get_session(_faked_session, host, userid, password)\n client = zhmcclient.Client(session)\n cpc = client.cpcs.find(name=cpc_name)\n\n partition = cpc.partitions.find(name=partition_name)\n partition.pull_full_properties()\n\n add_artificial_properties(\n partition, expand_storage_groups, expand_crypto_adapters)\n result = partition.properties\n return changed, result\n\n finally:\n session.logoff()\n\n\ndef perform_task(params, check_mode):\n \"\"\"\n Perform the task for this module, dependent on the 'state' module\n parameter.\n\n If check_mode is True, check whether changes would occur, but don't\n actually perform any changes.\n\n Raises:\n ParameterError: An issue with the module parameters.\n StatusError: An issue with the partition status.\n zhmcclient.Error: Any zhmcclient exception can happen.\n \"\"\"\n actions = {\n \"absent\": ensure_absent,\n \"active\": ensure_active,\n \"stopped\": ensure_stopped,\n \"facts\": facts,\n }\n return actions[params['state']](params, check_mode)\n\n\ndef main():\n\n # The following definition of module input parameters must match the\n # description of the options in the DOCUMENTATION string.\n argument_spec = dict(\n hmc_host=dict(required=True, type='str'),\n hmc_auth=dict(required=True, type='dict', no_log=True),\n cpc_name=dict(required=True, type='str'),\n name=dict(required=True, type='str'),\n state=dict(required=True, type='str',\n choices=['absent', 'stopped', 'active', 'facts']),\n properties=dict(required=False, type='dict', default={}),\n expand_storage_groups=dict(required=False, type='bool', default=False),\n expand_crypto_adapters=dict(required=False, type='bool',\n default=False),\n log_file=dict(required=False, type='str', default=None),\n _faked_session=dict(required=False, type='raw'),\n )\n\n module = AnsibleModule(\n argument_spec=argument_spec,\n supports_check_mode=True)\n\n if not IMP_URLLIB3:\n module.fail_json(msg=missing_required_lib(\"requests\"),\n exception=IMP_URLLIB3_ERR)\n\n requests.packages.urllib3.disable_warnings()\n\n if not IMP_ZHMCCLIENT:\n module.fail_json(msg=missing_required_lib(\"zhmcclient\"),\n exception=IMP_ZHMCCLIENT_ERR)\n\n log_file = module.params['log_file']\n log_init(LOGGER_NAME, log_file)\n\n _params = dict(module.params)\n del _params['hmc_auth']\n LOGGER.debug(\"Module entry: params: %r\", _params)\n\n try:\n\n changed, result = perform_task(module.params, module.check_mode)\n\n except (Error, zhmcclient.Error) as exc:\n # These exceptions are considered errors in the environment or in user\n # input. They have a proper message that stands on its own, so we\n # simply pass that message on and will not need a traceback.\n msg = \"{0}: {1}\".format(exc.__class__.__name__, exc)\n LOGGER.debug(\n \"Module exit (failure): msg: %s\", msg)\n module.fail_json(msg=msg)\n # Other exceptions are considered module errors and are handled by Ansible\n # by showing the traceback.\n\n LOGGER.debug(\n \"Module exit (success): changed: %r, cpc: %r\", changed, result)\n module.exit_json(changed=changed, partition=result)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"plugins/modules/zhmc_partition.py","file_name":"zhmc_partition.py","file_ext":"py","file_size_in_byte":58741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"493347461","text":"\n# -*- coding: utf-8 -*-\n\nimport logging\nimport Artus.Utility.logger as logger\nlog = logging.getLogger(__name__)\n\nfrom Artus.HarryPlotter.utility.binnings import BinningsDict\n\n\"\"\"\n\tThis module contains a dictionary for binnings.\n\"\"\"\nclass BinningsDictZJet(BinningsDict):\n\n\tdef __init__(self):\n\t\tsuper(BinningsDictZJet, self).__init__()\n\n\t\tabsetabins = \"0 0.783 1.305 1.93 2.5 2.964 3.139 5.191\"\n\t\tself.binnings_dict.update({\n\t\t\t'zpt': \"30 40 50 60 85 105 130 175 230 300 400 500 700 1000 1500\",\n\t\t'npv':\"-0.5 6.5 8.5 10.5 12.5 15.5 21.5 30.5 \",\n\t\t\t'eta':\" \".join([str(y) for y in [-i for i in [float(x) for x in absetabins.split(\" \")][7:0:-1]]+[float(x) for x in absetabins.split(\" \")]]),\n\t\t\t'abseta': absetabins,\n\t\t\t'jet1abseta': absetabins,\n\n\t\t\t'phi': '20,-3.14159,3.14159',\n\n\t\t\t'jet2eta': '50,-5,5',\n\t\t\t'jet2pt': '25,0,50',\n\n\t\t\t'deltaphijet1jet2': '25,-0,3.14159',\n\t\t\t'deltaetajet1jet2': '20,0,5',\n\t\t\t'deltarjet1jet2': '40,0,7'\n\t\t})\n","sub_path":"Plotting/python/utility/binningsZJet.py","file_name":"binningsZJet.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"63769232","text":"'''\nFunctions related to the output of the data to screen and files\n'''\n\nimport os\nimport time\nimport json\n\n\ndef save(events, filename, output_folder):\n '''saves events out as a single json object per line'''\n if not os.path.isdir(output_folder):\n return False\n\n filename = os.path.split(filename)[1]\n path = os.path.join(output_folder, filename)\n path += \".evtparser.json\"\n if os.path.isfile(path):\n path += str(time.time())\n handle = open(path, 'w')\n if not handle:\n return False\n\n for each in events:\n # print(json.dumps(each))\n handle.write(json.dumps(each))\n handle.write('\\n')\n\n handle.close()\n return True\n","sub_path":"module/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"160110087","text":"# Import requests, shutil python module.\r\n#copy the image-Sentiment-polarity-DFE.csv to current directory -same as the python file.\r\n#\r\nimport requests\r\nimport shutil\r\nimport os\r\nimport pathlib\r\nimport pandas as pd\r\nimport numpy as np\r\nimport glob\r\nimport datetime\r\n\r\nprint(datetime.datetime.now())\r\ndefault_dir = os.getcwd()\r\n#clean up default directory\r\nfilelist = glob.glob(default_dir + \"\\\\*.jpg\")\r\nfor file in filelist:\r\n os.remove(file)\r\n\r\n#Get the current directory and set the target directory for download images\r\ncurr_dir=pathlib.Path(__file__).resolve().parent\r\ntgt_dir = str(curr_dir) + \"\\\\\" + 'dwnld'\r\nif not os.path.exists(tgt_dir):\r\n os.makedirs(tgt_dir)\r\n#print(tgt_dir)\r\n\r\n#setting the log file to capture the steps of downloading images\r\nfile1 = open(tgt_dir + \"\\\\download.log\",\"w\")\r\nfile1.write(str(datetime.datetime.now()) + \"\\n\")\r\n\r\n#read the csv file of the metadata of the download images\r\nimage_file_raw = pd.read_csv(str(curr_dir) + \"\\\\\" + \"image-Sentiment-polarity-DFE.csv\")\r\nimage_file = image_file_raw.iloc[:,0:9]\r\n\r\n#image_file = image_file_1[(image_file_1['_unit_id'] >= 694551359) & (image_file_1['_unit_id'] <= 694551370)]\r\n#image_file = image_file_1[(image_file_1['_unit_id'] >= 694551359) & (image_file_1['_unit_id'] <= 694551370)]\r\nfile_range = image_file.count\r\n#add two new columns for flagging images exist and filename\r\nimage_file['image_exists']=\"NA\"\r\nimage_file['file_name']=\"NA\"\r\n\r\nfile1.write(tgt_dir + \"--\\n\")\r\n\r\n#For loop to download each image, flag when the return code is not 200\r\nfor i in range(len(image_file)):\r\n#for i in range(10):\r\n #print(i)\r\n file1.write(str(i))\r\n image_url = image_file.iloc[i, 7]\r\n # image_url = \"https://farm1.static.flickr.com/170/413562322_8a3fc74ce2.jpg\"\r\n\r\n resp = requests.get(image_url)\r\n #print(resp.status_code)\r\n local_file=\"\"\r\n if resp.status_code==200:\r\n local_file = open(image_url[image_url.rfind(\"/\")+1:], 'wb')\r\n\r\n #file_loc=\"c:/Swadesh/MMAI/Research_paper/\" + local_file.name\r\n file_loc = tgt_dir + \"\\\\\" + local_file.name\r\n #print(file_loc + \"--\")\r\n # Set decode_content value to True, otherwise the downloaded image file's size will be zero.\r\n file1.write(file_loc + \"--\")\r\n resp.raw.decode_content = True\r\n # Copy the response stream raw data to local image file.\r\n #shutil.copyfileobj(resp.raw, local_file)\r\n with open(file_loc, 'wb') as f:\r\n f.write(resp.content)\r\n # Remove the image url response object.\r\n #add new column\r\n image_file.iloc[i, 9]='YES'\r\n image_file.iloc[i, 10]=local_file.name\r\n file1.write(\"in the if block-\")\r\n file1.write(str(resp.status_code) + \"\\n\")\r\n #image_file['image_exists']='YES'\r\n #print(\"in the if block\")\r\n #print(resp.status_code)\r\n local_file.close()\r\n else:\r\n # print(\"in the else block\")\r\n # print(resp.status_code)\r\n file1.write(\"in the if block\")\r\n file1.write(str(resp.status_code) + \"\\n\")\r\n image_file.iloc[i, 9]='NO'\r\n #image_file.iloc[i, 10]=local_file.name\r\n#removing the temporary files\r\nprint(default_dir)\r\nfilelist=glob.glob(default_dir + \"\\\\*.jpg\")\r\nfor file in filelist:\r\n os.remove(file)\r\n#save the updated metadata file.\r\nimage_file.to_csv(tgt_dir + \"\\\\\" + 'out_image-Sentiment-polarity.csv')\r\nfile1.write(str(datetime.datetime.now()) + \"\\n\")\r\nprint(datetime.datetime.now())","sub_path":"dwnld_images_frm_web.py","file_name":"dwnld_images_frm_web.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"183772335","text":"#===============================================================================\n# File : rainbow.py\n# Author : Olivier Teboul, olivier.teboul@ecp.fr\n# Date : 31 july 2008, 14:02\n# Class : Rainbow\n#===============================================================================\n\nimport random\n\nclass Rainbow:\n \"\"\" This class provide a tool to convert a number between 0 and 1\n to a color from the rainbow. The Rainbow is defined as a path\n on the edges of the RGB cube.\n \"\"\"\n \n def __init__(self,x=None):\n if x==None :\n self.get_random()\n else:\n self.x = x\n self.get(self.x)\n\n def get(self,x):\n if 0<= x < 0.25:\n self.r = 255\n self.g = int(4*255*x)\n self.b = 0\n\n elif 0.25<= x < 0.50:\n self.r = int(255*(-4*x+2))\n self.g = 255\n self.b = 0\n\n elif 0.50<= x < 0.75:\n self.r = 0\n self.g = 255\n self.b = int(255*(4*x-2))\n\n else :\n self.r = 0\n self.g = int(255*(-4*x+4))\n self.b = 255\n \n self.color = (self.r,self.g,self.b)\n return self.color\n\n def get_random(self):\n self.x = random.random()\n return self.get(self.x)\n \n def get_hexa_color(self,x):\n (r,g,b) = self.get(x)\n return '#%02x%02x%02x' %(r,g,b)\n \n\n#--------------------------------------------------------------------------\nif __name__ == '__main__':\n rainbow = Rainbow()\n \n","sub_path":"rainbow.py","file_name":"rainbow.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"512248349","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys \n\ndef test_eng(text):\n return len(text) == len(text.encode('utf-8'))\n\ndef zh_segmentation(src): \n ''' segmentation for Chinese string\n src: should be an unicode string\n return: character list \n '''\n src_list = src.strip().split() \n seg_list = [] \n merge = ''; state = 'ZH' \n for section in src_list:\n for ch in section: \n #print_ch(\"-: \" + ch)\n #print_ch(\"+: \" + merge)\n if ch.isdigit():\n #print_ch(\"digit now\")\n if state == 'ZH': \n merge = ch \n elif state == 'ENG': \n seg_list.append(merge)\n merge = ch \n else: \n ##the former is number too \n merge += ch \n state = 'NUM' \n elif test_eng(ch): \n #print_ch(\"alphabet now\")\n if state == 'ZH': \n merge = ch \n elif state == 'NUM': \n seg_list.append(merge)\n merge = ch \n else: \n ##the former is alphabet too \n merge += ch \n state = 'ENG' \n else: \n #print_ch(\"chinese now\")\n if merge != '': seg_list.append(merge)\n merge = ''\n seg_list.append(ch) \n state = 'ZH' \n if merge != '': seg_list.append(merge)\n state = 'ZH'; merge = '' \n\n return seg_list \n\ndef print_ch(text):\n if type(text) == list:\n text = \"|\".join(text)\n text += '\\n'\n sys.stdout.buffer.write(text.encode('utf-8')) \n\n######################################################## \n\nif __name__ == \"__main__\": \n test_str = [u'asb123', \\\n u'45apple', \\\n u'我是中国人,1995 china,你是?',\\\n u'bmw中国从1995年开始深耕中国market',\\\n u'Remote Software Upgrade后', \\\n u'车辆车辆的Remote Software Upgrade后,电子版用户手册会收到最新信息:',\\\n u'有关用户手册和BMW的一般信息(例如技术信息),请访问:www.bmwusa.com。',\\\n u'CD DVD 换碟CD机 通123过手套箱 CD DVD',\\\n u'123 456 换碟CD机 通123过手套箱 123 456'\n ] \n for tst in test_str:\n print_ch(\"intput: \" + tst)\n print_ch('|'.join(zh_segmentation(tst))) \n print(\"############################\")\n","sub_path":"AutoQA-ding_merged/data/data_collection/tools/zh_segmentation.py","file_name":"zh_segmentation.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"348052232","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nProblem 10 : Python code for solving initial value problem using fourth order Runge-Kutta method\nCreated on Wed Apr 8 15:59:22 2020\n\n@author: krishnendu\n\"\"\"\n\nimport numpy as np\nfrom scipy.optimize import *\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import *\ndef fun(r,x): #defining functions that returns derivatives\n p=np.zeros(3)\n p[0]=r[0]+2*r[1]-2*r[2]+np.exp(-x)\n p[1]=r[1]+r[2]-2*np.exp(-x)\n p[2]=r[0]+2*r[1]+np.exp(-x)\n return p\na=0 #starting value\nb=1 #end value \nN=100 #number of mesh points\nh=(b-a)/(N-1) #step size\nx=np.linspace(a,b,N) #creating mesh points\n\n\nw2=np.zeros(3*N)\nw2=w2.reshape(3,N) \nw2[0,0] =3 #putting the initial condition \nw2[1,0]=-1 #putting the initial condition \nw2[2,0]=1 #putting the initial condition \n\nfor i in range(N-1): #iteration for Runge-Kutta method\n k1=h*fun(w2[:,i],x[i])\n k2=h*fun(w2[:,i]+k1/2,x[i]+h/2)\n k3=h*fun(w2[:,i]+k2/2,x[i]+h/2)\n k4=h*fun(w2[:,i]+k3,x[i]+h)\n w2[:,i+1]=w2[:,i]+1/6*(k1+2*k2+2*k3+k4)\n \nplt.plot(x,w2[0,:],label=r\"$u_1$\")\nplt.plot(x,w2[1,:],label=r\"$u_2$\")\nplt.plot(x,w2[2,:],label=r\"$u_3$\")\nplt.legend()\nplt.xlabel(\"t\",size=18)\nplt.title(\"Problem 11\",size=18)\nplt.grid()\nplt.show()","sub_path":"problem_11_assign_2.py","file_name":"problem_11_assign_2.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"320245014","text":"from sklearn.datasets import make_regression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import f_regression \nfrom sklearn.feature_selection import mutual_info_regression\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nX, y = make_regression(n_samples=1000, n_features=100, n_informative=10, noise=0.1, random_state=42)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1)\n\n# feature selection\ndef select_features(X_train, y_train, X_test, strategy=mutual_info_regression):\n \"\"\"\n strategy: f_regression or mutual_info_regression\n \"\"\"\n # configure to select all features\n fs = SelectKBest(score_func=f_regression, k='all')\n # learn relationship from training data\n fs.fit(X_train, y_train)\n # transform train input data\n X_train_fs = fs.transform(X_train)\n # transform test input data\n X_test_fs = fs.transform(X_test)\n\n # what are scores for the features\n fs_score = {}\n for i in range(len(fs.scores_)):\n fs_score.setdefault(i, fs.scores_[i])\n #print('Feature %d: %f' % (i, fs.scores_[i]))\n # plot the scores\n fs_score=pd.Series(fs_score)\n scores = fs_score.sort_values(ascending=True)\n width = np.arange(len(scores))\n ticks = list(scores.index)\n plt.figure(dpi=100, figsize=(40, 12))\n plt.barh(width, scores)\n plt.yticks(width, ticks)\n plt.title(f\"{strategy} Scores\")\n plt.style.use(\"seaborn-whitegrid\")\n \nif __name__ == \"__main__\": \n select_features(X_train, y_train, X_test, strategy=f_regression)","sub_path":"Variable Selection/regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"45260215","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/10/9 下午8:25\n# @Author : Hou Rong\n# @Site : \n# @File : load_final_data.py\n# @Software: PyCharm\nimport os\nimport pymysql\nimport time\nimport pymysql.err\nfrom warnings import filterwarnings\nfrom service_platform_conn_pool import base_data_final_pool\nfrom my_logger import get_logger\n\n# ignore pymysql warnings\nfilterwarnings('ignore', category=pymysql.err.Warning)\n\nlogger = get_logger(\"load_data\")\n\nfinal_database = 'BaseDataFinal'\n\nfinal_table = {\n \"hotel\": \"hotel_detail.sql\",\n \"attr\": \"daodao_attr_detail.sql\",\n \"rest\": \"daodao_rest_detail.sql\",\n \"total\": \"qyer_detail.sql\"\n}\n\ntime_key = {\n \"hotel_detail\": \"update_time\",\n \"attr_detail\": \"utime\",\n \"rest_detail\": \"utime\",\n \"total_detail\": \"insert_time\",\n \"hotel_images\": \"update_date\",\n \"poi_images\": \"date\",\n}\n\nall_seek_dict = None\n\n\ndef init_all_seek_dict():\n local_conn = base_data_final_pool.connection()\n local_cursor = local_conn.cursor()\n local_cursor.execute('''SELECT *\nFROM data_insert_seek;''')\n global all_seek_dict\n all_seek_dict = {k: v for k, v in local_cursor.fetchall()}\n local_cursor.close()\n local_conn.close()\n\n\ndef get_seek(table_name):\n global all_seek_dict\n if all_seek_dict is None:\n init_all_seek_dict()\n return all_seek_dict.get(table_name, '1970-1-1')\n\n\ndef update_seek_table(table_name, update_time):\n local_conn = base_data_final_pool.connection()\n local_cursor = local_conn.cursor()\n local_cursor.execute('''REPLACE INTO data_insert_seek VALUES (%s, %s);''', (table_name, update_time))\n logger.debug(\"[update seek table][table_name: {}][update_time: {}]\".format(table_name, update_time))\n global all_seek_dict\n all_seek_dict[table_name] = update_time\n local_conn.commit()\n local_cursor.close()\n local_conn.close()\n\n\ndef create_table():\n final_conn = base_data_final_pool.connection()\n final_cursor = final_conn.cursor()\n for k, v in final_table.items():\n real_path = os.path.split(os.path.realpath(__file__))[0]\n sql_path = os.path.join(real_path, 'sql', v)\n final_sql = open(sql_path).read()\n table_name = \"{}_final\".format(k)\n final_cursor.execute(final_sql % (table_name,))\n logger.debug('[create table][name: {}]'.format(table_name))\n final_cursor.close()\n final_conn.close()\n\n\ndef load_data(limit=400):\n local_conn = base_data_final_pool.connection()\n local_cursor = local_conn.cursor()\n local_cursor.execute('''SELECT TABLE_NAME\n FROM information_schema.TABLES\n WHERE TABLE_SCHEMA = '{}';'''.format(final_database))\n\n # 强制要求按照 tag 的先后顺序排列\n table_list = list(\n sorted(\n filter(lambda x: len(x.split('_')) in (3, 4),\n map(lambda x: x[0],\n local_cursor.fetchall()\n )\n ),\n key=lambda x: x.split('_')[-1]\n )\n )\n local_cursor.close()\n\n for each_table in table_list:\n if 'total' not in each_table:\n continue\n each_table_key_list = each_table.split('_')\n if len(each_table_key_list) == 3:\n if each_table_key_list[0] not in ('attr', 'rest', 'total', 'hotel'):\n logger.debug('[skip table][name: {}]'.format(each_table))\n continue\n if each_table_key_list[-1] < '20170929a':\n logger.debug('[skip table][name: {}]'.format(each_table))\n continue\n\n # 通过表明成获取类型以及 tag\n try:\n _type, _, _tag = each_table.split('_')\n except Exception:\n logger.error('[Unknown View Final: {}]'.format(each_table))\n continue\n\n # 生成如数据表名\n to_table_name = \"{}_final\".format(_type)\n _type = \"{}_detail\".format(_type)\n elif len(each_table_key_list) == 4:\n if each_table_key_list[1] != 'images':\n logger.debug('[skip table][name: {}]'.format(each_table))\n continue\n try:\n _type, _, _, _tag = each_table.split('_')\n except Exception:\n logger.error('[Unknown View Final: {}]'.format(each_table))\n continue\n # 生成如数据表名\n if _type == 'hotel':\n to_table_name = \"hotel_images\"\n elif _type == 'poi':\n to_table_name = \"poi_images\"\n else:\n raise TypeError('Unknown Type: {}'.format(_type))\n\n _type = \"{}_images\".format(_type)\n else:\n continue\n\n u_time = get_seek(table_name=each_table)\n start = time.time()\n\n # 开始进行数据合并\n local_cursor = local_conn.cursor()\n update_time_sql = '''SELECT {0}\n FROM {1}\n WHERE {0} >= '{2}'\n ORDER BY {0}\n LIMIT {3};'''.format(time_key[_type], each_table, u_time, limit)\n line_count = local_cursor.execute(update_time_sql)\n\n if line_count == 0:\n # 如果已无数据,则不需要执行后面的处理\n continue\n # get final update time for inserting db next time\n final_update_time = max(map(lambda x: x[0], local_cursor.fetchall()))\n local_cursor.close()\n\n # replace into final data\n local_cursor = local_conn.cursor()\n query_sql_list = []\n if to_table_name == 'hotel_images':\n query_sql = '''REPLACE INTO {0} (source, source_id, pic_url, pic_md5, part, hotel_id, status, update_date, size, flag, file_md5)\n SELECT\n source,\n source_id,\n pic_url,\n pic_md5,\n part,\n hotel_id,\n status,\n update_date,\n size,\n flag,\n file_md5\n FROM\n {1}\n WHERE update_date >= '{2}'\n ORDER BY update_date\n LIMIT {3};'''.format(to_table_name, each_table, u_time, limit)\n query_sql_list.append(query_sql)\n elif to_table_name == 'poi_images':\n query_sql = '''REPLACE INTO {0}\n (file_name, source, sid, url, pic_size, bucket_name, url_md5, pic_md5, `use`, part, date)\n SELECT\n file_name,\n source,\n sid,\n url,\n pic_size,\n bucket_name,\n url_md5,\n pic_md5,\n `use`,\n part,\n date\n FROM\n {1}\n WHERE date >= '{2}'\n ORDER BY date\n LIMIT {3};'''.format(to_table_name, each_table, u_time, limit)\n query_sql_list.append(query_sql)\n elif u_time != '':\n query_sql = '''REPLACE INTO {1} SELECT *\n FROM {2}\n WHERE {0} >= '{3}'\n ORDER BY {0}\n LIMIT {4};'''.format(time_key[_type], to_table_name, each_table, u_time, limit)\n query_sql_list.append(query_sql)\n if to_table_name == 'attr_final':\n query_sql = '''REPLACE INTO poi_merge.attr SELECT *\n FROM {2}\n WHERE {0} >= '{3}'\n ORDER BY {0}\n LIMIT {4};'''.format(time_key[_type], to_table_name, each_table, u_time, limit)\n query_sql_list.append(query_sql)\n elif to_table_name == 'total_final':\n query_sql = '''REPLACE INTO poi_merge.attr\n SELECT\n id,\n source,\n name,\n name_en,\n alias,\n map_info,\n city_id,\n source_city_id,\n address,\n star,\n recommend_lv,\n pv,\n plantocounts,\n beentocounts,\n overall_rank,\n ranking,\n grade,\n grade_distrib,\n commentcounts,\n tips,\n tagid,\n related_pois,\n nomissed,\n keyword,\n cateid,\n url,\n phone,\n site,\n imgurl,\n commenturl,\n introduction,\n '',\n opentime,\n price,\n recommended_time,\n wayto,\n 0,\n 0,\n insert_time\n FROM {2}\n WHERE {0} > '{3}'\n ORDER BY {0}\n LIMIT {4};'''.format(time_key[_type], to_table_name, each_table, u_time, limit)\n query_sql_list.append(query_sql)\n # elif to_table_name == 'rest_final':\n # query_sql = '''REPLACE INTO poi_merge.rest SELECT *\n # FROM {2}\n # WHERE {0} >= '{3}'\n # ORDER BY {0}\n # LIMIT {4};'''.format(time_key[_type], to_table_name, each_table, u_time, limit)\n\n else:\n raise TypeError(\"Unknown Type [u_time: {}][to_table_name: {}]\".format(u_time, to_table_name))\n\n for _each_query_sql in query_sql_list:\n is_replace = True\n try:\n replace_count = local_cursor.execute(_each_query_sql)\n except pymysql.err.IntegrityError as integrity_err:\n _args = integrity_err.args\n if 'Duplicate entry' in _args[1]:\n # 当出现 duplicate entry 时候,使用 Insert Ignore 代替(replace into 会出现 duplicate error,暂时不知道原因)\n is_replace = False\n _each_query_sql = _each_query_sql.replace('REPLACE INTO', 'INSERT IGNORE INTO')\n replace_count = local_cursor.execute(_each_query_sql)\n else:\n logger.exception(msg=\"[table_name: {}][error_sql: {}]\".format(each_table, _each_query_sql),\n exc_info=integrity_err)\n continue\n except Exception as e:\n logger.exception(msg=\"[table_name: {}][error_sql: {}]\".format(each_table, _each_query_sql), exc_info=e)\n continue\n logger.debug(\n \"[insert data][to: {}][from: {}][update_time: {}][final_update_time: {}][limit: {}][line_count: {}][\"\n \"{}: {}][takes: {}]\".format(\n to_table_name if 'poi_merge' not in _each_query_sql else 'poi_merge.attr' if 'poi_merge.attr' in _each_query_sql else 'poi_merge.rest',\n each_table,\n u_time,\n final_update_time,\n limit,\n line_count,\n 'replace_count' if is_replace else 'insert_ignore_count',\n replace_count,\n time.time() - start\n ))\n local_conn.commit()\n local_cursor.close()\n\n update_seek_table(each_table, final_update_time)\n local_conn.close()\n\n\ndef main():\n create_table()\n load_data(limit=5000)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"serviceplatform_data/load_final_data_test.py","file_name":"load_final_data_test.py","file_ext":"py","file_size_in_byte":10693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"298856813","text":"# 707. 设计链表\r\n# 20190402\r\n\r\nclass Node():\r\n def __init__(self, value):\r\n self.value = value\r\n self.next = None\r\n\r\nclass MyLinkedList(object):\r\n\r\n def __init__(self):\r\n \"\"\"\r\n Initialize your data structure here.\r\n \"\"\"\r\n self.head = Node(-1)\r\n\r\n def size(self):\r\n head = self.head\r\n length = 0\r\n while head is not None:\r\n length += 1\r\n head = head.next\r\n return length\r\n\r\n def get(self, index):\r\n \"\"\"\r\n Get the value of the index-th node in the linked list. If the index is invalid, return -1.\r\n :type index: int\r\n :rtype: int\r\n \"\"\"\r\n head = self.head\r\n l = self.size()\r\n if (index < 0) or (index > l-1): return -1\r\n i = 0\r\n while i <= index:\r\n if i == index:\r\n return head.value\r\n i += 1\r\n head = head.next\r\n return -1\r\n\r\n def addAtHead(self, val):\r\n \"\"\"\r\n Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.\r\n :type val: int\r\n :rtype: None\r\n \"\"\"\r\n head = self.head\r\n new_node = Node(val)\r\n new_node.next = head\r\n self.head = new_node\r\n\r\n def addAtTail(self, val):\r\n \"\"\"\r\n Append a node of value val to the last element of the linked list.\r\n :type val: int\r\n :rtype: None\r\n \"\"\"\r\n head = self.head\r\n new_node = Node(val)\r\n new_node.next = None\r\n while head is not None:\r\n prev = head\r\n head = head.next\r\n prev.next = new_node\r\n\r\n def addAtIndex(self, index, val):\r\n \"\"\"\r\n Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.\r\n :type index: int\r\n :type val: int\r\n :rtype: None\r\n \"\"\"\r\n head = self.head\r\n l = self.size()\r\n i = 0\r\n while head is not None and i <= index:\r\n if i == index:\r\n new_node = Node(val)\r\n if index == 0:\r\n new_node.next = head\r\n self.head = new_node\r\n else:\r\n new_node.next = head\r\n prev.next = new_node\r\n return None\r\n prev = head\r\n head = head.next\r\n i += 1\r\n\r\n if head is None and i == index:\r\n new_node = Node(val)\r\n prev.next = new_node\r\n\r\n def deleteAtIndex(self, index):\r\n \"\"\"\r\n Delete the index-th node in the linked list, if the index is valid.\r\n :type index: int\r\n :rtype: None\r\n \"\"\"\r\n head = self.head\r\n i = 0\r\n while head is not None and i <= index:\r\n if i == index:\r\n if index == 0:\r\n head = head.next\r\n self.head = head\r\n else:\r\n prev.next = head.next\r\n return None\r\n prev = head\r\n head = head.next\r\n i += 1\r\n","sub_path":"707. 设计链表.py","file_name":"707. 设计链表.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"431302824","text":"# -*- encoding: utf-8 -*-\nfrom Queue import Queue\nclass UndirectedGraphNode:\n def __init__(self, x):\n self.label = x\n self.neighbors = []\nclass Solution:\n # @param node, a undirected graph node\n # @return a undirected graph node\n def __init__(self):\n self.dict = {}\n\n def cloneGraph(self, node):\n # write your code here\n if node is None:\n return node\n # 用BFS来traverse图并得到所以nodes\n nodes = self.getNodes(node)\n\n # copy nodes, 存hash(key->value = old node->new node)\n hash = self.dict\n for each1 in nodes:\n hash[each1] = UndirectedGraphNode(each1.label)\n\n # copy neighbors\n for each2 in nodes:\n new_node = hash.get(each2)\n for neighbor in each2.neighbors:\n new_neighbor = hash.get(neighbor)\n new_node.neighbors.append(new_neighbor)\n return hash.get(node)\n\n\n def getNodes(self,node):\n queue = Queue()\n set = {}\n queue.put(node)\n set[node] = True\n while not queue.empty():\n head = queue.get()\n for neighbor in head.neighbors:\n if not set.has_key(neighbor):\n set[neighbor] = True\n queue.put(neighbor)\n return set\n","sub_path":"lintcode/graph and search/137 clone graph.py","file_name":"137 clone graph.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"370845798","text":"from __future__ import division\nimport json\n# import nltk\nimport sys\nimport torch\nimport math\nimport logging\nimport numpy as np\nfrom os.path import expanduser\nfrom numpy import linalg as LA\n\n\n# tokenizer = nltk.tokenize.TreebankWordTokenizer()\n\n\ndef pearson(x, y):\n x = np.array(x)\n y = np.array(y)\n x = x - np.mean(x)\n y = y - np.mean(y)\n return x.dot(y) / (LA.norm(x) * LA.norm(y))\n\n\ndef URL_maxF1_eval(predict_result, test_data_label):\n test_data_label = [item >= 1 for item in test_data_label]\n counter = 0\n tp = 0.0\n fp = 0.0\n fn = 0.0\n tn = 0.0\n\n for i, t in enumerate(predict_result):\n\n if t > 0.5:\n guess = True\n else:\n guess = False\n label = test_data_label[i]\n # print guess, label\n if guess == True and label == False:\n fp += 1.0\n elif guess == False and label == True:\n fn += 1.0\n elif guess == True and label == True:\n tp += 1.0\n elif guess == False and label == False:\n tn += 1.0\n if label == guess:\n counter += 1.0\n # else:\n # print label+'--'*20\n # if guess:\n # print \"GOLD-\" + str(label) + \"\\t\" + \"SYS-\" + str(guess) + \"\\t\" + sent1 + \"\\t\" + sent2\n\n try:\n P = tp / (tp + fp)\n R = tp / (tp + fn)\n F = 2 * P * R / (P + R)\n except:\n P = 0\n R = 0\n F = 0\n\n # print \"PRECISION: %s, RECALL: %s, F1: %s\" % (P, R, F)\n # print \"ACCURACY: %s\" % (counter/len(predict_result))\n accuracy = counter / len(predict_result)\n\n # print \"# true pos:\", tp\n # print \"# false pos:\", fp\n # print \"# false neg:\", fn\n # print \"# true neg:\", tn\n maxF1 = 0\n P_maxF1 = 0\n R_maxF1 = 0\n probs = predict_result\n sortedindex = sorted(range(len(probs)), key=probs.__getitem__)\n sortedindex.reverse()\n\n truepos = 0\n falsepos = 0\n for sortedi in sortedindex:\n if test_data_label[sortedi] == True:\n truepos += 1\n elif test_data_label[sortedi] == False:\n falsepos += 1\n precision = 0\n if truepos + falsepos > 0:\n precision = truepos / (truepos + falsepos)\n\n recall = truepos / (tp + fn)\n f1 = 0\n if precision + recall > 0:\n f1 = 2 * precision * recall / (precision + recall)\n if f1 > maxF1:\n # print probs[sortedi]\n maxF1 = f1\n P_maxF1 = precision\n R_maxF1 = recall\n print\n \"PRECISION: %s, RECALL: %s, max_F1: %s\" % (P_maxF1, R_maxF1, maxF1)\n return (accuracy, maxF1)\n\n\ndef tokenize(text):\n \"\"\"\n Tokenize a piece of text using the Treebank tokenizer\n\n :return: a list of strings\n \"\"\"\n return tokenizer.tokenize(text)\n\n\n# return text.split()\n\ndef shuffle_arrays(*arrays):\n \"\"\"\n Shuffle all given arrays with the same RNG state.\n\n All shuffling is in-place, i.e., this function returns None.\n \"\"\"\n rng_state = np.random.get_state()\n for array in arrays:\n np.random.shuffle(array)\n np.random.set_state(rng_state)\n\n\ndef readSTSdata(dir):\n # print(len(dict))\n # print(dict['bmxs'])\n lsents = []\n rsents = []\n labels = []\n for line in open(dir + 'a.toks'):\n line = line.decode('utf-8')\n pieces = line.strip().split()\n lsents.append(pieces)\n for line in open(dir + 'b.toks'):\n line = line.decode('utf-8')\n pieces = line.strip().split()\n rsents.append(pieces)\n for line in open(dir + 'sim.txt'):\n sim = float(line.strip())\n ceil = int(math.ceil(sim))\n floor = int(math.floor(sim))\n tmp = [0, 0, 0, 0, 0, 0]\n if floor != ceil:\n tmp[ceil] = sim - floor\n tmp[floor] = ceil - sim\n else:\n tmp[floor] = 1\n labels.append(tmp)\n # data=(lsents,rsents,labels)\n if not len(lsents) == len(rsents) == len(labels):\n print('error!')\n sys.exit()\n clean_data = []\n for i in range(len(lsents)):\n clean_data.append((lsents[i], rsents[i], labels[i]))\n return clean_data\n\n\ndef readSNLIdata(dir):\n # print(len(dict))\n # print(dict['bmxs'])\n lsents = []\n rsents = []\n labels = []\n for line in open(dir + 'a.toks'):\n pieces = line.strip().split()\n lsents.append(pieces)\n for line in open(dir + 'b.toks'):\n pieces = line.strip().split()\n rsents.append(pieces)\n for line in open(dir + 'sim.txt'):\n sim = line.strip()\n if sim == 'neutral':\n labels.append([0, 1, 0])\n elif sim == 'entailment':\n labels.append([1, 0, 0])\n elif sim == 'contradiction':\n labels.append([0, 0, 1])\n else:\n labels.append([0, 0, 0])\n clean_data = []\n for i in range(len(lsents)):\n if labels[i] != [0, 0, 0]:\n clean_data.append((lsents[i], rsents[i], labels[i].index(max(labels[i]))))\n return clean_data\n\n\ndef read_corpus(filename, lowercase):\n \"\"\"\n Read a JSONL or TSV file with the SNLI corpus\n\n :param filename: path to the file\n :param lowercase: whether to convert content to lower case\n :return: a list of tuples (first_sent, second_sent, label)\n \"\"\"\n logging.info('Reading data from %s' % filename)\n # we are only interested in the actual sentences + gold label\n # the corpus files has a few more things\n useful_data = []\n\n # the SNLI corpus has one JSON object per line\n with open(filename, 'rb') as f:\n\n if filename.endswith('.tsv') or filename.endswith('.txt'):\n\n for line in f:\n line = line.decode('utf-8').strip()\n if lowercase:\n line = line.lower()\n if len(line.split('\\t')) == 10:\n (label, _, _, _, _, sent1, sent2, _, _, _) = line.split('\\t')\n elif len(line.split('\\t')) == 14:\n (label, _, _, _, _, sent1, sent2, _, _, _, _, _, _, _) = line.split('\\t')\n # sent1, sent2, label = line.split('\\t')\n if label not in ('contradiction', 'neutral', 'entailment'):\n continue\n tokens1 = tokenize(sent1)\n tokens2 = tokenize(sent2)\n useful_data.append((tokens1, tokens2, ('contradiction', 'neutral', 'entailment').index(label)))\n else:\n for line in f:\n line = line.decode('utf-8')\n if lowercase:\n line = line.lower()\n data = json.loads(line)\n if data['gold_label'] == '-':\n # ignore items without a gold label\n continue\n\n sentence1_parse = data['sentence1_parse']\n sentence2_parse = data['sentence2_parse']\n label = data['gold_label']\n\n tree1 = nltk.Tree.fromstring(sentence1_parse)\n tree2 = nltk.Tree.fromstring(sentence2_parse)\n tokens1 = tree1.leaves()\n tokens2 = tree2.leaves()\n t = (tokens1, tokens2, ('neutral', 'contradiction', 'entailment', 'hidden').index(label))\n useful_data.append(t)\n\n return useful_data\n","sub_path":"model/DecAtt/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":7220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"114959999","text":"import arcpy\nimport os\nimport re\n\n\nfrom arcpy import env\nenv.workplace = 'E:\\\\workplace\\\\CarbonProject\\\\temp'\n\nre_tif = re.compile(r'.tif$')\nfiles_path = 'e:\\\\workplace\\\\CarbonProject\\\\GISS_raster'\nraster_path = 'e:\\\\workplace\\\\CarbonProject\\\\raster'\nfiles = os.listdir(files_path)\nrasters = []\nenvelope_europe = \"-30 40 45 70\"\nenvelope_india = \"65 15 90 20\"\nenvelope_east_china = \"95 15 135 50\"\nenvelope_northen_east_asia = \"120 30 150 45\"\nenvelope_america = \"-130 22 -60 55\"\n\nfor file in files:\n if not os.path.isdir(file):\n if re_tif.search(file):\n rasters.append(file)\n\nif not rasters:\n exit\n\nfor raster in rasters:\n in_raster = files_path + '\\\\' + raster\n\n europe_out_raster = raster_path + '\\\\' + raster[:-4] + '_europe.tif'\n print(\"Clipping \" + europe_out_raster)\n arcpy.Clip_management(in_raster, envelope_europe, europe_out_raster)\n\n india_out_raster = raster_path + '\\\\' + raster[:-4] + '_india.tif'\n print(\"Clipping \" + india_out_raster)\n arcpy.Clip_management(in_raster, envelope_india, india_out_raster)\n\n east_china_out_raster = raster_path + '\\\\' + raster[:-4] + '_east_china.tif'\n print(\"Clipping \" + east_china_out_raster)\n arcpy.Clip_management(in_raster, envelope_east_china, east_china_out_raster)\n\n northen_east_asia_out_raster = raster_path + '\\\\' + raster[:-4] + '_northen_east_asia.tif'\n print(\"Clipping \" + northen_east_asia_out_raster)\n arcpy.Clip_management(in_raster, envelope_northen_east_asia, northen_east_asia_out_raster)\n\n america_out_raster = raster_path + '\\\\' + raster[:-4] + '_america.tif'\n print(\"Clipping \" + america_out_raster)\n arcpy.Clip_management(in_raster, envelope_america, america_out_raster)\n \n","sub_path":"arcgis_python/GISS_clip_raster.py","file_name":"GISS_clip_raster.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"478006412","text":"from math import sqrt\n\n\ndef euclidean_distance(weights1, weights2):\n\tif len(weights2) != len(weights1):\n\t\traise RuntimeError('vectors have different size')\n\tdistance = 0.\n\tfor i in range(len(weights1)):\n\t\tdistance += (weights1[i] - weights2[i]) ** 2\n\n\treturn sqrt(distance)\n","sub_path":"som/somutils.py","file_name":"somutils.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"202176233","text":"from models.units.base_unit import BaseUnit\nimport json\nimport time\nfrom models.combat.logging_cfg import battle_logger\n\n\ndef get_unit_from_json(json_file):\n if json_file is None:\n raise Exception('Missing config file for unit!')\n else:\n with open(json_file) as conf:\n data = json.load(conf)\n unit_instance = BaseUnit.new(**data)\n return unit_instance\n\n\ndef get_cfg_from_json(json_file):\n if json_file is None:\n raise Exception('Missing config file for unit!')\n else:\n with open(json_file) as conf:\n armies = list()\n data = json.load(conf)\n for unit_data in data['armies']:\n unit = BaseUnit.new(**unit_data)\n armies.append(unit)\n return armies\n\n\nclass Battle:\n setup = {}\n\n def __init__(self, incoming_config=None):\n self._participants = get_cfg_from_json(incoming_config)\n self.current_attacker_index = 0\n self._log_timestamp = time.monotonic()\n\n battle_logger.info('Initiating new battle')\n battle_logger.info('Participating units:')\n for unit in self._participants:\n battle_logger.info('%s' % unit)\n\n def next_alive_unit(self, index):\n next_alive_unit_index = index + 1\n if next_alive_unit_index > (len(self._participants) - 1):\n next_alive_unit_index = 0\n if self._participants[next_alive_unit_index].is_alive:\n return next_alive_unit_index\n else:\n if next_alive_unit_index == self.current_attacker_index:\n return self.current_attacker_index\n else:\n return self.next_alive_unit(next_alive_unit_index)\n\n def clockwise_attack(self):\n defending_unit_index = self.next_alive_unit(self.current_attacker_index)\n if defending_unit_index is not None:\n # print('attacker is ', self.current_attacker_index, ' on', defending_unit_index)\n self._participants[self.current_attacker_index].engage(self._participants[defending_unit_index])\n self.current_attacker_index = self.next_alive_unit(self.current_attacker_index)\n\n def winner_get(self):\n alive_unit_count = 0\n for index, unit in enumerate(self._participants):\n if unit.is_alive:\n alive_unit_count += 1\n alive_index = index\n if alive_unit_count == 1:\n battle_logger.info('WE HAVE A WINNER %s \\n' % self._participants[alive_index])\n return self._participants[alive_index]\n else:\n return False\n\n def battle_log_schedule(self, every):\n cur_time = time.monotonic()\n if cur_time - self._log_timestamp >= every:\n self._log_timestamp = cur_time\n battle_logger.info(self.battle_log_get())\n\n def battle_log_get(self):\n string = 'battle_status: \\n'\n for unit in self._participants:\n string += str(unit) + '\\n'\n string += '_' * 80\n return string\n\n","sub_path":"models/combat/battle.py","file_name":"battle.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"2261063","text":"#! /usr/bin/env python\n#-*- coding: utf-8 -*-\n\n# import des librairies\nimport os\nimport json\nimport MySQLdb\nimport sys\nimport Adafruit_DHT\nimport csv\nimport ephem\nimport datetime\nimport time\nimport RPi.GPIO as GPIO\nimport smtplib\nfrom email.MIMEMultipart import MIMEMultipart\nfrom email.MIMEBase import MIMEBase\nfrom email.MIMEText import MIMEText\nfrom email.Utils import COMMASPACE, formatdate\nfrom email import Encoders\n\n\nGPIO.setwarnings(False) # pour éviter alarme : (This channel is already in use)\nGPIO.setmode(GPIO.BCM) # gpio numérotation BCM\n\n \nGPIO.setup(4, GPIO.OUT) # lumière\nGPIO.setup(17, GPIO.OUT) # chauffage\n\n# on ouvre le fichier config .json\nwith open('/var/www/html/terraspi/csv/bdd.json') as config: \n config = json.load(config)\n\n # on recupère le login et mdp de la bdd \nlogin = config[\"mysql\"][\"loginmysql\"]\nmdp = config[\"mysql\"][\"mdpmysql\"]\n\n# on se connecte a la bdd\ndb = MySQLdb.connect(host=\"localhost\", \n user=login, \n passwd=mdp, \n db=\"Terrarium\") \ncur = db.cursor()\ncur.execute(\"SELECT * FROM config\") # on sort tout de la table config\n\nfor row in cur.fetchall(): # et on récupère les champs qui nous intéresse\n longitude = row[3]\n latitude = row[4]\n altitude = row[5]\n limiteBasse = row[6]\n limiteHaute = row[7]\n jour = row[8]\n nuit = row[9]\n envoyeur = row[11]\n mdpenvoyeur = row[12]\n receveur = row[13]\n HeureEI = row[15]\n\ndb.close() # on ferme la connexion a la bdd\n\n# ici on régle en fonction des coordonnées mis sur la page admin\nsomewhere = ephem.Observer() \nsomewhere.lon = str(longitude) # longitude\nsomewhere.lat = str(latitude)\nsomewhere.elevation = int(altitude) # altitude \n\n# Heure actuelle ( du pi, GMT) convertie en chiffres\nheurenow = int(time.strftime('%H%M'))\n\n# Récupérer la date et l'heure\ndateandtime = time.strftime('%Y-%m-%d %H:%M',time.localtime()) \n\nsun = ephem.Sun()\n# r1 = heure lever soleil UTC\nr1 = somewhere.next_rising(sun)\n# s1 = heure coucher soleil UTC\ns1 = somewhere.next_setting(sun)\n\n# coucher = heure du coucher du soleil, en chiffres\n# on commence par convertir l'heure de coucher en chiffres\n# après avoir extrait les informations inutiles (date, etc.)\nheurec = str(s1)\nlong = len(heurec)\nfin = long - 8\nheurec = heurec[fin:long-3]\ncoucher = int(heurec[0:2] + heurec[3:5])\n\n# lever = heure du lever du soleil, en chiffres\n# on commence par convertir l'heure de lever en chiffres\n# après avoir extrait les informations inutiles (date, etc.)\nheurel = str(r1)\nlong = len(heurel)\nfin = long - 8\nheurel = heurel[fin:long-3]\nlever = int(heurel[0:2] + heurel[3:5])\n\nlever = lever + HeureEI #heure ete hiver\ncoucher = coucher + HeureEI\n\n\nif lever < heurenow < coucher: # si l'heure actuelle est comprise entre l'heure du lever et du coucher, s'il faut jour quoi.\n GPIO.output (4, True) # on allume la lumière (on intervertira True et False suivant le branchement du relais 'normalement ouvert ou fermer' )\n target = jour # on donne la consigne de jour comme température au point chaud\n \nelse: \n GPIO.output (4, False) # sinon on éteint la lumière\n target = nuit # on donne la consigne de nuit comme température au point chaud\n\n\nfname1 = \"/var/www/html/terraspi/csv/ephem.csv\" # on créer le fichier \nfile1 = open(fname1, \"wb\") \n \ntry:\n # Création de CSV.\n writer1 = csv.writer(file1)\n # Écriture de la ligne d'en-tête avec le titre\n # des colonnes.\n writer1.writerow( ('lever' ,'coucher') )\n # Écriture des quelques données.\n writer1.writerow( (lever, coucher) ) \n\nfinally: \n # Fermeture du fichier source\n file1.close() \n \n# on lit les sondes\nhumF, tempF = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 22) # point froid\nhumC, tempC = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 27) # point chaud\n\n# on arrondi a 2 chiffres\nhumF = round(humF,2) \ntempF = round(tempF,2)\nhumC = round(humC,2)\ntempC = round(tempC,2)\n\n# le contrôle du chauffage\nif tempC > target: # si la température du point chaud dépasse la target (nuit ou jour)\n GPIO.output (17, False) # on coupe le chauffage\n\t\t\t\t\t\t\t\t# (on intervertira True et False suivant le branchement du relais 'normalement ouvert ou fermer')\nelse:\n GPIO.output (17, True) # sinon on l'allume \n\n# on créer le fichier\nfname = \"/var/www/html/terraspi/csv/result.csv\" \nfile = open(fname, \"wb\")\n \ntry:\n # Création du CSV \n writer = csv.writer(file)\n # Écriture de la ligne d'en-tête avec le titre\n # des colonnes.\n writer.writerow( ('Humidity' ,'Temperature') )\n # Écriture des quelques données.\n writer.writerow( (humF, tempF) )\n writer.writerow( (humC, tempC) ) \n\nfinally:\n # Fermeture du fichier source \n file.close() \n\n # Connexion a la base MySQL\nbdd = MySQLdb.connect(host=\"localhost\",user=login,passwd=mdp,db=\"Terrarium\") \nreq = bdd.cursor()\n\n# Envoi a la base de donnée\ntry:\n req.execute(\"\"\"insert into capteurdata (`dateandtime`,`tempF`,`humF`,`tempC`,`humC`) values (%s,%s,%s,%s,%s)\"\"\",(dateandtime,tempF,humF,tempC,humC))\n bdd.commit()\n \nexcept:\n bdd.rollback()\n \nbdd.close() # Fermeture de la connexion\n\nUSERNAME = envoyeur # adresse de l'envoyeur\nPASSWORD = mdpenvoyeur # mot de passe\n\n# fonction sendmail\ndef sendMail(to, subject, text, files=[]): \n\tassert type(to)==list\n\tassert type(files)==list\n\n\tmsg = MIMEMultipart()\n\tmsg['From'] = USERNAME\n\tmsg['To'] = COMMASPACE.join(to)\n\tmsg['Date'] = formatdate(localtime=True)\n\tmsg['Subject'] = subject\n\n\tmsg.attach( MIMEText(text) )\n\n\tfor file in files:\n\t\tpart = MIMEBase('application', \"octet-stream\")\n\t\tpart.set_payload( open(file,\"rb\").read() )\n\t\tEncoders.encode_base64(part)\n\t\tpart.add_header('Content-Disposition', 'attachment; filename=\"%s\"'\n\t\t\t\t\t % os.path.basename(file))\n\t\tmsg.attach(part)\n\n\tserver = smtplib.SMTP('smtp.gmail.com:587')\n\tserver.ehlo_or_helo_if_needed()\n\tserver.starttls()\n\tserver.ehlo_or_helo_if_needed()\n\tserver.login(USERNAME,PASSWORD)\n\tserver.sendmail(USERNAME, to, msg.as_string())\n\tserver.quit()\n\t\n\t\n# On envoi un mail , si la température au point chaud dépasse les limites.\nif tempC <= limiteBasse or tempC >= limiteHaute :\n \n sendMail( [receveur], # adresse ou l'on veut envoyer le mail\n \"Alerte terrarium !!!!\", # sujet \n \"limite atteinte, il fait %s °C au point chaud ,connecte toi vite !!!\" %tempC, # le message\n [\"/var/www/html/terraspi/img/alerte.jpeg\"]) # chemin pièce jointe \n\nsys.exit(1)\n","sub_path":"terraspi/prog/terra.py","file_name":"terra.py","file_ext":"py","file_size_in_byte":6787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"127482385","text":"#Prepare epression for calculation. \n#For it, delete all spaces, and give negative numbers good form.\n\nimport re\nfrom shared import *\nfrom errors import *\n\ndef prepare_expression(expression):\n if len(expression) >= 0:\n wrong_functions = is_good(expression)\n if wrong_functions:\n raise UnknownFunction(', '.join(wrong_functions))\n if not is_valuable(expression[0]):\n expression = \"(\" + expression + \")\"\n expression = process_spaces(expression)\n expression = process_repeated_signs(expression)\n expression = process_mult_bracket(expression)\n expression = process_numb_before_func(expression)\n expression = process_unary_operators(expression)\n expression = process_logarithm(expression)\n\n return expression.replace(\" \", \"\").replace(\"(-\",\"(#\"). replace(\"(+\", \"(\")\n\ndef is_good(expression):\n return re.findall(\"[^\\d\\w\\+\\*\\-\\/\\.\\(\\)\\s\\^\\,\\%]\", expression)\n\ndef process_logarithm(expression):\n return expression.replace(\"log10\", \"lg\").replace(\"log\", \"ln\")\n\ndef process_numb_before_func(expression):\n numb_before_func = re.findall(r\"\\d+[a-z]+\", expression)\n if numb_before_func:\n for i in numb_before_func:\n tmp = re.split('([\\d]+)', i.strip())\n expression = expression.replace(i, tmp[1]+\"*\"+tmp[2])\n return expression\n\ndef process_spaces(expression):\n return expression.replace(\" \", \"\")\n\ndef process_unary_operators(expression):\n return expression.replace(\"*-\", \"*#\")\\\n .replace(\"/-\",\"/#\") \\\n .replace(\"^-\", \"^#\")\\\n .replace(\"**-\", \"**#\")\\\n .replace(\"++\", \"+\")\\\n .replace(\"-+\", \"-\")\\\n .replace(\"+-\", \"+#\")\\\n .replace(\"--\", \"-#\")\n \n#Replace \"++\" to \"+\", \"-+\" to \"-\" etc.\ndef process_repeated_signs(expression):\n sequences = find_sequences_signs(expression)\n need_to_replace = process_sequences_signs(sequences)\n replaced = replace_sequences(expression, need_to_replace)\n result = process_brackets(replaced) \n return result\n\ndef process_brackets(expression):\n return expression.replace(\"(-+\", \"(-\")\\\n .replace(\"(+-\", \"(-\")\\\n .replace(\"(--\", \"(\")\\\n .replace(\"(++\", \"(\")\n\ndef find_sequences_signs(expression):\n return re.findall(\"[+-]{3,}\", expression)\n\ndef process_sequences_signs(multiplied_signs):\n need_to_replace = {}\n for sequence in multiplied_signs:\n count = sequence[1:].count('-')\n if count % 2 == 0:\n need_to_replace[sequence] = sequence[:1]\n else:\n need_to_replace[sequence] = sequence[:1] + '-'\n return need_to_replace\n\ndef replace_sequences(expression, need_to_replace):\n for old, new in need_to_replace.iteritems():\n expression = expression.replace(old, new)\n return expression\n \n#Replace '3(' to '3*(', and ')4' to ')*4'\ndef process_mult_bracket(expression):\n numb_mul_bracket = re.findall(r\"[*+-/%#]\\d+\\(|\\p\\i\\(|\\e\\(|\\)\\.\\d+\\(|\\)\\d+\\.\\(|\\)\\d+\\(|\\)\\d+|^\\d+\\(|\\)\\w+\", expression)\n expression = expression.replace(\")(\", \")*(\")\n if numb_mul_bracket:\n multiplies = map(lambda a: (a, a.replace(\"(\", \"*(\").replace(\")\", \")*\")), numb_mul_bracket)\n multiplies = set(multiplies)\n for old, new in multiplies:\n expression = expression.replace(old, new)\n return expression\n\n\n","sub_path":"Calculator/preparator.py","file_name":"preparator.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"271885751","text":"from django.shortcuts import render\r\nfrom django.shortcuts import render_to_response\r\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\r\nfrom django.http.response import HttpResponse\r\nfrom django.http import JsonResponse\r\nfrom iiiedu.models import Branch, Tag, Cate, Course, Role, UserProfile, Favorite, Reply, Menu, Series, Theme\r\nfrom iiiedu.mongohelper import MongoHelper\r\nimport json\r\nfrom django.http import HttpResponseRedirect\r\nfrom django.core.urlresolvers import reverse\r\n\r\n\r\n# mongo = MongoHelper(host=\"mongodb://mario:69538463@ds155288.mlab.com:55288/course\", db_name='course',\r\n# collection='iiiedu')\r\n\r\nchart = MongoHelper(host=\"mongodb://mario:69538463@ds155288.mlab.com:55288/course\", db_name='course',\r\n collection='chart')\r\n\r\n\r\n# chert\r\n\r\ndef TopCourse(request):\r\n data = chart.collection.find_one({'chart': 'class'}, {'_id': 0, 'data': 1})\r\n ret = {\"data\": data[\"data\"], \"title\": \"十大課程\"}\r\n return render(request, \"chert/index.html\", ret)\r\n\r\n\r\ndef TopCertified(request):\r\n data = chart.collection.find_one({'chart': 'cert'}, {'_id': 0, 'data': 1})\r\n ret = {\"data\": data[\"data\"], \"title\": \"十大認證\"}\r\n\r\n return render(request, \"chert/index.html\", ret)\r\n\r\n\r\ndef TopLang(request):\r\n data = chart.collection.find_one({'chart': 'lang'}, {'_id': 0, 'data': 1})\r\n ret = {\"data\": data[\"data\"], \"title\": \"十大語言(待優化)\"}\r\n\r\n # ![](https://i.imgur.com/FDIbFL5.jpg)\r\n\r\n return render(request, \"chert/index.html\", ret)\r\n\r\n\r\ndef TopTheme(request):\r\n data = chart.collection.find_one({'chart': 'theme'}, {'_id': 0, 'data': 1})\r\n ret = {\"data\": data[\"data\"], \"title\": \"主題\"}\r\n\r\n # ![](https://i.imgur.com/FDIbFL5.jpg)\r\n\r\n return render(request, \"chert/index.html\", ret)\r\n\r\n\r\n# theme\r\n\r\ndef theme(request, pk):\r\n data = chart.collection.find_one({'chart': pk}, {'_id': 0, 'data': 1})\r\n t = Theme.objects.get(en=pk)\r\n series = Series.objects.filter(theme=t)\r\n\r\n ret = {\"data\": data[\"data\"], \"title\": t.name, 'url': t.en, 'menu': series}\r\n return render(request, \"theme/index.html\", ret)\r\n\r\n\r\n# series\r\n\r\ndef series(request, pk):\r\n s = Series.objects.get(en=pk)\r\n\r\n t = s.theme.all()[0]\r\n series = Series.objects.filter(theme=t)\r\n\r\n contact_list = Course.objects.filter(series=s)\r\n\r\n # contact_list = Course.objects.exclude(Cate__name='認證').exclude(Cate__name=\"養成班\")\r\n paginator = Paginator(contact_list, 10) # Show 10 contacts per page\r\n\r\n page = request.GET.get('page')\r\n try:\r\n data = paginator.page(page)\r\n except PageNotAnInteger:\r\n data = paginator.page(1)\r\n except EmptyPage:\r\n data = paginator.page(paginator.num_pages)\r\n\r\n page = {\r\n 'theme': {'name': t.name, 'url': t.en},\r\n 'series': {'name': s.name, 'url': s.en},\r\n }\r\n\r\n ret = {'data': data, 'menu': series, 'page': page}\r\n\r\n return render(request, \"series/index.html\", ret)\r\n\r\n\r\n# Course\r\n\r\ndef course(request):\r\n title = '專業課程'\r\n contact_list = Course.objects.exclude(Tag__name='認證').exclude(Tag__name=\"養成班\")\r\n paginator = Paginator(contact_list, 10) # Show 10 contacts per page\r\n\r\n page = request.GET.get('page')\r\n try:\r\n data = paginator.page(page)\r\n except PageNotAnInteger:\r\n data = paginator.page(1)\r\n except EmptyPage:\r\n data = paginator.page(paginator.num_pages)\r\n\r\n ret = {'data': data, 'title': title}\r\n\r\n return render(request, \"course/index.html\", ret)\r\n\r\n\r\ndef course_cert(request):\r\n q = '認證'\r\n contact_list = Course.objects.filter(Tag__name=q)\r\n paginator = Paginator(contact_list, 10) # Show 10 contacts per page\r\n\r\n page = request.GET.get('page')\r\n try:\r\n data = paginator.page(page)\r\n except PageNotAnInteger:\r\n data = paginator.page(1)\r\n except EmptyPage:\r\n data = paginator.page(paginator.num_pages)\r\n\r\n ret = {'data': data, 'title': q}\r\n return render(request, \"course/index.html\", ret)\r\n\r\n\r\ndef course_full(request):\r\n q = '養成班'\r\n\r\n contact_list = Course.objects.filter(Tag__name=q)\r\n paginator = Paginator(contact_list, 10) # Show 10 contacts per page\r\n\r\n page = request.GET.get('page')\r\n try:\r\n data = paginator.page(page)\r\n except PageNotAnInteger:\r\n data = paginator.page(1)\r\n except EmptyPage:\r\n data = paginator.page(paginator.num_pages)\r\n\r\n ret = {'data': data, 'title': q}\r\n return render(request, \"course/index.html\", ret)\r\n\r\n\r\n# search\r\n\r\ndef search(request):\r\n name = request.GET.get('name')\r\n print(request.GET.get('anc'))\r\n print(request.GET.get('pppp'))\r\n\r\n contact_list = Course.objects.filter(name__icontains=name)\r\n paginator = Paginator(contact_list, 10) # Show 10 contacts per page\r\n\r\n page = request.GET.get('page')\r\n try:\r\n data = paginator.page(page)\r\n except PageNotAnInteger:\r\n data = paginator.page(1)\r\n except EmptyPage:\r\n data = paginator.page(paginator.num_pages)\r\n\r\n ret = {'data': data, 'title': \"%s 搜尋結果\" % name}\r\n\r\n return render(request, \"search.html\", ret)\r\n\r\n\r\ndef testmap(request):\r\n # Create two threads as follows\r\n return HttpResponse(\"ok\")\r\n\r\n\r\ndef test_page(request):\r\n ret = {}\r\n\r\n return render(request, \"test.html\", ret)\r\n\r\n\r\ndef test_ajax(request):\r\n if request.POST:\r\n\r\n data = request.POST['data']\r\n print(data)\r\n else:\r\n data = \"ok\"\r\n return HttpResponse(data)\r\n\r\n\r\ndef cleardb(request):\r\n Tag.objects.all().delete()\r\n Cate.objects.all().delete()\r\n Course.objects.all().delete()\r\n Role.objects.all().delete()\r\n UserProfile.objects.all().delete()\r\n Favorite.objects.all().delete()\r\n Reply.objects.all().delete()\r\n Menu.objects.all().delete()\r\n Branch.objects.all().delete()\r\n\r\n return HttpResponse(\"清理OK\")\r\n\r\n\r\ndef testdb(request):\r\n t = Tag.objects.filter(**{'name': \"tag1\"})\r\n print(t)\r\n print(len(t))\r\n # x = mongo.collection.find_one()\r\n return HttpResponse(len(t))\r\n\r\n# redirect\r\ndef home_redirect(request):\r\n return HttpResponseRedirect(\r\n reverse('chart_theme')\r\n )","sub_path":"web_iiiedu/iiiedu/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"76833759","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Feb 7 22:58:26 2021\r\n\r\n@author: user\r\n\"\"\"\r\ngoods=[(60,10),(100,20),(120,30)]\r\ngoods.sort(key=lambda x:x[0]/x[1],reverse=True)\r\n\r\ndef fractional_backpack(goods,w):\r\n \r\n m=[0 for _ in range(len(goods))]\r\n total_v=0\r\n for i,(prize,weight) in enumerate(goods):\r\n if w>=weight:\r\n m[i]=1\r\n total_v+=prize\r\n w-=weight\r\n else:\r\n m[i]=w/weight\r\n total_v+=m[i]*prize\r\n w=0\r\n break\r\n print(total_v)\r\n print(m)\r\n \r\n return m,total_v\r\n \r\n\r\n \r\n \r\nfractional_backpack(goods, 50)\r\n\r\n ","sub_path":"fractional_backpack.py","file_name":"fractional_backpack.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"43895257","text":"# -*- coding: utf-8 -*-\n\"\"\"\n2020/11/05 15:55\nexplore data of CHEMDNER\n整理一个data class出来\n\"\"\"\n\nimport collections\nimport os\nimport matplotlib.pyplot as plt\nimport re\nimport nltk\nfrom flashtext import KeywordProcessor\n\nAbstract = collections.namedtuple('Abstract', ['PMID', 'title', 'abstract'])\nAnnotation = collections.namedtuple('Annotation', ['PMID', 'type_text', \n 'start', 'end', 'mention', 'type_cem'])\nclass Data:\n def __init__(self, path = '.\\\\chemdner_corpus'):\n self.path = path\n self.files = {\n 'train':{'abstracts':os.path.join(self.path, 'training.abstracts.txt'),\n 'annotations':os.path.join(self.path, 'training.annotations.txt')},\n 'silver':{'abstracts':os.path.join(self.path, 'silver.abstracts.txt'),\n 'annotations':os.path.join(self.path, 'silver.predictions.txt')},\n 'dev':{'abstracts':os.path.join(self.path, 'development.abstracts.txt'),\n 'annotations':os.path.join(self.path, 'development.annotations.txt')},\n 'eva':{'abstracts':os.path.join(self.path, 'evaluation.abstracts.txt'),\n 'annotations':os.path.join(self.path, 'evaluation.annotations.txt')},\n 'test':{'cdi':os.path.join(self.path, 'cdi_ann_test_13-09-13.txt'),\n 'cem':os.path.join(self.path, 'cem_ann_test_13-09-13.txt')},\n 'aux':{'chemical':os.path.join(self.path, 'chemdner_chemical_disciplines.txt'),\n 'corpus':os.path.join(self.path, 'chemdner_abs_test_pmid_label.txt')} \n }\n self.readData()\n \n def _preData(self, line, key2):\n if key2 == 'abstracts':\n return Abstract(*tuple(line.replace('\\n','').split('\\t')))\n elif key2 == 'annotations':\n return Annotation(*tuple(line.replace('\\n','').split('\\t')))\n \n def readData(self):\n self.data = {}\n for key1 in ['train', 'dev', 'eva']:\n self.data[key1] = {}\n for key2 in ['abstracts', 'annotations']:\n self.data[key1][key2] = []\n with open(self.files[key1][key2], 'r', encoding ='utf8') as f:\n line = f.readline()\n while line:\n self.data[key1][key2].append(self._preData(line, key2))\n line = f.readline()\n \n # def stat(self):\n # for key1 in self.data.keys():\n # for key2 in self.data[key1].keys():\n # print('data.{}.{}.length: {}'.format(key1, key2, len(self.data[key1][key2])))\n \n\nif __name__ == '__main__':\n d = Data()\n\ndef selfTest(d):\n '''\n 使用train, dev, eval生成的字典,交叉对数据集进行探索。\n 以字典的匹配结果作为base_baseline\n '''\n kps = {} # keyword processors\n ans_pred = {} # Annotations_pred_by_dict_method key1-pred, key2-vocab(kp)\n for key1 in ['train']:\n kps[key1] = KeywordProcessor(case_sensitive = True)\n for annotation in d.data[key1]['annotations']:\n kps[key1].add_keyword(annotation.mention, (annotation.type_cem, annotation.mention))\n for keya in ['train']:\n ans_pred[keya] = {}\n for keyb in ['train']:\n ans_pred[keya][keyb] = []\n for corpus in d.data[keya]['abstracts']:\n annotations_pre = kps[keyb].extract_keywords(corpus.title, span_info=True)\n # [(('Monument', 'Taj Mahal'), 0, 9), (('Location', 'Delhi'), 16, 21)]\n if len(annotations_pre):\n for a in annotations_pre:\n ans_pred[keya][keyb].append(\n Annotation(corpus.PMID, 'T', str(a[1]), str(a[2]), a[0][1], a[0][0]))\n annotations_pre = kps[keyb].extract_keywords(corpus.abstract, span_info=True)\n if len(annotations_pre):\n for a in annotations_pre:\n ans_pred[keya][keyb].append(\n Annotation(corpus.PMID, 'A', str(a[1]), str(a[2]), a[0][1], a[0][0]))\n # len(ans_pred['train']['train']) # 40208\n # len(d.data['train']['annotations']) # 29478\n # 探究一下True Negtive的原因\n rm_tt = _evalAA(d.data['train']['annotations'], ans_pred['train']['train'])\n text_tn = exploreA(d.data['train']['abstracts'], rm_tt['tn'])\n len(text_tn)\n for i in text_tn:\n print('\\t'.join(i))\n # 数据集本身的问题:子项的标注(多义性)问题/variance\n bt = []\n for i in text_tn:\n if len(i[-3]) and len(i[-1]):\n bt.append(re.match('[0-9a-zA-Z]', i[-3][-1]) is not None or \n re.match('[0-9A-z]', i[-1][0]) is not None)\n (len(bt) - sum(bt) + 3)/29478\n \n text_fp = exploreA(d.data['train']['abstracts'], rm_tt['fp'])\n len(text_fp)\n counter_keylength_fp = collections.Counter([len(i[-2]) for i in text_fp])\n x = list(counter_keylength_fp.elements())\n n_bins = max(counter_keylength_fp.keys()) - 1 # 35\n fig, ax = plt.subplots()\n ax.set_title('fp_Num')\n ax.hist(x, n_bins)\n len([i for i in x if i > 3]) # 965\n \n with open('text_fp.txt', 'w', encoding='utf8') as f:\n for i in text_fp:\n if len(i[-2]) > 3:\n f.write('\\t'.join(i)+'\\n')\n \n \n \n \n \n \n abstracts = d.data['train']['abstracts']\n dict_abs = { c.PMID:c.abstract for c in abstracts} # dict of abstract\n dict_title = { c.PMID:c.title for c in abstracts} # dict of title\n\n query = 'a nonlinear and nona'\n # query = '[xB2O3 + (1 - x)P2O5]'\n \n text = dict_abs['23261590']\n kp_temp = KeywordProcessor(case_sensitive = True)\n # kp_temp.add_keyword('aa')\n # kp_temp.add_keyword('aa bb')\n # kp_temp.add_keyword('bbaa')\n # kp_temp.add_keyword('bb') \n # kp_temp.extract_keywords('aa bb aa bb bb aa bc', span_info = True)\n \n kp_temp.extract_keywords(text, span_info = True)\n re.search(query, text)\n kps['train'].extract_keywords(text, span_info = True)\n kps['train'].extract_keywords(dict_abs['23300000'], span_info = True)\n \n\n\n# d.data['train']['annotations'][0]\n\n\n# Annotation = collections.namedtuple('Annotation', ['PMID', 'type_text', \n# 'start', 'end', 'mention', 'type_cem'])\n\ndef evalAA(annotations_target, annotations_pred):\n '''\n 给定两个annotations, 得到一个evaluation matrix, 给出TP, TN, FP, FN; Accuracy, Recall; F1\n 进阶:分类别统计:type_text? type_cem?\n 调用_evalAA\n '''\n # for \n \n \ndef _evalAA(annotations_target, annotations_pred):\n '''\n evalAA的核心实现,在evalAA中对数据进行分类记项讨论。\n '''\n set_target = set(annotations_target)\n set_pred = set(annotations_pred)\n refuse_matrix = {'tp':set_target & set_pred,\n 'tn':set_target - set_pred,\n 'fp':set_pred - set_target,\n 'fn':set()}\n tp = len(refuse_matrix['tp'])\n tn = len(refuse_matrix['tn'])\n fp = len(refuse_matrix['fp'])\n fn = len(refuse_matrix['fn'])\n print(' '*6 + 'Positive | Negative | Total')\n print('True {:8} {:8} {:8}'.format(tp, tn, tp+tn)) \n print('False {:8} {:8} {:8}'.format(fp, fn, fp+fn))\n print('Total {:8} {:8} {:8}'.format(tp+fp, tn+fn, tp+tn+fp+fn))\n return refuse_matrix\n \ndef exploreA(abstracts, annotations):\n '''\n 根据annotations,返回对应的摘要text及前后文信息,以\\t分割,便于人类检查。\n '''\n dict_abs = { c.PMID:c.abstract for c in abstracts} # dict of abstract\n dict_title = { c.PMID:c.title for c in abstracts} # dict of title\n text_return = []\n for a in annotations:\n if a.type_text == 'A':\n text = dict_abs[a.PMID]\n elif a.type_text == 'T':\n text = dict_title[a.PMID] \n text_return.append((a.PMID, a.type_text, a.start, a.end,\n text[max(0, int(a.start)-30):int(a.start)],\n text[int(a.start):int(a.end)],\n text[int(a.end):min(len(text), int(a.end)+30)]\n ))\n return text_return\n\ndef stat(d):\n '''\n 数据探索,得到一些统计上的信息:key的长度分布,Counter(key)的分布。\n 非常恶劣的长尾分布。\n\n '''\n print('==length==')\n for key1 in d.data.keys():\n for key2 in d.data[key1].keys():\n print('data.{}.{}.length: {}'.format(key1, key2, len(d.data[key1][key2])))\n\n print('==correlation==')\n cc = {} # for chemical_counter\n for key1 in d.data.keys():\n for key2 in ['annotations']:\n cc[key1] = collections.Counter([a.mention for a in d.data[key1][key2]])\n print(' '*12 + '|{:<12}|{:<12}|{:<12}'.format(*cc.keys()))\n for keya in cc.keys():\n print('{:<12}|{:<12}|{:<12}|{:<12}'.format(keya,\n *tuple(len(cc[keya].keys() & cc[keyb].keys()) for keyb in cc.keys())))\n\n print('==name length distribution==')\n # clc = {} # for chemical_length_count\n for key1 in cc.keys():\n x1 = [len(mention) for mention in cc[key1].keys()]\n x2 = [len(a.mention) for a in d.data[key1]['annotations']]\n n_bins = max(x1)\n fig, axs = plt.subplots(1, 2, sharey=True, tight_layout=True)\n axs[0].set_title(key1 + 'Key Length')\n axs[0].hist(x1, bins=n_bins)\n axs[1].hist(x2, bins=n_bins)\n \n print('==num distribution==')\n for key1 in cc.keys():\n x = [cc[key1][mention] for mention in cc[key1].keys()]\n n_bins = max(x)\n fig, ax = plt.subplots()\n ax.set_title(key1 + 'Num')\n ax.hist(x, n_bins)\n \n print('==feature==')\n dataset = 'train'\n print('for dataset = {}'.format(dataset))\n ct = cc[dataset]\n \n print('more than 50 times:',\n { key:ct[key] for key in ct.keys() if ct[key] > 50 })\n print('the number of these: ',\n len({ key:ct[key] for key in ct.keys() if ct[key] > 50 }))\n print('the mention of these: ',\n sum(ct[key] for key in ct.keys() if ct[key] > 50))\n \n print('less than 2 times:',\n collections.Counter( len(key) for key in ct.keys() if ct[key] < 2 ))\n print('the number of these: ',\n len({ key:ct[key] for key in ct.keys() if ct[key] < 2 }))\n print('the mention of these: ',\n sum([ct[key] for key in ct.keys() if ct[key] < 2]))\n \n print('Length of key longer than 50:',\n { (len(key),ct[key]) for key in ct.keys() if len(key) > 50 })\n print('the number of these: ',\n len({ key:ct[key] for key in ct.keys() if len(key) > 50 }))\n print('the mention of these: ',\n sum(ct[key] for key in ct.keys() if len(key) > 50))\n \n print('Length of key shorter than 5:',\n { (key,ct[key]) for key in ct.keys() if len(key) < 5 })\n print('the number of these: ',\n len({ key:ct[key] for key in ct.keys() if len(key) < 5 }))\n print('the mention of these: ',\n sum(ct[key] for key in ct.keys() if len(key) < 5))\n \n print('Length of key shorter than 10:')\n print('the number of these: ',\n len({ key:ct[key] for key in ct.keys() if len(key) < 10 }))\n print('the mention of these: ',\n sum(ct[key] for key in ct.keys() if len(key) < 10))\n \n \n \n # list(counter.elements())\n\n # kp_temp.add_keyword('aa')\n # kp_temp.add_keyword('aa bb')\n # kp_temp.add_keyword('bbaa')\n # kp_temp.add_keyword('bb') \n # kp_temp.extract_keywords('aa bb aa bb bb aa bc', span_info = True)\n\n# with open(os.path.join(d.path, 'training.abstracts.txt'), 'r', encoding ='utf8') as f:\n# line = f.readline() \n# i = 1\n# while line:\n# print(line)\n# print(i)\n# i -= 1\n# if i < 0:\n# break\n# # self.data[key1][key2].append(self._preData(line, key2))\n# line = f.readline()\n\n# [('Monument', 'Taj Mahal'), ('Location', 'Delhi')]\n# NOTE: replace_keywords feature won't work with this.","sub_path":"main/explore_data.py","file_name":"explore_data.py","file_ext":"py","file_size_in_byte":12065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"401933505","text":"#!/usr/bin/env python\n\"\"\"\nFinds the contents of the different blocks in a level, taking different data values (sub block types) into account.\n\"\"\"\n\nimport locale, os, sys\nimport glob\n# local module\ntry:\n\timport nbt\nexcept ImportError:\n\t# nbt not in search path. Let's see if it can be found in the parent folder\n\textrasearchpath = os.path.realpath(os.path.join(__file__,os.pardir,os.pardir))\n\tif not os.path.exists(os.path.join(extrasearchpath,'nbt')):\n\t\traise\n\tsys.path.append(extrasearchpath)\nfrom nbt.region import RegionFile\nfrom nbt.chunk import Chunk\n\ndef stats_per_chunk(chunk, block_data_totals):\n\t\"\"\"Given a chunk, increment the block types with the number of blocks found\"\"\"\n\tfor block_id, data_id in chunk.blocks.get_all_blocks_and_data():\n\t\tblock_data_totals[block_id][data_id] += 1\n\ndef bounded_stats_per_chunk(chunk, block_data_totals, start, stop):\n\t\"\"\"Given a chunk, return the number of blocks types within the specified selection\"\"\"\n\tchunk_z, chunk_x = chunk.get_coords()\n\tfor z in range(16):\n\t\tworld_z = z + chunk_z*16\n\t\tif ( (start != None and world_z < int(start[2])) or (stop != None and world_z > int(stop[2])) ):\n\t\t\t# Outside the bounding box; skip to next iteration\n\t\t\t#print(\"Z break: %d,%d,%d\" % (world_z,start[2],stop[2]))\n\t\t\tbreak\n\t\tfor x in range(16):\n\t\t\tworld_x = x + chunk_x*16\n\t\t\tif ( (start != None and world_x < int(start[0])) or (stop != None and world_x > int(stop[0])) ):\n\t\t\t\t# Outside the bounding box; skip to next iteration\n\t\t\t\t#print(\"X break: %d,%d,%d\" % (world_x,start[0],stop[0]))\n\t\t\t\tbreak\n\t\t\tfor y in range(128):\n\t\t\t\tif ( (start != None and y < int(start[1])) or (stop != None and y > int(stop[1])) ):\n\t\t\t\t\t# Outside the bounding box; skip to next iteration\n\t\t\t\t\t#print(\"Y break: %d,%d,%d\" % (y,start[1],stop[1]))\n\t\t\t\t\tbreak\n\t\t\t\t\n\t\t\t\t#print(\"Chunk: %d,%d Coord: %d,%d,%d\" % (c['x'], c['z'],x,y,z))\n\t\t\t\tblock_id,block_data = chunk.blocks.get_block_and_data(x,y,z)\n\t\t\t\tblock_data_totals[block_id][block_data] += 1\n\ndef process_region_file(filename, start, stop):\n\t\"\"\"Given a region filename, return the number of blocks of each ID in that file\"\"\"\n\tpieces = filename.split('.')\n\trx = int(pieces[1])\n\trz = int(pieces[2])\n\t\n\tblock_data_totals = [[0]*16 for i in range(256)] # up to 16 data numbers in 256 block IDs\n\t\n\t# Does the region overlap the bounding box at all?\n\tif (start != None):\n\t\tif ( (rx+1)*512-1 < int(start[0]) or (rz+1)*512-1 < int(start[2]) ):\n\t\t\treturn block_data_totals\n\telif (stop != None):\n\t\tif ( rx*512-1 > int(stop[0]) or rz*512-1 > int(stop[2]) ):\n\t\t\treturn block_data_totals\n\t\n\tfile = RegionFile(filename)\n\t\n\t# Get all chunks\n\tchunks = file.get_chunks()\n\tprint(\"Parsing %s... %d chunks\" % (os.path.basename(filename),len(chunks)))\n\tfor c in chunks:\n\t\t# Does the chunk overlap the bounding box at all?\n\t\tif (start != None):\n\t\t\tif ( (c['x']+1)*16 + rx*512 - 1 < int(start[0]) or (c['z']+1)*16 + rz*512 - 1 < int(start[2]) ):\n\t\t\t\tcontinue\n\t\telif (stop != None):\n\t\t\tif ( c['x']*16 + rx*512 - 1 > int(stop[0]) or c['z']*16 + rz*512 - 1 > int(stop[2]) ):\n\t\t\t\tcontinue\n\t\t\n\t\tchunk = Chunk(file.get_chunk(c['x'], c['z']))\n\t\tassert chunk.get_coords() == (c['x'] + rx*32, c['z'] + rz*32)\n\t\t#print(\"Parsing chunk (\"+str(c['x'])+\", \"+str(c['z'])+\")\")\n\t\t# Parse the blocks\n\n\t\t# Fast code if no start or stop coordinates are specified\n\t\t# TODO: also use this code if start/stop is specified, but the complete chunk is included\n\t\tif (start == None and stop == None):\n\t\t\tstats_per_chunk(chunk, block_data_totals)\n\t\telse:\n\t\t\t# Slow code that iterates through each coordinate\n\t\t\tbounded_stats_per_chunk(chunk, block_data_totals, start, stop)\n\t\n\treturn block_data_totals\n\n\ndef print_results(block_data_totals):\n\tlocale.setlocale(locale.LC_ALL, '')\n\t\n\t# Analyze blocks\n\tfor block_id,data in enumerate(block_data_totals):\n\t\tif sum(data) > 0:\n\t\t\tdatastr = \", \".join([locale.format_string(\"%d: %d\", (i,c), grouping=True) for (i,c) in enumerate(data) if c > 0])\n\t\t\tprint(locale.format_string(\"block id %3d: %12d (data id %s)\", (block_id,sum(data),datastr), grouping=True))\n\tblock_totals = [sum(data_totals) for data_totals in block_data_totals]\n\t\n\ttotal_blocks = sum(block_totals)\n\tsolid_blocks = total_blocks - block_totals[0]\n\tsolid_ratio = (solid_blocks+0.0)/total_blocks if (total_blocks > 0) else 0\n\tprint(locale.format_string(\"%d total blocks in region, %d are non-air (%0.4f\", (total_blocks, solid_blocks, 100.0*solid_ratio), grouping=True)+\"%)\")\n\t\n\t# Find valuable blocks\n\tprint(locale.format_string(\"Diamond Ore: %8d\", block_totals[56], grouping=True))\n\tprint(locale.format_string(\"Gold Ore: %8d\", block_totals[14], grouping=True))\n\tprint(locale.format_string(\"Redstone Ore: %8d\", block_totals[73], grouping=True))\n\tprint(locale.format_string(\"Iron Ore: %8d\", block_totals[15], grouping=True))\n\tprint(locale.format_string(\"Coal Ore: %8d\", block_totals[16], grouping=True))\n\tprint(locale.format_string(\"Lapis Lazuli Ore: %8d\", block_totals[21], grouping=True))\n\tprint(locale.format_string(\"Dungeons: %8d\", block_totals[52], grouping=True))\n\t\n\tprint(locale.format_string(\"Clay: %8d\", block_totals[82], grouping=True))\n\tprint(locale.format_string(\"Sugar Cane: %8d\", block_totals[83], grouping=True))\n\tprint(locale.format_string(\"Cacti: %8d\", block_totals[81], grouping=True))\n\tprint(locale.format_string(\"Pumpkin: %8d\", block_totals[86], grouping=True))\n\tprint(locale.format_string(\"Dandelion: %8d\", block_totals[37], grouping=True))\n\tprint(locale.format_string(\"Rose: %8d\", block_totals[38], grouping=True))\n\tprint(locale.format_string(\"Brown Mushroom: %8d\", block_totals[39], grouping=True))\n\tprint(locale.format_string(\"Red Mushroom: %8d\", block_totals[40], grouping=True))\n\tprint(locale.format_string(\"Lava Springs: %8d\", block_totals[11], grouping=True))\n\t\n\n\ndef main(world_folder, start=None, stop=None):\n\tif (not os.path.exists(world_folder)):\n\t\tprint(\"No such folder as \"+world_folder)\n\t\treturn 2 # ENOENT\n\t\n\tregions = glob.glob(os.path.join(world_folder,'region','*.mcr'))\n\t\n\tblock_data_totals = [[0]*16 for i in range(256)] # up to 16 data numbers in 256 block IDs\n\ttry:\n\t\tfor filename in regions:\n\t\t\tregion_totals = process_region_file(filename, start, stop)\n\t\t\tfor i, data in enumerate(region_totals):\n\t\t\t\tfor j, total in enumerate(data):\n\t\t\t\t\tblock_data_totals[i][j] += total\n\t\n\texcept KeyboardInterrupt:\n\t\tprint_results(block_data_totals)\n\t\treturn 75 # EX_TEMPFAIL\n\t\n\tprint_results(block_data_totals)\n\treturn 0 # EX_OK\n\n\nif __name__ == '__main__':\n\tif (len(sys.argv) == 1):\n\t\tprint(\"No world folder specified! Usage: %s [minx,miny,minz maxx,maxy,maxz]\" % sys.argv[0])\n\t\tsys.exit(64) # EX_USAGE\n\tworld_folder = sys.argv[1]\n\tif (not os.path.exists(world_folder)):\n\t\tprint(\"No such folder as \"+world_folder)\n\t\tsys.exit(72) # EX_IOERR\n\tstart,stop = None,None\n\tif (len(sys.argv) == 4):\n\t\t# A min/max corner was specified\n\t\tstart_str = sys.argv[2][1:-1] # Strip parenthesis...\n\t\tstart = tuple(start_str.split(',')) # and convert to tuple\n\t\tstop_str = sys.argv[3][1:-1] # Strip parenthesis...\n\t\tstop = tuple(stop_str.split(',')) # and convert to tuple\n\t\n\tsys.exit(main(world_folder, start, stop))\n","sub_path":"examples/block_analysis.py","file_name":"block_analysis.py","file_ext":"py","file_size_in_byte":7175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"26362806","text":"\"\"\"\r\nCHARLES TAM\r\nRANDOM WALKS\r\n\r\nClasses walk and dla\r\n\"\"\"\r\nimport numpy as np\r\nimport numba as nb\r\nfrom scipy import stats\r\nimport matplotlib.pyplot as plt\r\n\r\nclass walk:\r\n \"\"\"\r\n Random walk\r\n \"\"\"\r\n def __init__(self, start_point):\r\n \"\"\"\r\n Define variables\r\n \"\"\"\r\n self.start_point = np.asarray(start_point)\r\n self.walk_length = 1\r\n self.points = None\r\n self.dist = None\r\n\r\n def random(self, walk_length):\r\n \"\"\"\r\n Find points on a random walk of given length on a square lattice\r\n \"\"\"\r\n walk_length = int(walk_length)\r\n self.walk_length = walk_length\r\n # empty variable for points\r\n points = np.empty((walk_length, 2))\r\n # populate first column with random numbers\r\n points[:, 0] = np.random.randint(0, 4, walk_length)\r\n # map random numbers to a direction\r\n points[np.where(points[:, 0] == 0)[0]] = [-1, 0]\r\n points[np.where(points[:, 0] == 1)[0]] = [1, 0]\r\n points[np.where(points[:, 0] == 2)[0]] = [0, 1]\r\n points[np.where(points[:, 0] == 3)[0]] = [0, -1]\r\n # set start point\r\n points[0] = self.start_point\r\n # cumulatively sum points\r\n points_sum = np.cumsum(points, axis=0)\r\n self.points = points_sum\r\n return points_sum\r\n\r\n def random_loop(self, walk_length):\r\n \"\"\"\r\n Find points on a random walk of given length using a loop\r\n Should not use over random()\r\n \"\"\"\r\n self.walk_length = walk_length\r\n points = np.zeros([walk_length, 2])\r\n points[0] = self.start_point\r\n # iterate over walk length\r\n for i in range(1, walk_length):\r\n # random direction (right, down, left, up)\r\n direction = {0:np.array([1, 0]),\r\n 1:np.array([0, -1]),\r\n 2:np.array([-1, 0]),\r\n 3:np.array([0, 1])}.get(np.random.randint(0, 4))\r\n # append to list\r\n points[i] = points[i-1] + direction\r\n self.points = points\r\n return points\r\n\r\n def random_3d(self, walk_length):\r\n \"\"\"\r\n Find points on a random walk of given length on a simple cubic lattice\r\n \"\"\"\r\n walk_length = int(walk_length)\r\n # empty variable for points\r\n points = np.empty((walk_length, 3))\r\n # populate first column with random numbers\r\n points[:, 0] = np.random.randint(0, 6, walk_length)\r\n # map random numbers to a direction\r\n points[np.where(points[:, 0] == 0)[0]] = [-1, 0, 0]\r\n points[np.where(points[:, 0] == 1)[0]] = [1, 0, 0]\r\n points[np.where(points[:, 0] == 2)[0]] = [0, 1, 0]\r\n points[np.where(points[:, 0] == 3)[0]] = [0, -1, 0]\r\n points[np.where(points[:, 0] == 4)[0]] = [0, 0, 1]\r\n points[np.where(points[:, 0] == 5)[0]] = [0, 0, -1]\r\n # set start point\r\n points[0] = self.start_point\r\n # cumulatively sum points\r\n points_sum = np.cumsum(points, axis=0)\r\n return points_sum\r\n\r\n def self_avoid(self, walk_length):\r\n \"\"\"\r\n Find points on a self avoiding walk of given length on a square lattice\r\n using a loop, and terminates walk if it is trapped\r\n \"\"\"\r\n self.walk_length = walk_length\r\n # empty array for points\r\n points = [self.start_point]\r\n dir_dict = {0:[-1, 0], 1:[1, 0], 2:[0, 1], 3:[0, -1]}\r\n finished = False\r\n while finished is False:\r\n # allowed rolls\r\n ar = [0, 1, 2, 3]\r\n # delete allowed rolls if curve touches itself within one step\r\n if any(np.equal(points[:], points[-1] + np.array([-1, 0])).all(1)) is True:\r\n ar.remove(0)\r\n if any(np.equal(points[:], points[-1] + np.array([1, 0])).all(1)) is True:\r\n ar.remove(1)\r\n if any(np.equal(points[:], points[-1] + np.array([0, 1])).all(1)) is True:\r\n ar.remove(2)\r\n if any(np.equal(points[:], points[-1] + np.array([0, -1])).all(1)) is True:\r\n ar.remove(3)\r\n # terminate walk if stuck\r\n if not ar:\r\n finished = True\r\n else:\r\n # roll and map roll to dirction\r\n direction = dir_dict.get(np.random.choice(ar))\r\n # append to list of points\r\n points = np.append(points, [points[-1] + direction], axis=0)\r\n #terminate loop if desired walk length is reached\r\n finished = bool(len(points) == walk_length)\r\n self.points = points\r\n return points\r\n\r\n def saw_min(self, min_length):\r\n \"\"\"\r\n Find a self avoiding walk with minimum length, and number of attempts\r\n to do so\r\n \"\"\"\r\n length = False\r\n attempts = 0\r\n while length is False:\r\n saw = self.self_avoid(min_length + 1)\r\n attempts += 1\r\n if len(saw) == min_length:\r\n length = True\r\n return saw, attempts\r\n\r\n def distance(self, filename=None):\r\n \"\"\"\r\n Find step difference and distance between two points of all points\r\n in a random walk, using matrices that contain all combination of points\r\n \"\"\"\r\n # arrays of points\r\n a = np.empty((self.walk_length, self.walk_length, 2))\r\n a[:] = self.points\r\n b = np.transpose(a, (1, 0, 2))\r\n # step difference\r\n step = np.sum(np.abs(a - b), axis=2).flatten()\r\n # distance\r\n dist = np.sqrt(np.sum((a - b)**2, axis=2)).flatten()\r\n self.dist = np.sort([step, dist])\r\n # option to save file\r\n if filename is not None:\r\n data = np.vstack(([\"steps\", \"distance\"], np.transpose(self.dist)))\r\n np.savetxt(filename, data, delimiter=\",\", fmt=\"%s\")\r\n return self.dist\r\n\r\n def msd(self):\r\n \"\"\"\r\n Find mean squared displacement of points on a walk\r\n \"\"\"\r\n return np.sum(np.sum((self.start_point - self.points)**2))/self.walk_length\r\n\r\nclass dla:\r\n \"\"\"\r\n Diffusion limited aggregate\r\n \"\"\"\r\n def __init__(self, agg_start, prob):\r\n \"\"\"\r\n Define intial variables\r\n \"\"\"\r\n self.agg_start = agg_start\r\n self.points = np.asarray([agg_start])\r\n self.prob = prob\r\n\r\n def target(self, it, start, bounds):\r\n \"\"\"\r\n Random walk which terminates if reached a desired target, or if it\r\n leaves the radius of its initial position\r\n \"\"\"\r\n agg = self.points[:it]\r\n # aggregate expanded by 1 in each direction\r\n agg_ex = np.unique(np.vstack((agg + [1, 0], agg + [-1, 0],\r\n agg + [0, 1], agg + [0, -1])), axis=0)\r\n # inital position\r\n dir_dict = {0:[1, 0], 1:[0, -1], 2:[-1, 0], 3:[0, 1]}\r\n pos = start\r\n on_target = False\r\n while on_target is False:\r\n # random direction\r\n direct = np.random.randint(0, 4)\r\n pos = pos + dir_dict.get(direct)\r\n dist = np.sqrt(np.sum((pos - self.agg_start)**2))\r\n # is leaving boundary\r\n if dist > bounds[1]:\r\n # restart walk\r\n pos = start\r\n on_target = False\r\n # is leaving boundary\r\n elif dist < bounds[0]:\r\n # is point touching aggegate\r\n if any(np.equal(pos, agg_ex).all(1)):\r\n # sticking probability\r\n on_target = bool(np.random.choice([True, False],\r\n p=[self.prob, 1 - self.prob]))\r\n else:\r\n on_target = False\r\n else:\r\n on_target = False\r\n return pos\r\n\r\n def spawn(self, points, d_spawn, d_bound):\r\n \"\"\"\r\n Create start points scattered randomly on a circumference of a circle\r\n with a given radius, and call target() to get position of stuck particle\r\n \"\"\"\r\n agg = np.empty((points, 2), np.int32)\r\n agg[0] = self.agg_start\r\n r_max = 0\r\n # offset for inner radius of annulus\r\n d_offset = 2\r\n for i in range(1, points):\r\n # random point on circle\r\n t = 2*np.pi*np.random.random()\r\n a = r_max + d_spawn\r\n start = np.array([a*np.cos(t), a*np.sin(t)], dtype=np.int32)\r\n # get new particle position\r\n bounds = (r_max + d_offset, a + d_bound)\r\n agg[i] = self.target(i, start, bounds)\r\n # update r_max\r\n r_agg = np.sqrt(np.sum(agg[i]**2))\r\n if r_agg > r_max:\r\n r_max = r_agg\r\n self.points = agg\r\n return agg\r\n\r\n def spawn_nb(points, d_spawn, d_bound=0, p_stick=1):\r\n \"\"\"\r\n Wrapper function to call Numba functions to create aggregate\r\n \"\"\"\r\n return _spawn(points, d_spawn, d_bound, p_stick)\r\n\r\n@nb.jit(nopython=True)\r\ndef _get_dir(x):\r\n \"\"\"\r\n Map numbers 0 to 3 to a direction\r\n \"\"\"\r\n if x == 0:\r\n y = [1, 0]\r\n if x == 1:\r\n y = [0, -1]\r\n if x == 2:\r\n y = [0, 1]\r\n if x == 3:\r\n y = [-1, 0]\r\n return np.array(y, dtype=np.int32)\r\n\r\n@nb.jit(nopython=True)\r\ndef _target(start, agg, bounds, p_stick):\r\n \"\"\"\r\n Random walk which terminates if reached a desired target, or if it\r\n leaves the set boundary\r\n \"\"\"\r\n # inital position\r\n pos = start\r\n on_target = False\r\n while on_target is False:\r\n # random direction\r\n direct = _get_dir(np.random.randint(0, 4))\r\n pos = pos + direct\r\n pos_abs = np.sqrt(np.sum(pos**2))\r\n # is point ouside annulus\r\n if pos_abs > bounds[1]:\r\n # restart walk\r\n pos = start\r\n on_target = False\r\n # is point inside annulus\r\n elif pos_abs < bounds[0]:\r\n # surrounding points\r\n sur = np.vstack((pos + direct, pos + direct[::-1], pos - direct[::-1]))\r\n # are surrounding points of particle touching aggregate\r\n if np.any((agg[:, 0] == sur[0, 0]) & (agg[:, 1] == sur[0, 1])) or \\\r\n np.any((agg[:, 0] == sur[1, 0]) & (agg[:, 1] == sur[1, 1])) or \\\r\n np.any((agg[:, 0] == sur[2, 0]) & (agg[:, 1] == sur[2, 1])):\r\n # sticking probability\r\n if p_stick == 1:\r\n on_target = True\r\n elif np.random.random() < p_stick:\r\n on_target = True\r\n else:\r\n on_target = False\r\n else:\r\n on_target = False\r\n else:\r\n on_target = False\r\n return pos\r\n\r\n@nb.jit(nopython=True)\r\ndef _spawn(points, d_spawn, d_bound=0, p_stick=1):\r\n \"\"\"\r\n Create start points scattered randomly on a circumference of a circle\r\n with a given radius, and call target() to get position of stuck particle\r\n \"\"\"\r\n # define initial variables\r\n agg = np.empty((points, 2), np.int32)\r\n agg[0] = [0, 0]\r\n r_max = 0\r\n # offset for inner radius of annulus\r\n d_offset = 2\r\n for i in range(1, points):\r\n # random point on circle\r\n t = 2*np.pi*np.random.random()\r\n a = r_max + d_spawn\r\n start = np.array([a*np.cos(t), a*np.sin(t)], dtype=np.int32)\r\n # get new particle position\r\n bounds = (r_max + d_offset, a + d_bound)\r\n agg[i] = _target(start, agg[:i], bounds, p_stick)\r\n # update r_max\r\n r_agg = np.sqrt(np.sum(agg[i]**2))\r\n if r_agg > r_max:\r\n r_max = r_agg\r\n return agg\r\n\r\ndef gyration(seed, points, mass=1):\r\n \"\"\"\r\n Find the radius of gyration of the DLA. Assumes the mass of each particle\r\n is the same, with default value of 1.\r\n \"\"\"\r\n # convert inputs to numpy arrays\r\n seed = np.asarray(seed)\r\n points = np.asarray(points)\r\n # get total mass\r\n total_mass = len(points)*mass\r\n # get distances of particles\r\n distance = np.sum(2*(seed - points)**2)\r\n r_max = np.amax(np.sqrt(np.sum(points**2, axis=1)))\r\n return np.sqrt(distance/total_mass), r_max\r\n\r\ndef box(points):\r\n \"\"\"\r\n Find box counting dimension of fractal\r\n \"\"\"\r\n data = convert_image(points)\r\n # get shape of data\r\n shape = np.asarray(data.shape)\r\n # get ceiling of exponent of data in base 2\r\n exp = np.ceil(np.log(shape)/np.log(2)).astype(int)\r\n # pad data with zeros with size equal to 2^exp\r\n zero_pad = np.zeros(2**exp)\r\n zero_pad[:data.shape[0], :data.shape[1]] = data\r\n # create a range of box sizes\r\n box_size = np.logspace(min(exp), 0, num=min(exp)+1, base=2, dtype=\"int32\")\r\n n = []\r\n for i in box_size:\r\n # split data into i by i boxes\r\n boxes = zero_pad.reshape(2**exp[0]//i, i, -1, i).swapaxes(1, 2).reshape(-1, i, i)\r\n # count number of non-zero boxes\r\n n = np.append(n, sum(np.any(boxes != 0, axis=2).all(1)))\r\n # get rid of zeros\r\n idx_nzero = np.where(n != 0)\r\n n = n[idx_nzero].astype(\"int32\")\r\n box_size = box_size[idx_nzero]\r\n return n, box_size\r\n\r\ndef convert_image(data):\r\n \"\"\"\r\n Convert list of points to matrix of zeros with ones at corresponding points\r\n \"\"\"\r\n # extent of data\r\n x_extent = int(np.abs(max(data[:, 0]) - min(data[:, 0])))\r\n y_extent = int(np.abs(max(data[:, 1]) - min(data[:, 1])))\r\n image = np.zeros((y_extent + 1, x_extent + 1))\r\n # shift data\r\n shift = [min(data[:, 0]), min(data[:, 1])]\r\n data_s = data - shift\r\n # transform y coordinate to matrix index j\r\n data_s[:, 1] = y_extent - data_s[:, 1]\r\n data_s = data_s.astype(int)\r\n # set matrix elements to 1 on a point\r\n image[data_s[:, 1], data_s[:, 0]] = 1\r\n return image\r\n\r\n# plotting functions\r\ndef plot_walk(data, title=None, filename=None):\r\n \"\"\"\r\n Plot random walk\r\n \"\"\"\r\n fig, ax = plt.subplots(figsize=(8, 6))\r\n ax.plot(data[:, 0], data[:, 1], \"k-\")\r\n ax.set(xlabel=\"x\", ylabel=\"y\", title=title)\r\n ax.set_aspect(\"equal\", \"box\")\r\n # option to save file\r\n if filename is not None:\r\n plt.savefig(filename, dpi=400, bbox_inches=\"tight\")\r\n plt.show()\r\n return ax\r\n\r\ndef plot_3d(data, filename=None):\r\n \"\"\"\r\n Plot 3D random walk\r\n \"\"\"\r\n fig = plt.figure(figsize=(8, 6))\r\n ax = fig.gca(projection=\"3d\")\r\n ax.plot(data[:, 0], data[:, 1], data[:, 2], \"k,\")\r\n ax.set(xlabel=\"x\", ylabel=\"y\", zlabel=\"z\",\r\n title=\"Random walk, length = %d\" %len(data))\r\n ax.set_aspect(\"equal\", \"box\")\r\n if filename is not None:\r\n plt.savefig(fname=filename, dpi=400, bbox_inches=\"tight\")\r\n plt.show()\r\n return ax\r\n\r\ndef plot_hist(data, length, filename=None):\r\n \"\"\"\r\n Get stats, plot distance data from random walk and fit to pdfs\r\n \"\"\"\r\n # remove zero values\r\n print(\"Fitting curves... \", end=\"\", flush=True)\r\n idx_zero = np.where(data != 0)\r\n data = data[idx_zero]\r\n # get stats\r\n mean = np.mean(data)\r\n var = np.var(data)\r\n # histogram plot\r\n fig, ax = plt.subplots(figsize=(8, 6))\r\n bins = np.histogram_bin_edges(data, int(np.sqrt(len(np.unique(data)))))\r\n x = np.linspace(0, max(data), 1000)\r\n ax.hist(data, bins=bins, density=True, edgecolor=\"white\", linewidth=1)\r\n\r\n # fit to various pdfs\r\n norm1, norm2 = stats.norm.fit(data)\r\n ray1, ray2 = stats.rayleigh.fit(data)\r\n lnorm1, lnorm2, lnorm3 = stats.lognorm.fit(data)\r\n gamma1, gamma2, gamma3 = stats.gamma.fit(data)\r\n\r\n # chi squared test\r\n chi_n = stats.chisquare(stats.norm.pdf(bins, norm1, norm2), bins)\r\n chi_r = stats.chisquare(stats.rayleigh.pdf(bins, ray1, ray2), bins)\r\n chi_l = stats.chisquare(stats.lognorm.pdf(bins, lnorm1, lnorm2, lnorm3), bins)\r\n chi_g = stats.chisquare(stats.gamma.pdf(bins, gamma1, gamma2, gamma3), bins)\r\n print(\"Done\")\r\n\r\n # plot pdfs\r\n ax.plot(x, stats.norm.pdf(x, norm1, norm2), \"r\",\r\n label=\"Normal, \\n $\\chi^2$ = %5.2f\" % chi_n[0])\r\n ax.plot(x, stats.rayleigh.pdf(x, ray1, ray2), \"g\",\r\n label=\"Rayleigh, \\n $\\chi^2$ = %5.2f\" % chi_r[0])\r\n ax.plot(x, stats.lognorm.pdf(x, lnorm1, lnorm2, lnorm3), \"b\",\r\n label=\"Log Normal, \\n $\\chi^2$ = %5.2f\" % chi_l[0])\r\n ax.plot(x, stats.gamma.pdf(x, gamma1, gamma2, gamma3), \"k\",\r\n label=\"Gamma, \\n $\\chi^2$ = %5.2f\" % chi_g[0])\r\n ax.set(xlabel=\"Distance\", ylabel=\"Probability\",\r\n title=\"Distances between points on random walk, length = %d \\n $\\mu=$%5.3f, $\\sigma^2=$%5.3f\"\r\n % (length, mean, var))\r\n ax.legend()\r\n # option to save file\r\n if filename is not None:\r\n plt.savefig(filename, dpi=100, bbox_inches=\"tight\")\r\n plt.show()\r\n # print parameters\r\n print(\"mean = \", mean)\r\n print(\"variance = \", var)\r\n print(\"normal chi squared\", chi_n[0])\r\n print(\"Rayleigh chi squared\", chi_r[0])\r\n print(\"log normal chi squared\", chi_l[0])\r\n print(\"gamma chi squared\", chi_g[0])\r\n return ax, mean, var\r\n\r\ndef plot_dla(data, prob, filename=None):\r\n \"\"\"\r\n Plot diffusion limited aggregate with imshow()\r\n \"\"\"\r\n images = convert_image(data)\r\n # plot dla\r\n fig, ax = plt.subplots(figsize=(8, 6))\r\n extent = (min(data[:, 0]), max(data[:, 0]), min(data[:, 1]), max(data[:, 1]))\r\n ax.imshow(images, cmap=\"binary\", extent=extent)\r\n ax.set(xlabel=\"x\", ylabel=\"y\",\r\n title=r\"DLA for %d particles, $P_{stick}$ = %5.2f\" % (len(data), prob))\r\n # option to save file\r\n if filename is not None:\r\n plt.savefig(fname=filename, dpi=100, bbox_inches=\"tight\")\r\n plt.show()\r\n return ax\r\n\r\ndef main():\r\n \"\"\"\r\n main\r\n \"\"\"\r\n print(\"please run one of the test scripts\")\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"rw.py","file_name":"rw.py","file_ext":"py","file_size_in_byte":17791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"320238402","text":"\nimport os, sys\nimport shutil\nimport rosbag\nimport rospy\n\n\nimport cv2 as cv\nimport numpy as np\n# import time as timer\n\n\nfrom tqdm import tqdm\nfrom pathlib import Path\nfrom argparse import ArgumentParser\n\n# path: /media/pytorch-superpoint/datasets/draw_lines/images/training/0010/0010.bag\n# version: 2.0\n# duration: 0.0s\n# start: Jan 01 1970 00:00:00.00 (0.00)\n# end: Jan 01 1970 00:00:00.01 (0.01)\n# size: 122.3 KB\n# messages: 12\n# compression: none [1/1 chunks]\n# types: dvs_msgs/EventArray [5e8beee5a6c107e504c2e78903c224b8]\n# sensor_msgs/CameraInfo [c9a58c1b0b154e0e6da7578cb991d214]\n# sensor_msgs/Image [060021388200f6f0f447d0fcd9c64743]\n# topics: /cam0/camera_info 1 msg : sensor_msgs/CameraInfo\n# /cam0/events 10 msgs @ 1.2 kHz : dvs_msgs/EventArray \n# /cam0/image_raw 1 msg : sensor_msgs/Image\n\n\n\n# topics = bag.get_type_and_topic_info()[1].keys()\n# types = []\n\n# for i in range(0,len(bag.get_type_and_topic_info()[1].values())):\n# types.append(bag.get_type_and_topic_info()[1].values()[i][0])\n# print(types)\n\ndataset = [\"draw_lines\", \"draw_polygon\", \"draw_multiple_polygons\", \"draw_ellipses\", \"draw_star\", \"draw_checkerboard\", \"draw_stripes\", \"draw_cube\"]\n\n\n\n\ndef read_bag(H, W, iteration, frames):\n\n for d in dataset:\n\n idx = 0\n\n bag = rosbag.Bag(f\"/media/gen/data/{d}/{d}.bag\", 'r')\n evt_path = Path(f\"/media/gen/data/{d}/events\")\n pnt_path = Path(f\"/media/gen/data/{d}/points\")\n chk_path = Path(f\"/media/gen/data/{d}/events_check\")\n\n evt_path.mkdir(parents=True, exist_ok=True)\n pnt_path.mkdir(parents=True, exist_ok=True)\n chk_path.mkdir(parents=True, exist_ok=True)\n\n for i, (topic, msg, time) in enumerate(tqdm(bag.read_messages(topics=['/cam0/events']), desc=d, total=iteration*frames)):\n\n img = np.zeros((H, W, 3))\n\n\n for j, e in enumerate(msg.events):\n img[e.y, e.x, e.polarity * 2] = 255\n\n\n if (i + 1) % frames != 0:\n\n shutil.move(\"/media/gen/data/{}/raw_points/pnt_{:05d}.npy\".format(d, i), \n \"/media/gen/data/{}/points/pnt_{:05d}.npy\".format(d, idx))\n\n cv.imwrite(\"/media/gen/data/{}/events/{:05d}.png\".format(d, idx), img)\n \n\n if idx % 53 == 0:\n pts = np.load(\"/media/gen/data/{}/points/pnt_{:05d}.npy\".format(d, idx))\n for pt in pts:\n cv.circle(img, (int(pt[0]), int(pt[1])), 3, [0, 255, 0], -1)\n chk_ = str(Path(chk_path, \"chk_{:05d}.png\".format(idx)))\n cv.imwrite(chk_, img)\n\n\n idx += 1\n bag.close()\n\n\n\n\n\nif __name__ == \"__main__\":\n \n img_size = (160, 120)\n iteration = 550\n frames = 20\n\n\n\n parser = ArgumentParser()\n parser.add_argument(\"-H\", \"--height\", dest=\"height\",\n help=\"Original Height of a generated image\")\n parser.add_argument(\"-W\", \"--width\", dest=\"width\",\n help=\"Original Width of a generated image\")\n parser.add_argument(\"-i\", \"--iteration\", dest=\"iteration\",\n help=\"How many iterations for each shape batch\")\n parser.add_argument(\"-f\", \"--frames\", dest=\"frames\",\n help=\"Frames per batch\")\n args = parser.parse_args()\n\n\n\n H, W = int(args.height), int(args.width)\n iteration = int(args.iteration)\n frames = int(args.frames)\n\n\n\n print(\"======================================\")\n print(\"Compose Events Data\")\n print(\"======================================\")\n print(\"Original image size: \", H, W)\n print(\"Iteration: \", iteration)\n print(\"Frames: \", frames)\n print(\"Total images: \", frames*iteration)\n print(\"======================================\")\n\n\n\n read_bag(H, W, iteration, frames)\n \n\n","sub_path":"generate_data/bag2img.py","file_name":"bag2img.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"5368460","text":"from marshmallow_sqlalchemy import field_for\nfrom marshmallow import (\n fields,\n validates\n)\n\nfrom dataservice.extensions import ma\nfrom dataservice.api.biospecimen.models import Biospecimen\nfrom dataservice.api.common.schemas import BaseSchema\nfrom dataservice.api.common.validation import validate_age\nfrom dataservice.api.common.custom_fields import DateOrDatetime\nfrom dataservice.api.common.validation import (\n validate_positive_number,\n enum_validation_generator,\n validate_kf_id\n)\n\nANALYTE_TYPE_ENUM = {\"DNA\", \"RNA\", \"Other\", \"Virtual\"}\nSAMPLE_PROCUREMENT_ENUM = {\"Autopsy\", \"Biopsy\", \"Other\"}\n\n\nclass BiospecimenSchema(BaseSchema):\n participant_id = field_for(Biospecimen, 'participant_id', required=True,\n load_only=True)\n\n sequencing_center_id = field_for(Biospecimen, 'sequencing_center_id',\n required=True, load_only=True)\n\n age_at_event_days = field_for(Biospecimen, 'age_at_event_days',\n validate=validate_age)\n concentration_mg_per_ml = field_for(Biospecimen, 'concentration_mg_per_ml',\n validate=validate_positive_number)\n volume_ul = field_for(Biospecimen, 'volume_ul',\n validate=validate_positive_number)\n\n shipment_date = field_for(Biospecimen, 'shipment_date',\n field_class=DateOrDatetime)\n analyte_type = field_for(Biospecimen, 'analyte_type',\n validate=enum_validation_generator(\n ANALYTE_TYPE_ENUM))\n method_of_sample_procurement = field_for(\n Biospecimen,\n 'method_of_sample_procurement',\n validate=enum_validation_generator(SAMPLE_PROCUREMENT_ENUM))\n\n class Meta(BaseSchema.Meta):\n model = Biospecimen\n resource_url = 'api.biospecimens'\n collection_url = 'api.biospecimens_list'\n exclude = (BaseSchema.Meta.exclude +\n ('participant', 'sequencing_center') +\n ('genomic_files', 'biospecimen_genomic_files'))\n\n _links = ma.Hyperlinks({\n 'self': ma.URLFor(Meta.resource_url, kf_id=''),\n 'collection': ma.URLFor(Meta.collection_url),\n 'participant': ma.URLFor('api.participants', kf_id=''),\n 'sequencing_center': ma.URLFor('api.sequencing_centers',\n kf_id=''),\n 'biospecimen_genomic_files': ma.URLFor(\n 'api.biospecimen_genomic_files_list', biospecimen_id=''),\n 'biospecimen_diagnoses': ma.URLFor(\n 'api.biospecimen_diagnoses_list', biospecimen_id=''),\n 'diagnoses': ma.URLFor('api.diagnoses_list',\n biospecimen_id='')\n })\n\n\nclass BiospecimenFilterSchema(BiospecimenSchema):\n\n diagnosis_id = fields.Str()\n\n @validates('diagnosis_id')\n def valid_diagnosis_id(self, value):\n validate_kf_id('DG', value)\n","sub_path":"dataservice/api/biospecimen/schemas.py","file_name":"schemas.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"312236169","text":"import discord\nfrom discord.ext import commands\n\n\nclass HelpCommand(commands.HelpCommand):\n def __init__(self):\n super().__init__(command_attrs={\n 'help': 'Returns help about a command, or a category of commands.',\n 'cooldown': commands.Cooldown(1, 3.0, commands.BucketType.member),\n })\n\n async def send_bot_help(self, mapping):\n ctx = self.context\n bot = ctx.bot\n\n embed = discord.Embed(color=discord.Color.blurple())\n embed.add_field(name=\"Usage\", value=f\"Do `{self.clean_prefix}help ` to get help on a command or category\", inline=False)\n\n out = \"\"\n # bot.cogs returns a dict mapping of name:cog\n for cog_name in bot.cogs:\n if cog_name != \"Control\": out += cog_name.capitalize() + \"\\n\"\n\n embed.add_field(name=\"Categories\", value=out, inline=False)\n embed.add_field(name=\"Contact us\", value=\"[Join our support server](https://discord.gg/RdPaXZq)\", inline=False)\n await ctx.send(embed=embed)\n\n async def send_cog_help(self, cog):\n ctx = self.context\n bot = ctx.bot\n\n embed = discord.Embed(title=f\"Module **{cog.qualified_name}**\", description=cog.description, color=discord.Color.blue())\n commands_in_cog = \"\"\n for command in cog.get_commands():\n commands_in_cog += command.name + \"\\n\"\n embed.add_field(name=\"**Commands**\", value=commands_in_cog, inline=False)\n embed.set_footer(text=f\"Do {self.clean_prefix}help to get help on a specific command.\")\n await ctx.send(embed=embed)\n\n async def send_command_help(self, command):\n ctx = self.context\n\n embed = discord.Embed(title=f\"Help - {command.name}\", description=f\"{command.help} \\n **Usage** `{self.get_command_signature(command)}`\", color=discord.Color.blue())\n\n await ctx.send(embed=embed)\n\n def get_command_signature(self, command):\n if not command.signature and not command.parent: # checking if it has no args and isn't a subcommand\n return f'`{self.clean_prefix}{command.name}`'\n if command.signature and not command.parent: # checking if it has args and isn't a subcommand\n return f'`{self.clean_prefix}{command.name} {command.signature}`'\n if not command.signature and command.parent: # checking if it has no args and is a subcommand\n return f'`{command.name}`'\n else: # else assume it has args a signature and is a subcommand\n return f'`{command.name} {command.signature}`'\n\n @staticmethod\n def get_clean_usage_signature(command):\n \"\"\"Used in error handler to get clean usage string for commands. Similar to get_command_signature, but without the prefixs\"\"\"\n if not command.signature and not command.parent: # checking if it has no args and isn't a subcommand\n return f'`{command.name}`'\n if command.signature and not command.parent: # checking if it has args and isn't a subcommand\n return f'`{command.name} {command.signature}`'\n if not command.signature and command.parent: # checking if it has no args and is a subcommand\n return f'`{command.name}`'\n else: # else assume it has args a signature and is a subcommand\n return f'`{command.name} {command.signature}`'\n","sub_path":"utils/help_class.py","file_name":"help_class.py","file_ext":"py","file_size_in_byte":3343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"293682163","text":"import sys\n\nfreq = []\n\nfor line in sys.stdin.readlines():\n\tline = line.strip('\\n')\n\t(f, w) = line.split('\\t')\n\tfreq.append((int(f), w))\n\nfreq.sort(reverse=True)\n\n\nrank = 1\nmin = freq[0][0]\nranks = []\nfor i in range(0, len(freq)): \n\tif freq[i][0] < min: \n\t\trank = rank + 1\n\t\tmin = freq[i][0]\n\tranks.append((rank, freq[i][0], freq[i][1]))\n\nprint(ranks)\n","sub_path":"2018-komp-ling/practicals/transliteration-response/ranking/rank.py","file_name":"rank.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"461549378","text":"import urllib.request\nimport simplejson\nimport time\nimport pickle\nimport os\n\ndef save_obj(obj, name ):\n with open( name + \".pkl\" , 'wb') as f:\n pickle.dump(obj, f, protocol=2)\n\nfetcher = urllib.request.build_opener()\n\n\nYOUR_API_KEY = \"AIzaSyDhMnNNzDLVRBKEgoCwsKcRzcYMcq4rZaQ\"\nCX = \"006884488164293224233:lblrjk65gqe\"\nNUM = 10 # 10 results per request\n# 100 calls per day free (top 100 images are only accessible)\n\nsearchTerms = [i.strip() for i in open(\"Kanto.txt\").readlines()]\nnumberOfImages = 10\n\nurls = []\nfor searchTerm in searchTerms:\n\tsT = searchTerm.lower()\n\tos.makedirs(\"./Im/\" + sT.lower())\n\tsearchTerm = urllib.request.quote(searchTerm.lower()) # for non-ascii encoding of search term\n\tcount = 0\n\tfor startIndex in range(1, numberOfImages, NUM):\n\t\twhile True:\n\t\t\tsearchUrl = \"https://www.googleapis.com/customsearch/v1?q=\" + searchTerm + \"&cx=\" + CX + \"&num=\" + str(NUM) + \"&start=\" + str(startIndex) + \"&key=\" + YOUR_API_KEY+ \"&alt=json&searchType=image\"\n\t\t\tprint(searchUrl)\n\t\t\t# searchUrl = \"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=\" + searchTerm + \"&start=\" + str(startIndex) + \"&userip=192.168.1.2\"\n\t\t\tf = fetcher.open(searchUrl)\n\t\t\tdeserialized_output = simplejson.load(f)\n\t\t\t# print(deserialized_output)\n\t\t\t# break\n\t\t\tif None == deserialized_output[\"items\"]:\n\t\t\t print(\"Retrying \" + str(startIndex))\n\n\t\t\t # Sleep for two second to prevent IP blocking from Google\n\t\t\t time.sleep(3)\n\n\t\t\t continue\n\n\t\t\telse:\n\t\t\t for temp in deserialized_output[\"items\"]:\n\n\t\t\t urls.append(temp[\"link\"])\n\t\t\t u = temp[\"link\"]\n\t\t\t try:\n\t\t\t image = urllib.request.urlopen(u.strip()).read()\n\t\t\t print(u)\n\t\t\t f = open(\"./Im/\" + sT + \"/\" + str(count) + \".\" + u.split(\".\")[len(u.split(\".\"))-1].split(\"?\")[0].split(\"/\")[0],'wb')\n\t\t\t f.write(image)\n\t\t\t f.close()\n\t\t\t except Exception as e:\n\t\t\t print(\"Failed !\")\n\t\t\t print(e)\n\t\t\t continue\n\n\t\t\t count += 1\n\t\t\t save_obj(urls,\"./Im/urls\")\n\n\t\t\t # Sleep for two second to prevent IP blocking from Google\n\t\t\t time.sleep(3)\n\n\t\t\t print(startIndex)\n\t\t\t break\n","sub_path":"other/Data Crawling and Collection/Demo/GoogleImagesDownload.py","file_name":"GoogleImagesDownload.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"170017012","text":"\"\"\"\n907. Sum of Subarray Minimums (Medium)\n\nGiven an array of integers A, find the sum of min(B), where B ranges over \nevery (contiguous) subarray of A.\n\nSince the answer may be large, return the answer modulo 10^9 + 7.\n\nExample 1:\n\nInput: [3,1,2,4]\nOutput: 17\nExplanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], \n[3,1,2], [1,2,4], [3,1,2,4]. \nMinimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17.\n\nNote:\n\n1 <= A.length <= 30000\n1 <= A[i] <= 30000\n\"\"\"\n\nclass Solution(object):\n def sumSubarrayMins(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n MOD = 10 ** 9 + 7\n stack = []\n curr = 0\n res = 0\n for i, item in enumerate(A):\n tmp_cnt = 1\n new = curr + item\n while stack and stack[-1][0] >= item:\n tmp, old_cnt = stack.pop()\n new -= (tmp - item) * old_cnt\n tmp_cnt += old_cnt\n stack.append((item, tmp_cnt))\n res = (res + new) % MOD\n curr = new % MOD\n return res\n\n\nif __name__ == \"__main__\":\n a = Solution()\n print(a.sumSubarrayMins([3,1,2,4]))\n print(a.sumSubarrayMins([81, 55, 2]))\n","sub_path":"python/leetcode/array/stack/907_sum_of_subarray_min.py","file_name":"907_sum_of_subarray_min.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"310524677","text":"proj_type = input().lower()\nrows = int(input())\ncolumns = int(input())\n\nresult = 0\n\npremiere_price = 12\nnormal_price = 7.5\ndiscount_price = 5\nhall_places = rows * columns\n\nif proj_type == \"premiere\":\n result = hall_places * premiere_price\nelif proj_type == \"normal\":\n result = hall_places * normal_price\nelif proj_type == \"discount\":\n result = hall_places * discount_price\n\nprint(f\"{result:.2f}\")\n","sub_path":"nested_ifs/lab_cinema.py","file_name":"lab_cinema.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"481195436","text":"#!/usr/bin/env python\n\n## \n # ###################################################################\n # FiPy - Python-based finite volume PDE solver\n # \n # FILE: \"input.py\"\n # created: 11/17/03 {10:29:10 AM} \n # last update: 1/12/06 {8:40:51 PM} { 1:23:41 PM}\n # Author: Jonathan Guyer \n # Author: Daniel Wheeler \n # Author: James Warren \n # mail: NIST\n # www: http://www.ctcms.nist.gov/fipy/\n # \n # ========================================================================\n # This software was developed at the National Institute of Standards\n # and Technology by employees of the Federal Government in the course\n # of their official duties. Pursuant to title 17 Section 105 of the\n # United States Code this software is not subject to copyright\n # protection and is in the public domain. FiPy is an experimental\n # system. NIST assumes no responsibility whatsoever for its use by\n # other parties, and makes no guarantees, expressed or implied, about\n # its quality, reliability, or any other characteristic. We would\n # appreciate acknowledgement if the software is used.\n # \n # This software can be redistributed and/or modified freely\n # provided that any derivative works bear some notice that they are\n # derived from it, and any modified versions bear some notice that\n # they have been modified.\n # ========================================================================\n # \n # Description: \n # \n # History\n # \n # modified by rev reason\n # ---------- --- --- -----------\n # 2003-11-17 JEG 1.0 original\n # ###################################################################\n ##\n\nr\"\"\"\n\nHere we solve the level set equation in two dimensions for a square. The equation is\ngiven by:\n\n.. raw:: latex\n\n \\begin{alignat*}{2}\n | \\nabla \\phi | &= 1 &\\qquad& \\\\\n \\phi &= 0 && \\text{at} \\qquad \\begin{cases}\n\tx = \\left( L / 3, 2 L / 3 \\right) \n\t& \\text{for $L / 3 \\le y \\le 2 L / 3$} \\\\\n\ty = \\left( L / 3, 2 L / 3 \\right) \n\t& \\text{for $L / 3 \\le x \\le 2 L / 3$}\n \\end{cases}\n \\end{alignat*}\n \n\nDo the tests:\n\n >>> import fipy.tools.numerix as numerix\n >>> def evalCell(phix, phiy, dx, dy):\n ... aa = dy**2 + dx**2\n ... bb = -2 * ( phix * dy**2 + phiy * dx**2)\n ... cc = dy**2 * phix**2 + dx**2 * phiy**2 - dx**2 * dy**2\n ... sqr = numerix.sqrt(bb**2 - 4. * aa * cc)\n ... return ((-bb - sqr) / 2. / aa, (-bb + sqr) / 2. / aa)\n >>> val = evalCell(-dy / 2., -dx / 2., dx, dy)[0]\n >>> v1 = evalCell(val, -3. * dx / 2., dx, dy)[0]\n >>> v2 = evalCell(-3. * dy / 2., val, dx, dy)[0]\n >>> v3 = evalCell(v2, v1, dx, dy)[0]\n >>> v4 = dx * dy / numerix.sqrt(dx**2 + dy**2) / 2\n >>> arr = numerix.array((\n ... v3 , v2 , -3. * dy / 2. , v2 , v3,\n ... v1 , val , -dy / 2. , val , v1 ,\n ... -3. * dx / 2., -dx / 2., v4 , -dx / 2., -3. * dx / 2.,\n ... v1 , val , -dy / 2. , val , v1 ,\n ... v3 , v2 , -3. * dy / 2. , v2 , v3 ))\n >>> print var.allclose(arr)\n 1\n\n\"\"\"\n__docformat__ = 'restructuredtext'\n\nfrom fipy.meshes.grid2D import Grid2D\nfrom fipy.variables.cellVariable import CellVariable\nfrom fipy.models.levelSet.distanceFunction.distanceVariable import DistanceVariable\n\ndx = 0.5\ndy = 2.\nnx = 5\nny = 5\n\nLx = nx * dx\nLy = ny * dy\n\nmesh = Grid2D(dx = dx, dy = dy, nx = nx, ny = ny)\n\nvar = DistanceVariable(\n name = 'level set variable',\n mesh = mesh,\n value = -1,\n hasOld = 1\n )\n\nx, y = mesh.getCellCenters()[...,0], mesh.getCellCenters()[...,1]\nvar.setValue(1, where=((Lx / 3. < x) & (x < 2. * Lx / 3.)) & ((Ly / 3. < y) & (y < 2. * Ly / 3)))\n\nvar.calcDistanceFunction()\n\nif __name__ == '__main__':\n import fipy.viewers\n viewer = fipy.viewers.make(vars = var, limits = {'maxval': -5., 'minval': 5.})\n viewer.plot()\n raw_input('finished')\n","sub_path":"fipy/examples/levelSet/distanceFunction/square/input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":4038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"295698029","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\nimport pymysql\n\n\nclass MoviecrawlPipeline(object):\n def process_item(self, item, spider):\n \n conn = pymysql.connect(\n host='localhost',\n port=3306,\n user='root',\n passwd='wanglei666',\n database='cineama',\n charset='utf8'\n )\n cursor = conn.cursor()\n\n sql = 'INSERT INTO 80scine VALUES(%d, \\'%s\\', \\'%s\\', \\'%s\\')' % (int(item['iD']), item['cineName'], item['pictureLink'], item['downloadLink'])\n try:\n cursor.execute(sql)\n conn.commit()\n except Exception:\n conn.rollback()\n cursor.close()\n conn.close()\n return item\n \n","sub_path":"ScrapyProject/MovieCrawl/MovieCrawl/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"21668549","text":"def quickSort(nums):\n if len(nums)>0:\n sort(nums,0,len(nums)-1)\n return nums\n\ndef sort(nums,low,high):\n if lowtemp:\n high-=1\n nums[low]=nums[high]\n while low\", sep=\"\", end=\" \")\n\n if spec.indexed:\n print(\"[value...]\", end=\" \")\n\n if spec.cls and len(self.stack) == i + 1:\n print(\" ...\", end=\"\")\n\n print()\n\n # Output the details.\n for i, spec in enumerate(self.stack):\n summary, description = spec.doc or (None, None)\n\n if i:\n print(\"\\nCommand:\", spec.callable.__name__)\n if summary: print(wrap(summary, width))\n\n if spec.named:\n print(\"\\n\", \"CMDOPTS\" if i else \"OPTIONS\", \" may be one or more of:\", sep=\"\", end=\"\\n\\n\")\n\n strings = dict()\n abbreviation = dict(zip(spec.short.values(), spec.short.keys()))\n pretty = dict(zip(spec.trans.values(), spec.trans.keys()))\n\n for name in spec.named:\n default = spec.defaults.get(name)\n\n if spec.cast.get(name, None) is boolean:\n strings[((\"-\" + abbreviation[name] + \", \") if name in abbreviation else \"\") + \"--\" + pretty.get(name, name)] = \\\n spec.docs.get(name, \"Toggle this value.\\nDefault: %r\" % default)\n continue\n\n strings[\"-\" + abbreviation[name] + \", --\" + pretty.get(name, name) + \"=VAL\"] = \\\n spec.docs.get(name, \"Override this value.\\nDefault: %r\" % default)\n\n mlen = max([len(i) for i in strings])\n for name in sorted(strings):\n print(\" %-*s %s\" % (mlen, name, wrap(strings[name], width).replace(\"\\n\", \"\\n\" + \" \" * (mlen + 3))))\n\n if spec.cls and len(self.stack) == i + 1:\n print(\"\\n\", \"COMMAND may be one of:\", sep=\"\", end=\"\\n\\n\")\n\n cmds = dict()\n for cmd in dir(spec.target):\n if cmd[0] == '_' or not callable(getattr(spec.target, cmd)): continue\n cmds[cmd] = partitionhelp(getdoc(getattr(spec.target, cmd)) or \"Undocumented command.\")[0]\n\n mlen = max([len(i) for i in cmds])\n for name in sorted(cmds):\n print(\" %-*s %s\" % (mlen, name, wrap(cmds[name], width).replace(\"\\n\", \"\\n\" + \" \" * (mlen + 3))))\n\n print(\"\\n\", wrap(\"For help on a specific command, call the command and pass --help in CMDOPTS.\", width), sep=\"\")\n\n if description: print(\"\\n\", wrap(description, width), sep=\"\")\n\n print()\n\n raise ExitException(os.EX_USAGE, None)\n\n def version(self, value, via):\n \"\"\"Attempt to determine the owning package, version, author, and copyright information.\"\"\"\n pass\n \n @staticmethod\n def width(fallback=79):\n \"\"\"Return the width of the current terminal, or the fallback value.\"\"\"\n\n width = fallback\n\n # Determine current terminal width, if possible.\n if sys.stdout.isatty():\n try:\n # Use terminal control codes if possible.\n import fcntl, termios, struct\n width = struct.unpack(b'hh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234'))[1] - 1\n\n except:\n # Fall back on environment variables.\n try:\n width = int(os.environ['COLUMNS']) - 1\n except:\n # TODO: Fall back on curses, then ANSI.\n pass\n\n return width\n\n def expand(self, arguments, via):\n \"\"\"Expand short arguments into long ones and expand equations.\n\n Silently ignores unknown arguments to allow repeated calling for sub-commands.\n\n `arguments`:\n a list of arguments\n `via`:\n the specification we are expanding from\n\n You can override this in a subclass to perform additional transformations if you wish.\n \"\"\"\n\n result = []\n\n for arg in arguments:\n # Ensure arguments are unicode.\n # arg = arg.decode(encoding) if isinstance(arg, binary) else arg\n\n # Skip the impossibility of empty arguments.\n if not arg: continue\n\n # A double-hyphen argument signals the end of hyphenated arguments.\n if arg == '--' or '--' in result:\n result.append(arg)\n continue\n\n # Now we start looking for our hyphenated options.\n if len(arg) >= 2 and arg[0] == '-':\n if arg[1] == '-':\n # This is a long-form argument.\n name, _, value = arg.partition('=')\n\n # We append the name, then value if one exists.\n result.append(name)\n if value: result.append(value)\n\n continue\n\n # Expand short arguments into long ones.\n for char in arg[1:]:\n name = via.short.get(char, None)\n if name: result.append('--' + name)\n else: result.append('-' + char)\n\n continue\n\n # Other values we just pass along.\n result.append(arg)\n\n return result\n\n def arguments(self, arguments, via):\n \"\"\"Process the given command-line arguments and return the positional, keyword, and remaining arguments.\n\n Expects long-form arguments only, thus the output of the self.expand method.\n \"\"\"\n \n remainder = []\n arguments = arguments[::-1] # We reverse the argument list as popping is more efficient from the end.\n parsing = True\n args = []\n kwargs = {}\n\n while arguments:\n arg = arguments.pop()\n\n if arg == '--':\n # Stop processing keyword arguments.\n parsing = False\n continue\n \n if not parsing or ( arg[:2] != '--' and len(args) < via.range[1] ):\n # Positional argument.\n args.append(self.transform(\n name=via.positional[len(args)] if len(args) < len(via.positional) else None,\n value=arg,\n via=via\n ))\n continue\n\n if (arg[0] == '-' and arg[1] != '-') or \\\n (arg[:2] == '--' and (via.trans.get(arg[2:], arg[2:]) not in via.named and not via.keyed)) or \\\n (arg[:2] != '--' and len(args) == via.range[1]):\n # Unknown keyword argument or too many positional arguments, exiting early.\n remainder.append(arg)\n remainder.extend(reversed(arguments))\n break\n\n # Keyword argument.\n arg = arg[2:]\n\n if via.cast.get(arg, None) is boolean:\n kwargs[arg] = self.transform(name=arg, value=not via.defaults.get(arg, False), via=via)\n continue\n\n kwargs[arg] = self.transform(name=arg, value=arguments.pop(), via=via)\n\n return args, kwargs, remainder\n\n def transform(self, name, value, via):\n \"\"\"Typecast and optionally utilize callbacks for the given argument.\"\"\"\n\n if name is None:\n return value\n\n cast = via.cast.get(name)\n value = cast(value) if cast else value\n\n callback = via.callbacks.get(name)\n if callback:\n callback(value, via)\n\n return value\n","sub_path":"marrow/script/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":13315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"384772063","text":"from rest_framework import serializers\n\nfrom project.api.call_option.serializers import CallOptionSerializer\nfrom project.api.organisation.serializers import OrganisationSerializer\nfrom .models import Call\n\n\nclass CallGetSerializer(serializers.ModelSerializer):\n organisation = OrganisationSerializer()\n call_options = CallOptionSerializer(many=True, required=False)\n type = serializers.SerializerMethodField()\n\n class Meta:\n model = Call\n fields = ['id', 'title', 'call_picture', 'organisation', 'start_datetime', 'end_datetime',\n 'location', 'description', 'must_be_approved', 'call_options', 'type']\n read_only_fields = ['organisation', 'call_options', 'type']\n ordering = ['start_datetime']\n\n def get_type(self, call):\n return 'call'\n\n\nclass CallGetOrgFeedSerializer(serializers.ModelSerializer):\n call_options = CallOptionSerializer(many=True, required=False)\n\n class Meta:\n model = Call\n fields = ['id', 'title', 'call_picture', 'organisation', 'start_datetime', 'end_datetime',\n 'location', 'description', 'must_be_approved', 'call_options']\n read_only_fields = ['id', 'title', 'call_picture', 'organisation', 'start_datetime', 'end_datetime',\n 'location', 'description', 'must_be_approved', 'call_options']\n ordering = ['start_datetime']\n\n\nclass CallPostSerializer(serializers.ModelSerializer):\n class Meta:\n model = Call\n fields = ['title', 'call_picture', 'organisation', 'start_datetime', 'end_datetime',\n 'location', 'description', 'must_be_approved']\n read_only_fields = ['organisation']\n extra_kwargs = {\n 'call_options': {'required': True}\n }\n\n def create(self, validated_data):\n validated_data['organisation'] = self.context.get('request').user.organisation\n instance = super(CallPostSerializer, self).create(validated_data)\n call_options = self.context.get('request').data['call_options']\n for option in call_options:\n option['call'] = instance.id\n serializer = CallOptionSerializer(data=option)\n serializer.is_valid()\n serializer.create(serializer.validated_data)\n return instance\n\n def partial_update(self, instance, validated_data):\n call_options_update = validated_data.pop('call_options')\n call_options = instance.call_options\n call_options_serializer = self.fields['call_options']\n call_options_serializer.update(call_options, call_options_update)\n return super().update(instance, validated_data)\n","sub_path":"backend/project/api/call/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"341452697","text":"\"\"\"\nSign your name:Ian\n \nUpdate the code in this chapter to do the following:\nOpen a 500px by 500px window.\nChange the Ball class to a Box class.\nInstantiate two 30px by 30px boxes. One red and one blue.\nMake the blue box have a speed of 240 pixels/second\nMake the red box have a speed of 180 pixels/second\nControl the blue box with the arrow keys.\nControl the red box with the WASD keys.\nDo not let the boxes go off of the screen.\nIncorporate different sounds when either box hits the edge of the screen.\nHave two people play this TAG game at the same time.\nThe red box is always \"it\" and needs to try to catch the blue box.\nWhen you're done demonstrate to your instructor!\n\"\"\"\nimport arcade\nSW = 500\nSH = 500\nrs = 3\nbs = 4\n\n\nclass Box:\n def __init__(self, x, y, dx, dy, s, c):\n self.x = x\n self.y = y\n self.dx = dx\n self.dy = dy\n self.s = s\n self.c = c\n if self.c == arcade.color.RED:\n self.snd = arcade.load_sound(\"laser.mp3\")\n elif self.c == arcade.color.BLUE:\n self.snd = arcade.load_sound(\"explosion.mp3\")\n\n def draw_box(self):\n arcade.draw_rectangle_filled(self.x, self.y, self.s, self.s, self.c)\n\n def update_box(self):\n self.x += self.dx\n self.y += self.dy\n\n if self.x <= self.s / 2:\n self.dx = 0\n self.x = self.s / 2\n arcade.play_sound(self.snd)\n elif self.x >= SW - self.s / 2:\n self.dx = 0\n self.x = SW - self.s / 2\n arcade.play_sound(self.snd)\n elif self.y <= self.s / 2:\n self.dy = 0\n self.y = self.s / 2\n arcade.play_sound(self.snd)\n elif self.y >= SH - self.s / 2:\n self.dy = 0\n self.y = SH - self.s / 2\n arcade.play_sound(self.snd)\n\n\nclass Game(arcade.Window):\n def __init__(self, width, height, title):\n super().__init__(width, height, title)\n self.set_mouse_visible(True)\n arcade.set_background_color(arcade.color.WHITE)\n self.red_box = Box(25, 250, 0, 0, 30, arcade.color.RED)\n self.blue_box = Box(475, 250, 0, 0, 30, arcade.color.BLUE)\n\n def on_draw(self):\n arcade.start_render()\n self.red_box.draw_box()\n self.blue_box.draw_box()\n\n def on_update(self, delta_time: float):\n self.red_box.update_box()\n self.blue_box.update_box()\n\n def on_key_press(self, key, modifiers):\n if key == arcade.key.LEFT:\n self.blue_box.dx = -bs\n elif key == arcade.key.RIGHT:\n self.blue_box.dx = bs\n elif key == arcade.key.UP:\n self.blue_box.dy = bs\n elif key == arcade.key.DOWN:\n self.blue_box.dy = -bs\n elif key == arcade.key.W:\n self.red_box.dy = rs\n elif key == arcade.key.A:\n self.red_box.dx = -rs\n elif key == arcade.key.S:\n self.red_box.dy = -rs\n elif key == arcade.key.D:\n self.red_box.dx = rs\n\n def on_key_release(self, key, modifiers):\n if key == arcade.key.LEFT:\n self.blue_box.dx = 0\n elif key == arcade.key.RIGHT:\n self.blue_box.dx = 0\n elif key == arcade.key.UP:\n self.blue_box.dy = 0\n elif key == arcade.key.DOWN:\n self.blue_box.dy = 0\n elif key == arcade.key.W:\n self.red_box.dy = 0\n elif key == arcade.key.A:\n self.red_box.dx = 0\n elif key == arcade.key.S:\n self.red_box.dy = 0\n elif key == arcade.key.D:\n self.red_box.dx = 0\n\n\ndef main():\n window = Game(SW, SH, \"Game\")\n arcade.run()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"13.0_Jedi_Training.py","file_name":"13.0_Jedi_Training.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"276439629","text":"# MFR classification\n#\n# analyses HELCATS ICMECAT for predicting labels of CME MFRs\n# Author: C. Moestl, Space Research Institute IWF Graz, Austria\n# last update: May 2018\n\n\nfrom scipy import stats\nimport scipy.io\nfrom matplotlib import cm\nimport sys\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport numpy as np\nimport sunpy.time\nimport time\nimport pickle\nimport seaborn as sns\nimport pandas as pd\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nsns.set_context(\"talk\") \nsns.set_style(\"darkgrid\") \n\nplt.close('all')\n\n######## functions\n\ndef getcat(filename):\n print('reading CAT')\n cat=scipy.io.readsav(filename, verbose='true') \n print('done CAT')\n return cat \n \ndef decode_array(bytearrin):\n #for decoding the strings from the IDL .sav file to a list of python strings, not bytes \n #make list of python lists with arbitrary length\n bytearrout= ['' for x in range(len(bytearrin))]\n for i in range(0,len(bytearrin)-1):\n bytearrout[i]=bytearrin[i].decode()\n #has to be np array so to be used with numpy \"where\"\n bytearrout=np.array(bytearrout)\n return bytearrout \n \n\ndef time_to_num_cat(time_in): \n\n #for time conversion from catalogue .sav to numerical time\n #this for 1-minute data or lower time resolution\n\n #for all catalogues\n #time_in is the time in format: 2007-11-17T07:20:00 or 2007-11-17T07:20Z\n #for times help see: \n #http://docs.sunpy.org/en/latest/guide/time.html\n #http://matplotlib.org/examples/pylab_examples/date_demo2.html\n \n j=0\n #time_str=np.empty(np.size(time_in),dtype='S19')\n time_str= ['' for x in range(len(time_in))]\n #=np.chararray(np.size(time_in),itemsize=19)\n time_num=np.zeros(np.size(time_in))\n \n for i in time_in:\n\n #convert from bytes (output of scipy.readsav) to string\n time_str[j]=time_in[j][0:16].decode()+':00'\n year=int(time_str[j][0:4])\n time_str[j]\n #convert time to sunpy friendly time and to matplotlibdatetime\n #only for valid times so 9999 in year is not converted\n #pdb.set_trace()\n if year < 2100:\n \t time_num[j]=mdates.date2num(sunpy.time.parse_time(time_str[j]))\n j=j+1 \n #the date format in matplotlib is e.g. 735202.67569444\n #this is time in days since 0001-01-01 UTC, plus 1.\n \n #return time_num which is already an array and convert the list of strings to an array\n return time_num, np.array(time_str)\n\n\ndef IDL_time_to_num(time_in): \n #convert IDL time to matplotlib datetime\n time_num=np.zeros(np.size(time_in))\n for ii in np.arange(0,np.size(time_in)):\n time_num[ii]=mdates.date2num(sunpy.time.parse_time(time_in[ii])) \n return time_num \n \n\ndef gaussian(x, amp, mu, sig):\n return amp * exp(-(x-cen)**2 /wid)\n\n\ndef dynamic_pressure(density, speed):\n # make dynamic pressure from density and speed\n #assume pdyn is only due to protons\n #pdyn=np.zeros(len([density])) #in nano Pascals\n protonmass=1.6726219*1e-27 #kg\n pdyn=np.multiply(np.square(speed*1e3),density)*1e6*protonmass*1e9 #in nanoPascal\n return pdyn\n\n\n\n\n#####################################################################################\n######################## main program ###############################################\n\nplt.close('all')\nprint('MFR classify.')\n\n#-------------------------------------------------------- get cats\n\n#solar radius\nRs_in_AU=7e5/149.5e6\n\n\nfilename_icmecat='../catpy/ALLCATS/HELCATS_ICMECAT_v20_SCEQ.sav'\ni=getcat(filename_icmecat)\n\n#now this is a scipy structured array \n#access each element of the array see http://docs.scipy.org/doc/numpy/user/basics.rec.html\n#access variables\n#i.icmecat['id']\n#look at contained variables\n#print(i.icmecat.dtype)\n\n\n#get spacecraft and planet positions\npos=getcat('../catpy/DATACAT/positions_2007_2018_HEEQ_6hours.sav')\npos_time_num=time_to_num_cat(pos.time)[0]\n\n#----------------- get all parameters from ICMECAT for easier handling\n\n#id for each event\niid=i.icmecat['id']\n#need to decode all strings\niid=decode_array(iid)\n\n#observing spacecraft\nisc=i.icmecat['sc_insitu'] #string\nisc=decode_array(isc)\n\n#all times need to be converted from the IDL format to matplotlib format\nicme_start_time=i.icmecat['ICME_START_TIME']\n[icme_start_time_num,icme_start_time_str]=time_to_num_cat(icme_start_time)\n\nmo_start_time=i.icmecat['MO_START_TIME']\n[mo_start_time_num,mo_start_time_str]=time_to_num_cat(mo_start_time)\n\nmo_end_time=i.icmecat['MO_END_TIME']\n[mo_end_time_num,mo_end_time_str]=time_to_num_cat(mo_end_time)\n\n#this time exists only for Wind\nicme_end_time=i.icmecat['ICME_END_TIME']\n[icme_end_time_num,icme_end_time_str]=time_to_num_cat(icme_end_time)\n\nsc_heliodistance=i.icmecat['SC_HELIODISTANCE']\nsc_long_heeq=i.icmecat['SC_LONG_HEEQ']\nsc_lat_heeq=i.icmecat['SC_LAT_HEEQ']\nmo_bmax=i.icmecat['MO_BMAX']\nmo_bmean=i.icmecat['MO_BMEAN']\nmo_bstd=i.icmecat['MO_BSTD']\nmo_bzmean=i.icmecat['MO_BZMEAN']\nmo_bzmin=i.icmecat['MO_BZMIN']\nmo_duration=i.icmecat['MO_DURATION']\nmo_mva_axis_long=i.icmecat['MO_MVA_AXIS_LONG']\nmo_mva_axis_lat=i.icmecat['MO_MVA_AXIS_LAT']\nmo_mva_ratio=i.icmecat['MO_MVA_RATIO']\nsheath_speed=i.icmecat['SHEATH_SPEED']\nsheath_speed_std=i.icmecat['SHEATH_SPEED_STD']\nmo_speed=i.icmecat['MO_SPEED']\nmo_speed_st=i.icmecat['MO_SPEED_STD']\nsheath_density=i.icmecat['SHEATH_DENSITY']\nsheath_density_std=i.icmecat['SHEATH_DENSITY_STD']\nmo_density=i.icmecat['MO_DENSITY']\nmo_density_std=i.icmecat['MO_DENSITY_STD']\nsheath_temperature=i.icmecat['SHEATH_TEMPERATURE']\nsheath_temperature_std=i.icmecat['SHEATH_TEMPERATURE_STD']\nmo_temperature=i.icmecat['MO_TEMPERATURE']\nmo_temperature_std=i.icmecat['MO_TEMPERATURE_STD']\nsheath_pdyn=i.icmecat['SHEATH_PDYN']\nsheath_pdyn_std=i.icmecat['SHEATH_PDYN_STD']\nmo_pdyn=i.icmecat['MO_PDYN']\nmo_pdyn_std=i.icmecat['MO_PDYN_STD']\n\n\n#get indices of events by different spacecraft\nivexind=np.where(isc == 'VEX')\nistaind=np.where(isc == 'STEREO-A')\nistbind=np.where(isc == 'STEREO-B')\niwinind=np.where(isc == 'Wind')\nimesind=np.where(isc == 'MESSENGER')\niulyind=np.where(isc == 'ULYSSES')\nimavind=np.where(isc == 'MAVEN')\n\n\n#take MESSENGER only at Mercury, only events after orbit insertion\nimercind=np.where(np.logical_and(isc =='MESSENGER',icme_start_time_num > mdates.date2num(sunpy.time.parse_time('2011-03-18'))))\n\n#limits of solar minimum, rising phase and solar maximum\n\nminstart=mdates.date2num(sunpy.time.parse_time('2007-01-01'))\nminend=mdates.date2num(sunpy.time.parse_time('2009-12-31'))\n\nrisestart=mdates.date2num(sunpy.time.parse_time('2010-01-01'))\nriseend=mdates.date2num(sunpy.time.parse_time('2011-06-30'))\n\nmaxstart=mdates.date2num(sunpy.time.parse_time('2011-07-01'))\nmaxend=mdates.date2num(sunpy.time.parse_time('2014-12-31'))\n\n\n#extract events by limits of solar min, rising, max, too few events for MAVEN and Ulysses\n\n#extract events by limits of solar min, rising, max, too few events for MAVEN and Ulysses\n\niallind_min=np.where(np.logical_and(icme_start_time_num > minstart,icme_start_time_num < minend))[0]\niallind_rise=np.where(np.logical_and(icme_start_time_num > risestart,icme_start_time_num < riseend))[0]\niallind_max=np.where(np.logical_and(icme_start_time_num > maxstart,icme_start_time_num < maxend))[0]\n\niwinind_min=iallind_min[np.where(isc[iallind_min]=='Wind')]\niwinind_rise=iallind_rise[np.where(isc[iallind_rise]=='Wind')]\niwinind_max=iallind_max[np.where(isc[iallind_max]=='Wind')]\n\nivexind_min=iallind_min[np.where(isc[iallind_min]=='VEX')]\nivexind_rise=iallind_rise[np.where(isc[iallind_rise]=='VEX')]\nivexind_max=iallind_max[np.where(isc[iallind_max]=='VEX')]\n\nimesind_min=iallind_min[np.where(isc[iallind_min]=='MESSENGER')]\nimesind_rise=iallind_rise[np.where(isc[iallind_rise]=='MESSENGER')]\nimesind_max=iallind_max[np.where(isc[iallind_max]=='MESSENGER')]\n\nistaind_min=iallind_min[np.where(isc[iallind_min]=='STEREO-A')]\nistaind_rise=iallind_rise[np.where(isc[iallind_rise]=='STEREO-A')]\nistaind_max=iallind_max[np.where(isc[iallind_max]=='STEREO-A')]\n\nistbind_min=iallind_min[np.where(isc[iallind_min]=='STEREO-B')]\nistbind_rise=iallind_rise[np.where(isc[iallind_rise]=='STEREO-B')]\nistbind_max=iallind_max[np.where(isc[iallind_max]=='STEREO-B')]\n\n\n#select the events at Mercury extra after orbit insertion, no events for solar minimum!\nimercind_min=iallind_min[np.where(np.logical_and(isc[iallind_min] =='MESSENGER',icme_start_time_num[iallind_min] > mdates.date2num(sunpy.time.parse_time('2011-03-18'))))]\nimercind_rise=iallind_rise[np.where(np.logical_and(isc[iallind_rise] =='MESSENGER',icme_start_time_num[iallind_rise] > mdates.date2num(sunpy.time.parse_time('2011-03-18'))))]\nimercind_max=iallind_max[np.where(np.logical_and(isc[iallind_max] =='MESSENGER',icme_start_time_num[iallind_max] > mdates.date2num(sunpy.time.parse_time('2011-03-18'))))]\n\n\n\n\n\n############################## get Wind data ################################\n\nprint( 'read Wind.')\n#get insitu data\nwin= pickle.load( open( \"../catpy/DATACAT/WIND_2007to2018_HEEQ_plasma_median21.p\", \"rb\" ) )\n#win_time=IDL_time_to_num(win.temperatureime)\n#pickle.dump([win_time], open( \"DATACAT/insitu_times_mdates_win_2007_2018.p\", \"wb\" ) )\n[win_time]=pickle.load( open( \"../catpy/DATACAT/insitu_times_mdates_win_2007_2018.p\", \"rb\" ) )\nprint( 'read data done.')\n\n#############################################################################\n\n\n\n\n\n\n\n\n\n\n\n#############################\n#Questions?\n\n\n#1 classify MFRs for type - need to classify manually first?\n\n#split into training and test data\n\n\n#wie image recognition - aus einem Teil-Bild (Zeitserie der MFR + features sind ein 2D array)\n#das Rest Bild vorhersagen\n\n#oder Zeitserie der ersten 20% rein - klassifizieren - dann schauen wie es am wahrscheinlichsten weitergeht\n#durch pattern vergleich dieser Kategorie\n\n\n#die feature sind die Zeitserien über die ersten 20% und die parameter - label ist die gesamte Zeitserie\n\n\n\n\n\n\n\n##################### (1) classify background wind, sheath, MFR based on 4 features in hourly data\n\n\n#go through all wind data and check for each hour whether this is inside a MFR or sheath or background wind\n\n#3 labels: background wind, sheath, MFR\n#data: about 1e5 training instances (without test data) with 4 features: average btot, std btot, vtot, vstd\n\n#get the features and labels for ICME classification\n\nget_fl_classify=False\n#get_fl_classify=True\n\ninterval_hours=1\n\n#takes 22 minutes for full data\nif get_fl_classify:\n \n start = time.time()\n print('extract features for classification')\n\n #test CME extraction April 2010\n #win=win[1690000:1720000]\n #win_time=win_time[1690000:1720000]\n\n #win=win[1500000:2000000]\n #win_time=win_time[1500000:2000000]\n\n #win=win[0:2500000]\n #win_time=win_time[0:2500000]\n\n\n hour_int_size=round(np.size(win)/(60*interval_hours))-1\n\n btot_ave_hour=np.zeros(hour_int_size)\n btot_std_hour=np.zeros(hour_int_size)\n bmax_hour=np.zeros(hour_int_size)\n\n bz_ave_hour=np.zeros(hour_int_size)\n bz_std_hour=np.zeros(hour_int_size)\n\n by_ave_hour=np.zeros(hour_int_size)\n by_std_hour=np.zeros(hour_int_size)\n\n bx_ave_hour=np.zeros(hour_int_size)\n bx_std_hour=np.zeros(hour_int_size)\n \n vtot_ave_hour=np.zeros(hour_int_size)\n vtot_std_hour=np.zeros(hour_int_size)\n vmax_hour=np.zeros(hour_int_size)\n\n t_ave_hour=np.zeros(hour_int_size)\n t_std_hour=np.zeros(hour_int_size)\n n_ave_hour=np.zeros(hour_int_size)\n n_std_hour=np.zeros(hour_int_size)\n \n time_hour=np.zeros(hour_int_size)\n \n\n #get features for 1 hour steps\n for p in np.arange(hour_int_size):\n\n \n #extract index for current hour \n indexrange=np.where(np.logical_and(win_time > win_time[0]+p*interval_hours/24.0,win_time < win_time[0]+p*interval_hours/24.0+interval_hours/24.0))\n\n btot_ave_hour[p]=np.mean(win.btot[indexrange] )\n btot_std_hour[p]=np.std(win.btot[indexrange] )\t\n bmax_hour[p]=np.max(win.btot[indexrange] )\n\n bx_ave_hour[p]=np.mean(win.btot[indexrange] )\n bx_std_hour[p]=np.std(win.btot[indexrange] )\t\n\n by_ave_hour[p]=np.mean(win.btot[indexrange] )\n by_std_hour[p]=np.std(win.btot[indexrange] )\t\n\n bz_ave_hour[p]=np.mean(win.btot[indexrange] )\n bz_std_hour[p]=np.std(win.btot[indexrange] )\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n vtot_ave_hour[p]=np.mean(win.vtot[indexrange] )\n vtot_std_hour[p]=np.std(win.vtot[indexrange] )\n vmax_hour[p]=np.max(win.vtot[indexrange] )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t#add temperature, density\t\t\n\t\t\t\t\n t_ave_hour[p]=np.mean(win.temperature[indexrange] )\n t_std_hour[p]=np.std(win.temperature[indexrange] )\n n_ave_hour[p]=np.mean(win.density[indexrange] )\n n_std_hour[p]=np.std(win.density[indexrange] )\n\n time_hour[p]=win_time[0]+p*interval_hours/24+0.5*interval_hours/24 \n \n print('extract features done.')\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\n #plot features over original time series\n\n ############# \n #plt.figure(1)\n #plt.plot_date(win_time, win.btot,'k-', alpha=0.4)\n #plt.plot_date(time_hour, btot_std_hour)\n #plt.plot_date(time_hour, btot_ave_hour)\n #plt.tight_layout()\n \n \n #plt.figure(2)\n #plt.plot_date(win_time, win.vtot,'k-', alpha=0.4)\n #plt.plot_date(time_hour, vtot_std_hour)\n #plt.plot_date(time_hour, vtot_ave_hour)\n #plt.tight_layout()\n\n\n print('extract label for each hour interval with ICMECAT')\n\n #old try\n #1 if fully inside a sheath, 0 otherwise, same for others\n #sheath=np.zeros(hour_int_size)\n #mfr=np.zeros(hour_int_size)\n #bwind=np.zeros(hour_int_size)+1\n \n \n #classify: bwind =0, mfr=1 #leave for now: sheath=2\n sw_label=np.zeros(hour_int_size)\n\n for p in np.arange(hour_int_size):\n \n \n #icme_start_time_num[iwinind], mo_start_time_num[iwinind], mo_end_time_num[iwinind]\n \n #first try: check all ICMECAT events for each hour timestep\n \n for i in np.arange(np.size(iwinind)):\n #when current time is between ICME_START_TIME and MO_START_TIME, its a sheath \n #if np.logical_and(time_hour[p] > icme_start_time_num[iwinind][i],time_hour[p] < mo_start_time_num[iwinind][i]):\n # sw_label[p]=1\n #this is a MFR \n #elif \n if np.logical_and(time_hour[p] > mo_start_time_num[iwinind][i],time_hour[p] < mo_end_time_num[iwinind][i]):\n sw_label[p]=1\n\n \n\n\n #make nans to averages ***maybe better interpolation?\n nans=np.where(np.isnan(btot_ave_hour) == True)\n btot_ave_hour[nans]=np.nanmean(btot_ave_hour)\n\n nans=np.where(np.isnan(btot_std_hour) == True)\n btot_std_hour[nans]=np.nanmean(btot_std_hour)\n\n nans=np.where(np.isnan(bmax_hour) == True)\n bmax_hour[nans]=np.nanmean(bmax_hour)\n\n nans=np.where(np.isnan(bx_ave_hour) == True)\n bx_ave_hour[nans]=np.nanmean(bx_ave_hour)\n\n nans=np.where(np.isnan(bx_std_hour) == True)\n bx_std_hour[nans]=np.nanmean(bx_std_hour)\n\n nans=np.where(np.isnan(by_ave_hour) == True)\n by_ave_hour[nans]=np.nanmean(by_ave_hour)\n\n nans=np.where(np.isnan(by_std_hour) == True)\n by_std_hour[nans]=np.nanmean(by_std_hour)\n\n np.where(np.isnan(bz_ave_hour) == True)\n bz_ave_hour[nans]=np.nanmean(bz_ave_hour)\n\n nans=np.where(np.isnan(bz_std_hour) == True)\n bz_std_hour[nans]=np.nanmean(bz_std_hour)\n\n nans=np.where(np.isnan(vtot_ave_hour) == True)\n vtot_ave_hour[nans]=np.nanmean(vtot_ave_hour)\n\n nans=np.where(np.isnan(vtot_std_hour) == True)\n vtot_std_hour[nans]=np.nanmean(vtot_std_hour)\n \n nans=np.where(np.isnan(vmax_hour) == True)\n vmax_hour[nans]=np.nanmean(vmax_hour)\n\n \n nans=np.where(np.isnan(t_ave_hour) == True)\n t_ave_hour[nans]=np.nanmean(t_ave_hour)\n nans=np.where(np.isnan(t_std_hour) == True)\n t_std_hour[nans]=np.nanmean(t_std_hour)\n \n nans=np.where(np.isnan(n_ave_hour) == True)\n n_ave_hour[nans]=np.nanmean(n_ave_hour)\n nans=np.where(np.isnan(n_std_hour) == True)\n n_std_hour[nans]=np.nanmean(n_std_hour)\n\n\n # #save features and labels\n# #fl feature labels pandas dataframe\n# fl = {'B_ave': btot_ave_hour, 'B_std': btot_std_hour,'Bmax': bmax_hour, \n# 'Bx_ave': bx_ave_hour, 'Bx_std': bx_std_hour,\n# 'By_ave': by_ave_hour, 'By_std': by_std_hour,\n# 'Bz_ave': bz_ave_hour, 'Bz_std': bz_std_hour, \n# 'V_ave': vtot_ave_hour, 'V_std': vtot_std_hour,'Vmax': vmax_hour,\n# 'T_ave': t_ave_hour, 'T_std': t_std_hour,\n# 'N_ave': n_ave_hour, 'N_std': n_std_hour, 'sw_label': sw_label}\n# flf = pd.DataFrame(data=fl)\n# \n# #features: right format for sklearn, deeplearning, ...\n# \n# \n# #all features\n# X=np.zeros([hour_int_size,16]) \n# X[:,0]=btot_ave_hour\n# X[:,1]=btot_std_hour\n# X[:,2]=bmax_hour\n# X[:,3]=bx_ave_hour\n# X[:,4]=bx_std_hour\n# X[:,5]=by_ave_hour\n# X[:,6]=by_std_hour\n# X[:,7]=bz_ave_hour\n# X[:,8]=bz_std_hour\n# X[:,9]=vtot_ave_hour\n# X[:,10]=vtot_std_hour\n# X[:,11]=vmax_hour\n# X[:,12]=t_ave_hour\n# X[:,13]=t_std_hour\n# X[:,14]=n_ave_hour\n# X[:,15]=n_std_hour\n# \n\n #camporeale 2017 Xu 2015 : design features that allow discrimination\n \n \n #alfven speed \n alfv=btot_ave_hour*1e-9/np.sqrt(4*np.pi*1e-7*n_ave_hour*1.6726219*1e-27*1e6)/1000 #result in km/s\n #entropy\n entropy=(t_ave_hour)/(n_ave_hour*1e6)**(2/3)\n #Texp/Tp\n texp=((vtot_ave_hour/258)**3.113)/t_ave_hour\n \n\n\n #classify: bwind =0, mfr=1 no sheath\n bwind=np.where(sw_label==0)\n #sheath=np.where(sw_label==1)\n mfr=np.where(sw_label==1)\n \n \n \n fl = {'B_tot': btot_ave_hour,'V_tot': vtot_ave_hour, 'T_ave': t_ave_hour, 'T_std': t_std_hour,\n 'Entropy': entropy,'Alfven speed': alfv, 'T_exp': texp, 'sw_label': sw_label}\n\n flf = pd.DataFrame(data=fl)\n \n X=np.zeros([hour_int_size,7]) \n \n X[:,0]=btot_ave_hour\n X[:,1]=vtot_ave_hour\n X[:,2]=t_ave_hour\n X[:,3]=t_std_hour\n X[:,4]=entropy\n X[:,5]=alfv #alfven speed\n X[:,6]=texp #texp/t\n\n \n\n #X[:,1]=bmax_hour\n #X[:,2]=vtot_ave_hour\n #X[:,3]=vmax_hour\n #X[:,5]=n_ave_hour\n\n\n \n #labels: make one hot encoding for label array\n from keras.utils.np_utils import to_categorical\n y = to_categorical(sw_label, 2) #3 means number of categories\n \n #split into training and test data this has one hot encoding\n from sklearn.model_selection import train_test_split\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42, stratify=y)\n\n \n \n #pickle.dump([btot_ave_hour, btot_std_hour, vtot_ave_hour, vtot_std_hour, time_hour,sheath, mfr, bwind], open( \"mfr_classify/mfr_classify_features_labels_save_50p.p\", \"wb\" ) ) \n #pickle.dump([flf,X,y, X_train, X_test, y_train, y_test, sw_label], open( \"mfr_classify/mfr_classify_features_labels_all_new.p\", \"wb\" ) ) \n #pickle.dump([flf,X,y, X_train, X_test, y_train, y_test,sw_label], open( \"mfr_classify/mfr_classify_features_labels_small.p\", \"wb\" ) ) \n #pickle.dump([flf,X,y, X_train, X_test, y_train, y_test,sw_label], open( \"mfr_classify/mfr_classify_features_labels_small_campo.p\", \"wb\" ) ) \n pickle.dump([flf,X,y, X_train, X_test, y_train, y_test,sw_label], open( \"mfr_classify/mfr_classify_features_labels_large_campoxu.p\", \"wb\" ) ) \n\n\n print('labels extracted and saved. time in minutes:')\n end = time.time()\n print((end - start)/60)\n########################################################\n\nif get_fl_classify == False:\n #[btot_ave_hour, btot_std_hour, vtot_ave_hour, vtot_std_hour, time_hour,sheath, mfr, bwind]= pickle.load( open( \"mfr_classify/mfr_features_labels_save_50p.p\", \"rb\" ) )\n #[flf,X,y, X_train, X_test, y_train, y_test,sw_label]=pickle.load( open( \"mfr_classify/mfr_classify_features_labels_all_new.p\", \"rb\" ) )\n # [flf,X,y, X_train, X_test, y_train, y_test,sw_label]=pickle.load( open( \"mfr_classify/mfr_classify_features_labels_small_campo.p\", \"rb\" ) )\n [flf,X,y, X_train, X_test, y_train, y_test,sw_label]=pickle.load( open( \"mfr_classify/mfr_classify_features_labels_large_campoxu.p\", \"rb\" ) )\n\n\n #[flf,X,y, X_train, X_test, y_train, y_test]=pickle.load( open( \"mfr_classify/mfr_classify_features_labels_small.p\", \"rb\" ) )\n\n print('loaded features for classification')\n\n\n\n#check data histograms\n#flf.hist(bins=20,figsize=(10,10))\n#plt.tight_layout()\n#filename='mfr_classify/classify_hist.png'\n#plt.savefig(filename)\n\n\n#pd.plotting.scatter_matrix(flf,figsize=(10,10))\n#plt.tight_layout()\n#filename='mfr_classify/classify_scatter_matrix.png'\n#plt.savefig(filename)\n\n#classify: bwind =0, mfr=1 no sheath\nbwind=np.where(sw_label==0)\n#sheath=np.where(sw_label==1)\nmfr=np.where(sw_label==1)\n\n\n#fig=plt.figure(3)\n#ax = fig.add_subplot(111, projection='3d')\n#ax.scatter(X[mfr,0],X[mfr,1],X[mfr,2],'bo')\n#ax.scatter(X[bwind,0],X[bwind,1],X[bwind,2],'ko')\n\n\n# X[:,0]=entropy\n# X[:,1]=alfv #alfven speed\n# X[:,2]=texp #texp/t\n\n\n\n#plt.figure(4)\n#plt.plot(X[bwind,1],X[bwind,2],'ko')\n#plt.plot(X[mfr,1],X[mfr,2],'bo')\n\n\n#plt.figure(5)\n#plt.plot(X[mfr,0],X[mfr,2],'bo')\n#plt.plot(X[bwind,0],X[bwind,2],'ko')\n\n\n\n#plt.plot(X[bwind,0],X[bwind,1],'bo')\n\n\n###################### use a SVM\n\n#use here the original sw_label\n\nprint()\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.svm import LinearSVC\nfrom sklearn.svm import SVC\n\n#normalize\n#X[:,2]=X[:,2]*1e5\n#X[:,1]=X[:,1]/10\nX_trains, X_tests, y_trains, y_tests = train_test_split(X, sw_label, test_size=0.30, random_state=42,stratify=y)\n\nfrom sklearn import preprocessing \nX_trains=preprocessing.scale(X_trains)\nX_tests=preprocessing.scale(X_tests)\n\n\nfrom sklearn.metrics import confusion_matrix\n\n#clf=Pipeline([\n# (\"scaler\", StandardScaler()),\n# (\"linear_svc\", LinearSVC(C=1e2,loss=\"hinge\")),\n# ])\n\n\n#SVM\n#clf=Pipeline([\n# (\"scaler\", StandardScaler()),\n# (\"svm_clf\", SVC(kernel=\"rbf\",C=100,gamma=2)),\n# ])\n \nfrom sklearn.tree import DecisionTreeClassifier \n \n \nclf=DecisionTreeClassifier(max_depth=25) \nclf.fit(X_trains, y_trains)\n#clf.fit(X_trains, y_trains)\n\ny_preds = clf.predict(X_tests)\nprint(confusion_matrix(clf.predict(X_trains), y_trains))\n\nprint('all MFR intervals: ', np.size(np.where(y_trains==1)))\nprint('ratio: ', confusion_matrix(clf.predict(X_trains), y_trains)[1,1]/np.size(np.where(y_trains==1)))\n\nprint(confusion_matrix(y_tests, y_preds))\n\nprint('all MFR intervals: ', np.size(np.where(y_tests==1)))\nprint('ratio: ', confusion_matrix(y_preds, y_tests)[1,1]/np.size(np.where(y_tests==1)))\n\n\n#sys.exit()\n\n#plt.figure(3)\n#plt.plot(X[mfr,0],X[mfr,1],'bo',markersize=3)\n#plt.plot(X[bwind,0],X[bwind,1],'ko',markersize=3)\n\n\n\n\n\n# \n# xlim = [0,50]\n# ylim = [0,200]\n# NBINS = 25\n# xg = np.linspace(xlim[0], xlim[1], NBINS)\n# yg = np.linspace(ylim[0], ylim[1], NBINS)\n# Yg, Xg = np.meshgrid(yg, xg)\n# xy = np.vstack([Xg.ravel(), Yg.ravel()]).T\n# P1 = clf.decision_function(xy).reshape(Xg.shape)\n# cont = plt.contour(Xg, Yg, P1, colors='k',linewidth=9,\n# levels=[-1,0,1], alpha=0.7,\n# linestyles=['--','-','--'])\nprint()\nprint('Test score')\nprint(clf.score(X_tests, y_tests))\n\nfrom sklearn.metrics import accuracy_score\nprint(accuracy_score(y_tests, y_preds))\n\n\n#from sklearn.svm import SVC\n#svc = SVC(kernel='linear', C=1, gamma=1,verbose=True)\n\n\n#for c in [ 1e-2, 1e-1,1,1e1,1e2,1e3,1e4,1e5,1e6,1e7]:\n# print(c)\n#for gam in [1e-5, 1e-4, 1e-3, 1e-2, 1e-1,1,1e1,1e2,1e3,1e4,1e5,1e6,1e7]:\n# print(gam)\n# svc = SVC(kernel='rbf', C=1,gamma=gam)#,verbose=True)\n\n#svc = SVC(kernel='linear', C=1, gamma=1,verbose=True)\n\n\n\n\n\n#print('ypreds')\n#print(y_preds.tolist())\n\n\n#model2 = SVC(kernel='rbf', C=1E6, gamma=1.)\n#model2.fit(X, sw_label)\n#print(model2.score(X,sw_label))\n\n\n\nsys.exit()\n\n\n\n\n\n######################## ANN\n\n#ANN with 1 hidden layer\n\nfrom keras.layers import Input\nfrom keras.layers import Dense\nfrom keras.models import Model\n\n\n\n#input layer\ninputs = Input(shape=(7, ))\n#fully connected hidden layer\nfc = Dense(10)(inputs)\nfc2 = Dense(10)(fc)\nfc3 = Dense(10)(fc2)\n\n#output\npredictions = Dense(2, activation='softmax')(fc3)\n\nmodel = Model(input=inputs, output=predictions)\n\nmodel.summary()\n\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n\nfrom sklearn import preprocessing\n\nmodel.fit(preprocessing.scale(X_train), y_train, epochs=5)\n\n#loss_and_metrics = model.evaluate(X_test, y_test, batch_size=128) \n#print(loss_and_metrics)\n\ny_pred = model.predict(X_test)#, batch_size=128) \n\n\ny_testlab=np.zeros(len(y_test))\ny_predlab=np.zeros(len(y_test))\n\nfor q in np.arange(len(y_test)):\n if y_test[q][0]==1: y_testlab[q]=0\n if y_test[q][1]==1: y_testlab[q]=1\n #if y_test[q][2]==1: y_testlab[q]=2\n\n if y_pred[q][0]==1: y_predlab[q]=0\n if y_pred[q][1]==1: y_predlab[q]=1\n #if y_pred[q][2]==1: y_predlab[q]=2\n\n\n\nfrom sklearn.metrics import confusion_matrix\nprint(confusion_matrix(y_testlab, y_predlab))\n\n#from sklearn.metrics import accuracy_score\n#print(accuracy_score(y_test, y_pred))\n\n################ train model\n\n\n\n\n\n\n\n\n\nsys.exit()\n\n\n\n\n\n\n\n\n","sub_path":"mfr_classify.py","file_name":"mfr_classify.py","file_ext":"py","file_size_in_byte":24802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"400748884","text":"from openerp.osv import fields, orm\nimport openerp.addons.decimal_precision as dp\n\n\nclass account_voucher(orm.Model):\n _name = \"account.voucher\"\n _inherit = \"account.voucher\"\n\n def _amount_all_hkd(self, cr, uid, ids, field_name, arg, context=None):\n cur_obj = self.pool.get('res.currency')\n res = {}\n ctx = context.copy()\n for voucher in self.browse(cr, uid, ids, context=context):\n ctx.update({'date': voucher.date})\n rate_ids = cur_obj.search(cr, uid, [('name', '=', 'HKD')], context=ctx, limit=1)\n temp = voucher.amount\n cur = voucher.currency_id\n for rate_id in cur_obj.browse(cr, uid, rate_ids, ctx):\n if cur != rate_id:\n temp = cur_obj.compute(cr, uid, cur.id, rate_id.id, temp, context=ctx)\n res[voucher.id] = cur_obj.round(cr, uid, cur, temp)\n return res\n\n _columns = {\n 'amount_total_hkd': fields.function(_amount_all_hkd, digits_compute=dp.get_precision('Account'), string='Total (HKD)',\n store=True, help=\"The total amount in HKD.\"),\n }\n\n# end of account_voucher()\n","sub_path":"fal_total_amount_hkd_store/models/account_voucher.py","file_name":"account_voucher.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"552235267","text":"#\n# @lc app=leetcode.cn id=66 lang=python3\n#\n# [66] 加一\n#\n# https://leetcode-cn.com/problems/plus-one/description/\n#\n# algorithms\n# Easy (44.24%)\n# Likes: 478\n# Dislikes: 0\n# Total Accepted: 162K\n# Total Submissions: 365.9K\n# Testcase Example: '[1,2,3]'\n#\n# 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。\n# \n# 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。\n# \n# 你可以假设除了整数 0 之外,这个整数不会以零开头。\n# \n# 示例 1:\n# \n# 输入: [1,2,3]\n# 输出: [1,2,4]\n# 解释: 输入数组表示数字 123。\n# \n# \n# 示例 2:\n# \n# 输入: [4,3,2,1]\n# 输出: [4,3,2,2]\n# 解释: 输入数组表示数字 4321。\n# \n# \n#\n\n# @lc code=start\nclass Solution:\n def plusOne(self,digits):\n num = 0\n for i in range(len(digits)):\n num += digits[i] * pow(10, (len(digits)-1-i))\n return [int(i) for i in str(num+1)]\n# @lc code=end\n\n","sub_path":"66.加一.py","file_name":"66.加一.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"140783537","text":"\nfrom math import log, floor, sqrt\n\ndef nth_prime_number(n):\n num_prime = int(2 * n * log(n)) + 1 #formula\n primes = [1] * num_prime #list of length of num_prime with all elements as 1.\n count = 0 #count is the ith number \n if n == 1:\n return 2\n for i in range(2, num_prime + 1): #i is the index\n if primes[i]:\n count += 1\n for j in range(2*i, num_prime, i): #putting all multiples of the prime as 0\n primes[j] = 0\n if count == n:\n return i\n\nprint(nth_prime_number(2))\n\ndef isPrime_optimised(n):\n if n == 1: #1 is not a prime number\n return False\n elif n < 2: \n return False\n elif n < 4: # the only prime number less than 4 are 2 and 3\n return True\n elif n % 2 == 0: # 2 is the only even number\n return False\n elif n % 3 == 0:\n return False\n else:\n res = floor(sqrt(n)) # round-off to the greatest integer\n f = 5\n while f <= res:\n if n % f == 0:\n return False \n if n % (f + 2) == 0:\n return False\n f += 6\n return True\n\n\ndef nth_prime_method_two(limit):\n count = 1\n r = 1\n for i in range(1, limit + 1):\n if count == limit:\n return r\n r += 2\n if isPrime_optimised(r):\n count += 1\n return res \n\n\n# t = int(input().strip())\n# for a0 in range(t):\n# n = int(input().strip())\n# print(nth_prime_method_two(n))","sub_path":"Q7_10001st_prime_number.py","file_name":"Q7_10001st_prime_number.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"79650763","text":"'''\n@Descripttion: \n@version: 3.X\n@Author: hu_xz\n@Date: 2020-04-23 20:50:52\n@LastEditors: hu_xz\n@LastEditTime: 2020-04-25 16:26:47\n'''\n#\n# @lc app=leetcode.cn id=589 lang=python\n#\n# [589] N叉树的前序遍历\n#\n\n# @lc code=start\n\"\"\"\n# Definition for a Node.\nclass Node(object):\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\"\"\"\n\nclass Solution(object):\n def preorder(self, root):\n \"\"\"\n :type root: Node\n :rtype: List[int]\n \"\"\"\n if not root: return []\n stack, res = [root,], []\n while stack:\n tmp = stack.pop()\n res.append(tmp.val)\n stack.extend(tmp.children[::-1])\n return res\n \n\n# @lc code=end\n\n","sub_path":"Week_02/589.n叉树的前序遍历.py","file_name":"589.n叉树的前序遍历.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"92986167","text":"# https://atcoder.jp/contests/agc007/tasks/agc007_b\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda:sys.stdin.readline().rstrip()\ndef resolve():\n n=int(input())\n M=20000\n A=[M*i for i in range(1,n+1)]\n B=[M*(n-i+1) for i in range(1,n+1)]\n perm=list(map(lambda x:int(x)-1,input().split()))\n for i in range(n):\n A[perm[i]]+=i\n\n print(*A)\n print(*B)\nresolve()\n","sub_path":"AGC007/b_construct_sequences.py","file_name":"b_construct_sequences.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"177961599","text":"import tkinter as tk\r\nfrom tkinter import ttk\r\nimport tkinter as tk \r\nfrom PIL import Image, ImageTk\r\n \r\n# Creating tkinter window\r\nroot = tk.Tk () \r\nroot.title('Inverter Battery Selection Software')\r\nroot.geometry('1500x850')\r\nroot.config(bg = \"khaki1\")\r\n \r\n#Creating variables for gui\r\name = tk.StringVar()\r\ncfl = tk.IntVar()\r\ntube = tk.IntVar()\r\nfan = tk.IntVar()\r\ndish = tk.IntVar()\r\nlcd = tk.IntVar()\r\ncomputer = tk.IntVar()\r\n\r\n#Baground\r\nimage1 = Image.open(\"AC.PNG\")\r\ntest = ImageTk.PhotoImage(image1)\r\n\r\nlabel1 = tk.Label(image=test)\r\nlabel1.image = test\r\n\r\n\r\nlabel1.place(x=1, y=15) # Position image\r\n\r\n#Main title\r\nttk.Label(root, text = \"Inverter Battery Selection Software\",background = \"khaki1\",font = (\"Times New Roman\", 22)).grid(column = 2,row = 0, padx = 10, pady = 25)\r\nttk.Label(root, text = \"Customer Name \",background = \"khaki1\",font = (\"Times New Roman\", 15)).grid(column = 0,row = 1, padx = 10, pady = 25)\r\nent = ttk.Entry(root,width = 40, textvariable = ame)\r\nent.grid(column = 1,row = 1, padx = 10, pady = 25)\r\n\r\n#Labels for titles\r\nttk.Label(root, text = \"Appliances\", borderwidth = 3, background = \"khaki1\",font = (\"Times New Roman\", 14)).grid(column = 0,row = 2, padx = 10, pady = 25)\r\nttk.Label(root, text = \"Quantity\",background = \"khaki1\",font = (\"Times New Roman\", 14)).grid(column = 1,row = 2, padx = 10, pady = 25) #Combobox creation\r\nttk.Label(root, text = \"Approximate Wattage\",background = \"khaki1\",font = (\"Times New Roman\", 14)).grid(column = 2,row = 2, padx = 10, pady = 1) \r\n\r\n#=============================================================================\r\n\r\n#Landing Battery Image\r\nimage1 = Image.open(\"AD.PNG\")\r\ntest = ImageTk.PhotoImage(image1)\r\n\r\nlabel1 = tk.Label(image=test)\r\nlabel1.image = test\r\n\r\nlabel1.place(x=923, y=300)\r\n\r\n#------------------------------------------------------------------------------\r\n\r\n#1st Appliance\r\nlbl_cfl = ttk.Label(root, text = \"CFL - Large\" ,background = \"khaki1\", anchor=\"w\",borderwidth = 2, justify = \"left\", border=10 , font = (\"Times New Roman\", 11)).grid(column = 0,row = 3, padx = 10, pady = 25)\r\n \r\ncombo_cfl = ttk.Combobox(root,background = \"khaki1\", width = 27, textvariable = cfl) #Combobox creation\r\n \r\n# Adding combobox drop down list\r\ncombo_cfl['values'] = (0,1,2,3,4,5,6,7,8,9,10) \r\ncombo_cfl.grid(column = 1, row = 3)\r\nlbl1 = ttk.Label(root, text = 30 ,background = \"khaki1\",font = (\"Times New Roman\", 12)).grid(column = 2,row = 3, padx = 10, pady = 25) \r\ncombo_cfl.current()\r\n\r\n#------------------------------------------------------------------------------\r\n\r\n#2nd Appliance\r\nlbl_tube = ttk.Label(root, text = \"Tube Light \",justify = \"left\",anchor=\"w\",background = \"khaki1\",font = (\"Times New Roman\", 11)).grid(column = 0,row = 4, padx = 10, pady = 25)\r\n \r\ncombo_tube = ttk.Combobox(root,background = \"khaki1\", width = 27, textvariable = tube) #Combobox creation\r\nlbl3 = ttk.Label(root, text = 60,background = \"khaki1\",font = (\"Times New Roman\", 12)).grid(column = 2,row = 4, padx = 10, pady = 25) \r\n\r\n \r\n# Adding combobox drop down list\r\ncombo_tube['values'] = (0,1,2,3,4,5,6,7,8,9,10)\r\n \r\ncombo_tube.grid(column = 1, row = 4)\r\ncombo_tube.current()\r\n\r\n#------------------------------------------------------------------------------\r\n\r\n#3rd Appliance\r\n \r\nlbl_fan = ttk.Label(root, text = \"Fan \",background = \"khaki1\",justify = \"left\",font = (\"Times New Roman\", 11)).grid(column = 0,row = 5, padx = 10, pady = 25)\r\n \r\ncombo_fan = ttk.Combobox(root,background = \"khaki1\", width = 27, textvariable = fan) #Combobox creation\r\ncombo_fan.grid(column = 1, row = 5)\r\nlbl3 = ttk.Label(root, text = 100,background = \"khaki1\",font = (\"Times New Roman\", 12)).grid(column = 2,row = 5, padx = 10, pady = 25) \r\n\r\n \r\n# Adding combobox drop down list\r\ncombo_fan['values'] = (0,1,2,3,4,5,6,7,8,9,10)\r\n \r\ncombo_fan.current()\r\n\r\n#------------------------------------------------------------------------------\r\n\r\n#4th Appliance\r\nlbl_dish = ttk.Label(root, text = \"Satellite / Dish TV Connection \",anchor=\"w\",justify = \"left\",background = \"khaki1\",font = (\"Times New Roman\", 11)).grid(column = 0,row =6, padx = 10, pady = 25)\r\n \r\ncombo_dish = ttk.Combobox(root,background = \"khaki1\", width = 27, textvariable = dish) #Combobox creation\r\ncombo_dish.grid(column = 1, row = 6)\r\nlbl3 = ttk.Label(root, text = 100,background = \"khaki1\",font = (\"Times New Roman\", 12)).grid(column = 2,row = 6, padx = 10, pady = 25) \r\n \r\n# Adding combobox drop down list\r\ncombo_dish['values'] = (0,1,2,3,4,5,6,7,8,9,10)\r\n \r\ncombo_dish.current()\r\n\r\n#------------------------------------------------------------------------------\r\n\r\n#5th Appliance\r\nlbl_lcd = ttk.Label(root, text = \"LCD TV up to 32 inch \",justify = \"left\",background = \"khaki1\",font = (\"Times New Roman\", 11)).grid(column = 0,row = 7, padx = 10, pady = 25)\r\nbatteryBox = ttk.Label(root, text = \"--Recommended Battery (60 mins back-up)--\",justify = \"left\",background = \"khaki1\",font = (\"Times New Roman\", 15)).grid(column = 4,row = 8, padx = 10, pady = 25) \r\ncombo_lcd = ttk.Combobox(root,background = \"khaki1\", width = 27, textvariable = lcd) #Combobox creation\r\ncombo_lcd.grid(column = 1, row = 7)\r\nlbl3 = ttk.Label(root, text = 150,background = \"khaki1\",font = (\"Times New Roman\", 12)).grid(column = 2,row = 7, padx = 10, pady = 25) \r\n\r\n \r\n# Adding combobox drop down list\r\ncombo_lcd['values'] = (0,1,2,3,4,5,6,7,8,9,10)\r\n \r\ncombo_lcd.current()\r\n\r\n#------------------------------------------------------------------------------\r\n\r\n#6th Appliance\r\nlbl_computer = ttk.Label(root, text = \"Computer with monitor - max 20 in\",justify = \"left\",background = \"khaki1\",font = (\"Times New Roman\", 11)).grid(column = 0,row = 8, padx = 10, pady = 25)\r\n \r\nlbl_computer = ttk.Combobox(root,background = \"khaki1\", width = 27, textvariable = computer) #Combobox creation\r\nlbl_computer.grid(column = 1, row =8)\r\nlbl3 = ttk.Label(root, text = 450,background = \"khaki1\",font = (\"Times New Roman\", 12)).grid(column = 2,row = 8, padx = 10, pady = 25) \r\n\r\n \r\n# Adding combobox drop down list\r\nlbl_computer['values'] = (0,1,2,3,4,5,6,7,8,9,10)\r\n \r\nlbl_computer.current()\r\n \r\n#---------------------------------------------------------------------------------\r\n\r\n#Calculations \r\ndef but( ): \r\n\r\n a1 = cfl.get()\r\n a1 = a1 * 30\r\n a2 = tube.get()\r\n a2 = a2 * 60\r\n a3 = fan.get()\r\n a3 = a3 * 100\r\n a4 = dish.get()\r\n a4 = a4 * 100\r\n a5 = lcd.get()\r\n a5 = a5 * 150\r\n a6 = computer.get()\r\n a6 = a6 * 300 \r\n\r\n total = a1+a2+a3+a4+a5+a6\r\n print(\"\\nTotal load in Watts is \",total,\"W\") \r\n \r\n#creating gui for image \r\n if total > 1000:\r\n # Create a photoimage object of the image in the path\r\n image1 = Image.open(\"3.PNG\")\r\n test = ImageTk.PhotoImage(image1)\r\n\r\n label1 = tk.Label(image=test)\r\n label1.image = test\r\n\r\n # Position image\r\n label1.place(x=923, y=300)\r\n \r\n elif total > 600:\r\n # Create a photoimage object of the image in the path\r\n image1 = Image.open(\"2.PNG\")\r\n test = ImageTk.PhotoImage(image1)\r\n\r\n label1 = tk.Label(image=test)\r\n label1.image = test\r\n\r\n # Position image\r\n label1.place(x=923, y=300)\r\n\r\n\r\n else:\r\n # Create a photoimage object of the image in the path\r\n image1 = Image.open(\"1.PNG\")\r\n test = ImageTk.PhotoImage(image1)\r\n\r\n label1 = tk.Label(image=test)\r\n label1.image = test\r\n\r\n # Position image\r\n label1.place(x=923, y=300)\r\n root.mainloop()\r\n\r\n#=========================================================\r\n#Database\r\ndef base():\r\n import sqlite3 # Connect to sqlite database\r\n conn = sqlite3.connect('students.db') \r\n print(\"\\n\\nDatabase Created\")\r\n\r\n cursor = conn.cursor() #used cursor to point to the database connection\r\n \r\n\r\n def data():\r\n a1 = cfl.get()\r\n a1 = a1 * 30\r\n a2 = tube.get()\r\n a2 = a2 * 60\r\n a3 = fan.get()\r\n a3 = a3 * 100\r\n a4 = dish.get()\r\n a4 = a4 * 100\r\n a5 = lcd.get()\r\n a5 = a5 * 150\r\n a6 = computer.get()\r\n a6 = a6 * 450 \r\n \r\n name = ame.get()\r\n \r\n cursor.execute('CREATE TABLE IF NOT EXISTS final ( Name TEXT, A1 REAL , A2 REAL , A3 REAL ,A4 REAL , A5 REAL, A6 REAL)')\r\n \r\n print(\"\\nTable created successfully \")\r\n\r\n \r\n cursor.execute(\"INSERT INTO final (Name,A1,A2,A3,A4,A5,A6) VALUES(?, ?,?,?,?,?,?)\", (name,a1,a2,a3,a4,a5,a6))\r\n\r\n\r\n conn.commit()\r\n\r\n print(\"\\nRecords inserted........\")\r\n \r\n data()\r\n print(\"\\nReading Records.......\")\r\n print(\"Name,CFL,Tube,Fan,LCD,Dish,Computer\\n\\n\")\r\n cursor = conn.execute(\"SELECT * from final\")\r\n result = cursor.fetchall()\r\n print(result, end = \"\\n\")\r\n print(\"----------------------------------------------------------------------\")\r\n\r\n#Buttons \r\nb1 = ttk.Button(root,text = \"\\n Submit \\n\", command = but ) #command calls the function\r\nb1.grid(column = 1,row = 13) #packing button\r\n\r\nb2 = ttk.Button(root,text = \"Click here to update database\", command = base)\r\nb2.grid(column = 0, row = 14)\r\n\r\n#Exit Code\r\ndef iExit():\r\n\r\n root.destroy()\r\n return\r\n\r\nb3 = ttk.Button(root,text = \"\\n Exit \\n\", command =iExit)\r\nb3.grid(column = 2,row = 13) \r\n\r\ndef clearForm():\r\n cfl.set(0) \r\n tube.set(0) \r\n fan.set(0)\r\n dish.set(0)\r\n lcd.set(0)\r\n computer.set(0)\r\n image1 = Image.open(\"AD.PNG\")\r\n test = ImageTk.PhotoImage(image1)\r\n\r\n label1 = tk.Label(image=test)\r\n label1.image = test\r\n\r\n \r\n label1.place(x=923, y=300)\r\n\r\nb4 = ttk.Button(root,text = \"Clear form\", command= clearForm)\r\nb4.grid(column = 0,row = 13) \r\n\r\nroot.mainloop()\r\n \r\n ","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":10027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"538072210","text":"\ndef Question24():\n print(\"Enter two strings and I'll tell you if they are anagram:\")\n first = input(\"Enter the first string : \")\n second = input(\"Enter the second string : \")\n \n if is_anagram(first, second):\n print(\"{0:s} and {1:s} are anagram.\".format(first, second))\n else:\n print(\"{0:s} and {1:s} are not anagram.\".format(first, second))\n \n \ndef is_anagram(first, second):\n check = []\n k = 0\n if len(first) == len(second):\n for i in first:\n check.append(False)\n for j in second:\n if i == j:\n check[k] = True\n k = k + 1\n if(check.count(False) > 0):\n return False\n else:\n return True\n else:\n return False","sub_path":"CodingTraining/PythonStudy/Chapter05/Question24.py","file_name":"Question24.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"507564999","text":"import glob\nimport os\n\nimport MeCab\nfrom gensim import corpora, matutils\n\n\ndef doc2word(doc: str) -> list:\n tagger = MeCab.Tagger('mecabrc')\n node = tagger.parseToNode(doc)\n words = []\n while node:\n meta = node.feature.split(',')\n if meta[0] == '名詞':\n words.append(node.surface.lower())\n node = node.next\n return words\n\ndef generate_dictionary(data: list) -> type:\n dictionary = corpora.Dictionary(data)\n if os.path.isfile('Dictionary.txt'):\n dictionary.load_from_text('Dictionary.txt')\n else:\n dictionary.save_as_text('Dictionary.txt')\n return dictionary\n\ndef curpus2dense(dictionary: type, doc: list) -> list:\n bow = dictionary.doc2bow(doc)\n dense = list(matutils.corpus2dense([bow], num_terms=len(dictionary)).T[0])\n return dense\n\nif __name__ == '__main__':\n files = glob.glob('./data/*.txt')\n data = []\n for file in files:\n with open(file) as f:\n doc = f.read()\n data.append(doc2word(doc))\n dictionary = generate_dictionary(data)\n for doc in data:\n curpus2dense(dictionary, doc)\n","sub_path":"vectter/classifier/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"363175968","text":"#!/usr/bin/python\nimport psycopg2 as pg\n\ndef get_table_columns(connection, schema, table):\n cols = []\n try:\n cursor = connection.cursor()\n sql = \"SELECT * FROM {}.{} LIMIT 0\".format(schema, table)\n cursor.execute(sql)\n for desc in cursor.description:\n cols.append(desc[0])\n cursor.close()\n except pg.Error as e:\n print(e)\n return cols\n\ndef check_tables():\n connection = pg.connect('dbname=training user=postgres password=postgres host=localhost port=5432')\n schema = 'hn_paths'\n # for Roads\n #tables = ['ferrynode', 'ferryterminal', 'ferrylink', 'road', 'roadjunction', 'roadlink', 'roadnode', 'street']\n # for RAMI\n #tables = ['accessrestriction', 'hazard', 'highwaydedication', 'reinstatement', 'restrictionforvehicles', 'specialdesignation', 'structure', 'turnrestriction']\n # tables = ['connectinglink', 'connectingnode', 'ferrylink', 'ferrynode', 'ferryterminal', 'highwaydedication', 'maintenance', 'path', 'pathlink', 'pathnode', 'reinstatement', 'specialdesignation', 'street']\n tables = ['street']\n for t in tables:\n columns = get_table_columns(connection, schema, t)\n for c in columns:\n try:\n cur = connection.cursor()\n sql = \"SELECT DISTINCT {} FROM {}.{} ORDER BY {} NULLS LAST LIMIT 2\".format(c, schema, t, c)\n cur.execute(sql)\n results = cur.fetchall()\n if results[0][0] is None:\n print(t + \": \" + c + \" ...INVALID\")\n else:\n print(t + \": \" + c + \" ...OK\")\n cur.close()\n except pg.Error as e:\n print(e)\n\nif __name__ == '__main__':\n check_tables()\n","sub_path":"scripts/test_HN.py","file_name":"test_HN.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"348844223","text":"\r\nsimdataplus = [triboson_inv_mass_charge2,top_inv_mass_charge2,fake_inv_mass_charge2,diboson_inv_mass_charge2]\r\nsimweightplus = [triboson_weight_charge2,top_weight_charge2,fake_weight_charge2,diboson_weight_charge2]\r\n\r\nsimdatamin = [triboson_inv_mass_charge2min,top_inv_mass_charge2min,fake_inv_mass_charge2min,diboson_inv_mass_charge2min]\r\nsimweightmin = [triboson_weight_charge2min,top_weight_charge2min,fake_weight_charge2min,diboson_weight_charge2min]\r\n\r\nfig, (ax1, ax2) = plt.subplots(1,2)\r\n\r\nax1.hist(data_inv_mass_charge2, bins=inv_mass_bin,histtype='step',stacked=False,label='data')\r\nax1.hist(simdataplus, bins=inv_mass_bin,histtype='bar',weights=simweightplus,stacked=True,label=['triboson','top','fake','diboson'])\r\nax1.set_xlim([100,800])\r\nax1.set_xlabel('invariant mass (GeV)')\r\nax1.set_ylim([0,4])\r\nax1.set_ylabel('#events')\r\nax1.legend()\r\nax1.set_title('Invariant Mass for total charge = 2')\r\n\r\nax2.hist(data_inv_mass_charge2min, bins=inv_mass_bin,histtype='step',stacked=False,label='data')\r\nax2.hist(simdatamin, bins=inv_mass_bin,histtype='bar',weights=simweightmin,stacked=True,label=['triboson','top','fake','diboson'])\r\nax2.set_xlim([100,800])\r\nax2.set_xlabel('invariant mass (GeV)')\r\nax2.set_ylim([0,4])\r\nax2.set_ylabel('#events')\r\nax2.legend()\r\nax2.set_title('Invariant Mass for total charge = -2')\r\n\r\nplt.show()\r\n","sub_path":"plot code/invariant mass/plot_inv_mass_charges.py","file_name":"plot_inv_mass_charges.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"524206081","text":"'''\n2.3 设计算法\n归并排序:引入分治策略,使用递归思想进行算法设计\n时间复杂度 O(n) = nlogn\n'''\n\ndef Merge(L,R):\n A = []\n print(L,R)\n while L and R:\n if L[0]>R[0]:\n A.append(R.pop(0))\n else:\n A.append(L.pop(0))\n while L:\n A.append(L.pop(0))\n while R:\n A.append(R.pop(0))\n return A\n\ndef Merge_Sort(L):\n if (len(L) <2):\n return L\n middle = int(len(L)/2) \n left, right = L[0:middle], L[middle:]\n #print(left,right)\n return Merge(Merge_Sort(left),Merge_Sort(right))\n\n\na = [10,9,8,7,6,5,4,3,2,1,0]\nprint('Merge sort result:',Merge_Sort(a))","sub_path":"Section1/002_MERGESORT.py","file_name":"002_MERGESORT.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"550815445","text":"# 거스름돈\n#\n# 엘리스씨는 1원, 5원, 10원, 50원, 100원 짜리 동전이 무한개(!) 존재하는 가게에 근무한다. 손님이 계산을 하고 난 후,\n# 거스름돈을 돌려주어야 하는데 가능한 적은 수의 동전을 돌려주고 싶다. 예를 들어, 7원을 돌려줘야 한다면 1원을 7개 돌려줄 수도 있지만,\n# 그것보다는 5원 1개와 1원 2개를 돌려주는 것이 적은 수의 동전을 돌려주는 것이므로, 이것이 더 좋은 경우이다. 거스름돈 nn원을 돌려주어야 할 때,\n# 돌려주어야 하는 동전 개수의 최솟값을 출력하는 프로그램을 작성하세요.\n#\n# 입력\n# 첫째 줄에 거스름돈 nn원이 주어진다. (1 \\leq n \\leq 100,000,0001≤n≤100,000,000)\n#\n# 출력\n# 돌려주어야 하는 동전의 개수의 최솟값을 출력한다.\n#\n# 입력 예시 1\n# 7\n#\n# 출력 예시 1\n# 3\n#\n# 입력 예시 2\n# 103\n#\n# 출력 예시 2\n# 4\n\nimport sys\n\ndef coinChange(n) :\n '''\n n원을 돌려주기 위해 필요한 동전 개수의 최솟값을 반환하는 함수를 작성하세요.\n '''\n\n coins = [100, 50, 10, 5, 1]\n result = 0\n\n for c in coins :\n result += n // c\n n -= c * (n//c)\n\n return result\n\ndef main():\n '''\n 이 부분은 수정하지 마세요.\n '''\n\n n = int(input())\n\n print(coinChange(n))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"4주차/예제1.py","file_name":"예제1.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"251446323","text":"# -*- coding: utf-8 -*-\n\n\"\"\"WSGI configuration.\"\"\"\n\nimport os\nimport sys\n\n\n# python\nsys.path.append('/data2/python_venv/3.8/djshed/lib/python3.8/')\nsys.path.append('/data2/python_venv/3.8/djshed/lib/python3.8/site-packages/')\n# django\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djshed.settings.shell')\nos.environ.setdefault('PYTHON_EGG_CACHE', '/var/cache/python/.python-eggs')\nos.environ.setdefault('TZ', 'America/Chicago')\n# informix\nos.environ['INFORMIXSERVER'] = ''\nos.environ['DBSERVERNAME'] = ''\nos.environ['INFORMIXDIR'] = ''\nos.environ['ODBCINI'] = ''\nos.environ['ONCONFIG'] = ''\nos.environ['INFORMIXSQLHOSTS'] = ''\nos.environ['LD_LIBRARY_PATH'] = \"\"\"\n {0}/lib:{0}/lib/esql:{0}/lib/tools:/usr/lib/apache2/modules:{0}/lib/cli\n\"\"\".format(os.environ['INFORMIXDIR'])\nos.environ['LD_RUN_PATH'] = os.environ['LD_LIBRARY_PATH']\n# wsgi\nfrom django.core.wsgi import get_wsgi_application\napplication = get_wsgi_application()\n","sub_path":"djshed/wsgi_default.py","file_name":"wsgi_default.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"376631946","text":"class Settings:\n \"\"\"A class to store all settings for target Invasion.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the game's settings.\"\"\"\n # Screen settings\n self.screen_width = 0\n self.screen_height = 0\n self.bg_color = (255, 255, 255)\n\n # Ship settings\n self.ship_speed = 1.5\n\n # # Bullet settings\n self.bullet_speed = 3\n self.bullet_width = 10\n self.bullet_height = 3\n self.bullet_color = (60, 60, 60)\n self.bullets_allowed = 3\n self.bullets_limit = 3\n\n # target settings\n self.target_speed = 3.0\n self.target_drop_speed = 30\n # target_direction of 1 represents up; -1 represents down.\n self.target_direction = -1\n","sub_path":"p1_alien_invasion/project_1_exercises/pg_372_tiy_14_2/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"638228258","text":"\"\"\"\n使用udp套接字编程完成\n\n从客户端,input输入一个单词,发送给服务端\n从服务端,回发给客户端这个单词的解释,并在客户端打印一下\n\n单词使用 dict数据查询\n\n思路 :\n1. 接收到客户端的单词\n2. 通过数据库查找到单词(如果查不到怎么办)\n3. 将单词查询结果发送给客户端\n\n\"\"\"\n\nfrom socket import *\nimport pymysql\n\n# 数据库功能类\nclass Database:\n def __init__(self):\n # 链接数据库\n self.db = pymysql.connect(host=\"localhost\",\n port=3306,\n user=\"root\",\n password='123456',\n database=\"dict\",\n charset=\"utf8\")\n\n # 创建游标 (调用sql语句,获取执行结果)\n self.cur = self.db.cursor()\n\n # 关闭数据库\n def close(self):\n # 关闭游标和数据库\n self.cur.close()\n self.db.close()\n\n # 查单词\n def find_word(self,word):\n sql = \"select mean from words where word=%s;\"\n self.cur.execute(sql,[word])\n\n mean = self.cur.fetchone()\n if mean:\n # 如果找到了\n return mean[0]\n else:\n # 没找到\n return \"Not Found The Word!\"\n\n\n\ndef main():\n udp_socket = socket(AF_INET,SOCK_DGRAM) # 创建套接字\n udp_socket.bind((\"0.0.0.0\",8888)) # 绑定地址\n db = Database() # 实例化对象\n\n while True:\n try:\n data,addr = udp_socket.recvfrom(50) # 接收单词\n mean = db.find_word(data.decode()) # 找单词\n udp_socket.sendto(mean.encode(),addr) # 发送结果\n except KeyboardInterrupt:\n break\n\n db.close()\n udp_socket.close()\n print(\"服务结束\")\n\n\nmain()\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"day11/exercise_1_server.py","file_name":"exercise_1_server.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"596900920","text":"r\"\"\"The Born Iterative Method.\r\n\r\nThis module implements the Born Iterative Method [1]_ as a derivation of\r\nSolver class. The object contains an object of a forward solver and\r\none of linear inverse solver. The method solves the nonlinear\r\ninverse problem iteratively. The implemented in\r\n:class:`BornIterativeMethod`\r\n\r\nReferences\r\n----------\r\n.. [1] Wang, Y. M., and Weng Cho Chew. \"An iterative solution of the\r\n two‐dimensional electromagnetic inverse scattering problem.\"\r\n International Journal of Imaging Systems and Technology 1.1 (1989):\r\n 100-108.\r\n\"\"\"\r\n\r\n# Standard libraries\r\nimport copy as cp\r\nimport time as tm\r\nimport numpy as np\r\nimport sys\r\n\r\n# Developed libraries\r\nimport configuration as cfg\r\nimport inputdata as ipt\r\nimport results as rst\r\nimport solver as slv\r\nimport forward as fwr\r\nimport inverse as inv\r\n\r\n\r\nclass BornIterativeMethod(slv.Solver):\r\n r\"\"\"The Born Interative Method (BIM).\r\n\r\n This class implements a classical nonlinear inverse solver [1]_. The\r\n method is based on coupling forward and inverse solvers in an\r\n iterative process. Therefore, it depends on the definition of a\r\n forward solver implementation and an linear inverse one.\r\n\r\n Attributes\r\n ----------\r\n forward : :class:`forward.Forward`:\r\n An implementation of the abstract class which defines a\r\n forward method which solves the total electric field.\r\n\r\n inverse : :class:`inverse.Inverse`:\r\n An implementation of the abstract class which defines method\r\n for solving the linear inverse scattering problem.\r\n\r\n MAX_IT : int\r\n The number of iterations.\r\n\r\n References\r\n ----------\r\n .. [1] Wang, Y. M., and Weng Cho Chew. \"An iterative solution of the\r\n two‐dimensional electromagnetic inverse scattering problem.\"\r\n International Journal of Imaging Systems and Technology 1.1 (1989):\r\n 100-108.\r\n \"\"\"\r\n\r\n def __init__(self, configuration, version, forward_solver, inverse_solver,\r\n maximum_iterations=10):\r\n \"\"\"Create the object.\r\n\r\n Parameters\r\n ----------\r\n configuration : :class:`configuration.Configuration`\r\n It may be either an object of problem configuration or\r\n a string to a pre-saved file or a 2-tuple with the file\r\n name and path, respectively.\r\n\r\n version : str\r\n A string naming the version of this method. It may be\r\n useful when using different implementation of forward\r\n and inverse solvers.\r\n\r\n forward_solver : :class:`forward.Forward`\r\n An implementation of the abstract class Forward which\r\n defines a method for computing the total intern field.\r\n\r\n inverse_solver : :class:`inverse.Inverse`\r\n An implementation of the abstract class Inverse which\r\n defines a method for solving the linear inverse problem.\r\n\r\n maximum_iterations : int, default: 10\r\n Maximum number of iterations.\r\n \"\"\"\r\n super().__init__(configuration)\r\n self.MAX_IT = maximum_iterations\r\n self.forward = forward_solver\r\n self.inverse = inverse_solver\r\n self.name = 'Born Iterative Method'\r\n self.alias = version\r\n\r\n if self.forward.configuration is None:\r\n self.forward.configuration = self.configuration\r\n\r\n if self.inverse.configuration is None:\r\n self.inverse.configuration = self.configuration\r\n\r\n def solve(self, instance, print_info=True, print_file=sys.stdout):\r\n \"\"\"Solve a nonlinear inverse problem.\r\n\r\n Parameters\r\n ----------\r\n instance : :class:`inputdata.InputData`\r\n An object which defines a case problem with scattered\r\n field and some others information.\r\n\r\n print_info : bool\r\n Print or not the iteration information.\r\n \"\"\"\r\n super().solve(instance, print_info, print_file)\r\n\r\n if self.forward.configuration.name != self.configuration:\r\n self.forward.configuration = cp.deepcopy(self.configuration)\r\n if self.inverse.configuration.name != self.configuration:\r\n self.inverse.configuration = cp.deepcopy(self.configuration)\r\n\r\n result = rst.Results(instance.name + '_' + self.alias,\r\n method_name=self.alias,\r\n configuration_filename=self.configuration.name,\r\n configuration_filepath=self.configuration.path,\r\n input_filename=instance.name,\r\n input_filepath=instance.path)\r\n\r\n if print_info:\r\n print('Iterations: %d' % self.MAX_IT, file=print_file)\r\n print('----------------------------------------', file=print_file)\r\n print(self.forward, file=print_file)\r\n print('----------------------------------------', file=print_file)\r\n print(self.inverse, file=print_file)\r\n print('----------------------------------------', file=print_file)\r\n\r\n # The solution variable will be an object of InputData.\r\n solution = cp.deepcopy(instance)\r\n\r\n # First-Order Born Approximation\r\n solution.et = self.forward.incident_field(instance.resolution)\r\n\r\n # If the same object is used for different resolution instances,\r\n # then some parameters may need to be updated within the inverse\r\n # solver. So, the next line ensures it:\r\n self.inverse.reset_parameters()\r\n self.execution_time = 0.\r\n\r\n for it in range(self.MAX_IT):\r\n\r\n iteration_message = 'Iteration: %d - ' % (it+1)\r\n tic = tm.time()\r\n self.inverse.solve(solution)\r\n self.forward.solve(solution, SAVE_INTERN_FIELD=True)\r\n\r\n # The variable `execution_time` will record only the time\r\n # expended by the forward and linear routines.\r\n self.execution_time = self.execution_time + (tm.time()-tic)\r\n\r\n result.update_error(instance, scattered_field=solution.es,\r\n total_field=solution.et,\r\n relative_permittivity_map=solution.epsilon_r,\r\n conductivity_map=solution.sigma)\r\n\r\n iteration_message = result.last_error_message(instance,\r\n iteration_message)\r\n if print_info:\r\n print(iteration_message, file=print_file)\r\n\r\n # This is only emergencial feature for ensuring that the\r\n # scattered field data received by the inverse solver in the\r\n # next iteration will not be the one estimated in the last\r\n # call of the forward solver.\r\n if it != self.MAX_IT-1:\r\n solution.es = np.copy(instance.es)\r\n\r\n # Remember: results stores the estimated scattered field. Not\r\n # the given one.\r\n result.es = solution.es\r\n result.et = solution.et\r\n result.epsilon_r = solution.epsilon_r\r\n result.sigma = solution.sigma\r\n result.execution_time = self.execution_time\r\n\r\n return result\r\n","sub_path":"library/bim.py","file_name":"bim.py","file_ext":"py","file_size_in_byte":7328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"14976819","text":"import os, shutil\n\ncwd = os.getcwd()\ndir_files = os.listdir()\n\nclass Categorize():\n\n def __init__(self, **obj):\n self.path = cwd\n self.movedir = obj[\"movedir\"]\n self.extension = obj[\"extension\"]\n self.moveto()\n\n def moveto(self):\n total_file_moved = 0\n\n # to check if images, songs, videos, pdf dir is there if not then create a new one\n if not os.path.exists(os.path.join(self.path, self.movedir)):\n os.makedirs(os.path.join(self.path, self.movedir))\n \n # Now Move the file to their respctive directory\n for item in dir_files:\n item = item.lower()\n if os.path.isfile(item):\n if item.endswith(self.extension):\n total_file_moved += 1\n shutil.move(item, os.path.join(self.path, self.movedir))\n \n print({\n \"Status\": \"Completed\",\n \"File is\": self.movedir + \"(\" + self.extension + \")\",\n \"Total Files Moved\": total_file_moved\n })\n\n\napp = Categorize(**{\n \"movedir\": \"images\",\n \"extension\": \"png\"\n })\napp = Categorize(**{\n \"movedir\": \"images\",\n \"extension\": \"jpg\"\n })\napp = Categorize(**{\n \"movedir\": \"videos\",\n \"extension\": \"mp4\"\n })\napp = Categorize(**{\n \"movedir\": \"songs\",\n \"extension\": \"mp3\"\n })\napp = Categorize(**{\n \"movedir\": \"docs\",\n \"extension\": \"pdf\"\n })\napp = Categorize(**{\n \"movedir\": \"docs\",\n \"extension\": \"xlsx\"\n }) \n","sub_path":"categorize-v1.py","file_name":"categorize-v1.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"519087661","text":"from django.core.management.base import BaseCommand\nfrom cinemas.models import Cinema\nfrom cinemas.importers.mk2 import get_mk2_cinemas_list\n\nclass Command(BaseCommand):\n help = 'Import theaters from their websites and adds them to the database.'\n\n def add_arguments(self, parser):\n parser.add_argument('theater_brand', nargs=1, type=str)\n\n def handle(self, *args, **options):\n if 'MK2' in options['theater_brand']:\n cinemas = get_mk2_cinemas_list()\n created_theaters = []\n for theater in cinemas:\n new_theater = Cinema(\n name=theater.get('name'),\n brand='MK2',\n address=theater.get('address'),\n url=theater.get('url'))\n created_theaters.append(new_theater)\n\n Cinema.objects.bulk_create(created_theaters)\n","sub_path":"src/cinemas/management/commands/import_cinemas.py","file_name":"import_cinemas.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"70073464","text":"\"\"\"Module: Define Player and Rooms\"\"\"\n\nimport items as it\nimport story as s\n\n\nROOMS = {\n 1: {\"name\": \"White Room\",\n \"north\": it.BLUE_DOOR,\n \"item\": it.PACK, \"orb\": it.BLUE_ORB},\n 2: {\"name\": \"Blue Room\",\n \"south\": it.WHITE_DOOR, \"east\": it.GREEN_DOOR, \"west\": it.PURPLE_DOOR,\n \"object\": it.BOOKSHELF},\n 3: {\"name\": \"Green Room\",\n \"west\": it.BLUE_DOOR, \"north\": it.YELLOW_DOOR,\n \"orb\": it.PURPLE_ORB},\n 4: {\"name\": \"Purple Room\",\n \"east\": it.BLUE_DOOR, \"north\": it.RED_DOOR,\n \"object\": it.CAMERA_CRATE},\n 5: {\"name\": \"Red Room\",\n \"south\": it.PURPLE_DOOR, \"east\": it.ORANGE_DOOR,\n \"orb\": it.YELLOW_ORB},\n 6: {\"name\": \"Yellow Room\",\n \"south\": it.GREEN_DOOR, \"west\": it.ORANGE_DOOR,\n \"object\": it.BUILDING_MATERIALS},\n 7: {\"name\": \"Orange Room\",\n \"east\": it.YELLOW_DOOR, \"west\": it.RED_DOOR, \"north\": it.BLACK_DOOR,\n \"orb\": it.WHITE_ORB},\n 8: {\"name\": \"Black Room\",\n \"south\": it.ORANGE_DOOR,\n \"object\": it.SHRINE}\n}\nCHECKABLES = (it.BOOKSHELF, it.CAMERA_CRATE, it.BUILDING_MATERIALS, it.SHRINE)\nORB_LIST = (it.BLUE_ORB, it.GREEN_ORB, it.PURPLE_ORB, it.RED_ORB,\n it.YELLOW_ORB, it.ORANGE_ORB, it.WHITE_ORB, it.BLACK_ORB)\n\n\nclass Player():\n \"\"\"Establish Player gameplay\"\"\"\n def __init__(self, room=1, inventory=set()):\n self.room = room\n self.inventory = inventory\n\n def menu(self):\n \"\"\"List main menu\"\"\"\n line_1 = \"_\" * 58\n space = \" \" * 17\n\n print(\"\\n\" + line_1)\n print(space + \"Valid Commands\")\n print(space + \"--------------\"\n \"\\n> 'options' (List commands)\"\n \"\\n> 'check [target]' ('object', 'item', 'orb')\"\n \"\\n> 'go [direction]' (north, south, east, or west)\"\n \"\\n> 'get item' (Pick up nearby non-orb item)\"\n \"\\n> 'get orb' (Pick up nearby orb)\"\n \"\\n> 'gg' (Quit game)\")\n print(line_1 + \"\\n\")\n\n def stats(self):\n \"\"\"Broadcast current status\"\"\"\n line_2 = \"-\" * 30\n location = ROOMS[self.room]\n\n print(\"\\n\" + line_2)\n print(\"You are in : \" + location[\"name\"])\n if it.PACK in self.inventory:\n print(it.PACK.contents())\n if \"object\" in location:\n print(\"You catch sight of a {}\".format(location[\"object\"]))\n if \"item\" in location:\n print(\"You catch sight of a {}\".format(location[\"item\"]))\n if \"orb\" in location:\n print(\"You catch sight of a {}\".format(location[\"orb\"]))\n print(line_2 + \"\\n\")\n\n def match(self, door):\n \"\"\"Check PACK for Orb match\"\"\"\n for x in it.PACK.pocket:\n if x.icolor() == door.icolor():\n return True\n\n def move(self, direction):\n \"\"\"Move in desired direction\"\"\"\n door = ROOMS[self.room][str(direction)]\n\n if door.lock_status(False):\n self.room = door.room_tag()\n elif door.lock_status(True):\n print(\"\\nYou encounter \" + it.door_desc(door.icolor()))\n if it.PACK in self.inventory and self.match(door):\n door.unlock()\n self.room = door.room_tag()\n else:\n print(\"The door doesn't budge!\")\n\n def check(self, obj):\n \"\"\"Check Object for hidden Items\"\"\"\n print(\"\\nYou take a closer look at the {}...\".format(obj))\n print(obj.info())\n if obj in CHECKABLES and obj.not_checked():\n if obj == it.SHRINE:\n print(s.SHRINE_TEXT_BETA)\n del it.PACK.pocket[:]\n new_obj = obj.hidden()\n print(obj.hidden_text())\n print((\"You discover a {} \"\n \"hidden inside the {}!\").format(new_obj, obj))\n if new_obj in ORB_LIST:\n ROOMS[self.room][\"orb\"] = new_obj\n else:\n ROOMS[self.room][\"item\"] = new_obj\n else:\n return None\n\n def action(self):\n \"\"\"Establish Player action\"\"\"\n choice = input(\"> \").lower().split()\n location = ROOMS[self.room]\n\n if choice[0] == \"options\":\n self.menu()\n elif choice[0] == \"check\" and len(choice) > 1:\n if choice[1] == \"object\" and choice[1] in location:\n self.check(location[\"object\"])\n elif choice[1] == \"item\" and choice[1] in location:\n self.check(location[\"item\"])\n elif choice[1] == \"orb\" and choice[1] in location:\n self.check(location[\"orb\"])\n else:\n print(\"\\nIt must have been your imagination\")\n elif choice[0] == \"go\" and len(choice) > 1:\n if choice[1] == \"north\" and choice[1] in location:\n self.move(\"north\")\n elif choice[1] == \"east\" and choice[1] in location:\n self.move(\"east\")\n elif choice[1] == \"south\" and choice[1] in location:\n self.move(\"south\")\n elif choice[1] == \"west\" and choice[1] in location:\n self.move(\"west\")\n else:\n print(\"\\nThere's no going that way!\")\n elif choice[0] == \"get\" and len(choice) > 1:\n if choice[1] == \"item\" and \"item\" in location:\n if location[\"item\"] == it.PACK:\n self.inventory.add(it.PACK)\n else:\n it.PACK.add_pack(location[\"item\"])\n print(\"\\nPicked up {}!\".format(location[\"item\"]))\n print(location[\"item\"].info())\n del location[\"item\"]\n elif choice[1] == \"orb\" and \"orb\" in location:\n if it.PACK in self.inventory:\n it.PACK.add_pack(location[\"orb\"])\n print(\"\\nPicked up {}!\".format(location[\"orb\"]))\n print(location[\"orb\"].info())\n del location[\"orb\"]\n else:\n print(\"\\nYou should have worn the pants with pockets!\")\n elif choice[1] == \"object\" and \"object\" in location:\n print(\"\\nYou're going to need a bigger Pack!\")\n return None\n else:\n print(\"\\nIt must have been a mirage...\")\n elif choice[0] == \"gg\":\n while choice[0] == \"gg\":\n exit_choice = input(\"\\nAre you sure you wish to quit?\"\n \" Choose [Y] or [N]: \").lower()\n if exit_choice == \"y\":\n quit()\n elif exit_choice == \"n\":\n break\n else:\n print(\"\\nThat's not a valid choice.\")\n continue\n else:\n print(\"\\nThat's not a valid command!\")\n","sub_path":"thecraving/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":6861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"454546994","text":"# Verzenden API gegevens ZMQ-packet\nimport zmq\nimport time\ncontext = zmq.Context()\nsocket = context.socket(zmq.PUSH)\nsocket.connect(\"tcp://mc1337server.ddns.net:24241\")\nwhile True:\n # Declareren van voorbeeld waardes die zogezegd van de api komen\n # In de toekomst worden in deze variabelen de echte uitgelezen waardes van de api gestopt\n #topic = ID (x,y)\n x = 0\n y = 1\n #message\n mode = 2\n freq = 25.000 #in Hz\n R1 = 255\n G1 = 65\n B1 = 38\n W1 = 0\n R2 = 44\n G2 = 0\n B2 = 120\n W2 = 33\n R3 = 0\n G3 = 25\n B3 = 255\n W3 = 0\n hoekAlpha = 20\n hoekTheta = 170\n # Send to reciever\n socket.send_string(\"%u,%u>{%u,%f,[%u,%u,%u,%u],[%u,%u,%u,%u],[%u,%u,%u,%u],[%u,%u]}\"\n % (x, y, mode, freq, R1, G1, B1, W1, R2, G2, B2, W2, R3, G3, B3, W3, hoekAlpha, hoekTheta))\n time.sleep(1)\n","sub_path":"PsocCode/forwarder_server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"251825294","text":"\"\"\"\nURL Configuration for superheroes\n\"\"\"\nfrom django.urls import path\nfrom . import views # import views from app\nfrom . import views404\nfrom . import viewsbasictemplate\nfrom . import viewstemplate\nfrom . import viewsqueries\n\napp_name = 'superheroes'\n\nurlpatterns = [\n path('', views.home, name='home'), # 'superheroes:home'\n # 'NAMESPACE:VIEW'\n path('hero//', views.hero, name=\"hero\"),\n\n\n path('hero404x//', views404.hero404, name=\"hero404\"),\n path('hero404sc//', views404.hero404sc, name=\"hero404sc\"),\n path(\n 'herotemplate101//',\n viewsbasictemplate.hero_basic_template,\n name=\"herobasictemplate\",\n ),\n path(\n 'herohardway//',\n viewstemplate.hero_hard_way,\n name=\"herohardway\",\n ),\n path(\n 'heroeasyway//',\n viewstemplate.hero_easy_way,\n name=\"heroeasyway\",\n ),\n path(\n 'herolookups//',\n viewstemplate.hero_lookups,\n name=\"herolookups\",\n ),\n path(\n 'herofilters//',\n viewstemplate.hero_filters,\n name=\"herofilters\",\n ),\n path(\n 'herotags//',\n viewstemplate.hero_tags,\n name=\"herotags\",\n ),\n path(\n 'herodetails//',\n viewstemplate.hero_details,\n name=\"herodetails\",\n ),\n path(\n 'heroescape//',\n viewstemplate.hero_escape,\n name=\"heroescape\",\n ),\n path(\n 'herourls/',\n viewstemplate.hero_urls,\n name=\"herourls\",\n ),\n path(\n 'herostatic//',\n viewstemplate.hero_static,\n name=\"herostatic\",\n ),\n path(\n 'heroqueries/',\n viewsqueries.hero_queries,\n name=\"heroqueries\",\n ),\n path(\n 'session1', views.session1, name='session1'\n ),\n path(\n 'session2', views.session2, name='session2'\n ),\n path('login/', views.login, name='login'),\n path('logout/', views.logout, name='logout'),\n]\n\n","sub_path":"wombats/EXAMPLES/django2.0/djsuper/superheroes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"87618289","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('cv', '0002_auto_20160328_2153'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='contactmethod',\n name='type',\n field=models.IntegerField(choices=[(3, 'email'), (1, 'land phone'), (0, 'cell phone'), (2, 'skype')], verbose_name='type'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='education',\n name='importance',\n field=models.IntegerField(help_text='Educations with higher importance will be placed grouped and placed higher chronologically in the CV.', choices=[(2, 'interesting'), (0, 'very important'), (1, 'important'), (3, 'unimportant')], verbose_name='Importance'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='workexperience',\n name='_company_logo_height',\n field=models.PositiveIntegerField(editable=False, blank=True, null=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='workexperience',\n name='_company_logo_width',\n field=models.PositiveIntegerField(editable=False, blank=True, null=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='workexperience',\n name='company_logo',\n field=models.ImageField(upload_to='', blank=True, null=True, verbose_name='Company logo', width_field='_company_logo_width', height_field='_company_logo_height'),\n preserve_default=True,\n ),\n ]\n","sub_path":"backend/cv/migrations/0003_auto_20160328_2241.py","file_name":"0003_auto_20160328_2241.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"379525519","text":"from synapse.lib.module import CoreModule\n\nlatlongre = '^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?),\\s*[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$'\n\nclass GeoMod(CoreModule):\n\n @staticmethod\n def getBaseModels():\n modl = {\n 'types': (\n ('geo:place', {'subof': 'guid', 'alias': 'geo:place:alias', 'doc': 'A GUID for a specific place'}),\n ('geo:alias',\n {'subof': 'str:lwr', 'regex': '^[0-9a-z]+$', 'doc': 'An alias for the place GUID', 'ex': 'foobar'}),\n ('geo:latlong',\n {'subof': 'str', 'regex': latlongre, 'nullval': '??', 'doc': 'A Lat/Long string specifying a point'}),\n ),\n\n 'forms': (\n ('geo:place', {'ptype': 'geo:place'}, [\n ('alias', {'ptype': 'geo:alias'}),\n ('name', {'ptype': 'str', 'lower': 1, 'doc': 'The name of the place'}),\n ('latlong', {'ptype': 'geo:latlong', 'defval': '??', 'doc': 'The location of the place'}),\n ]),\n ),\n\n }\n name = 'geo'\n return ((name, modl), )\n","sub_path":"synapse/models/geospace.py","file_name":"geospace.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"48794292","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n# This script is an attempt to solve:\n# https://adventofcode.com/2019/day/1\n\n\"\"\"\nFuel required to launch a given module is based on its mass.\nSpecifically, to find the fuel required for a module,\ntake its mass, divide by three, round down, and subtract 2.\n\nThe Fuel Counter-Upper needs to know the total fuel requirement.\nTo find it, individually calculate the fuel needed for the mass \nof each module (your puzzle input), then add together all the fuel values.\n\"\"\"\n\nimport math\n\ndef round_down(n, decimals=0):\n multiplier = 10 ** decimals\n return math.floor(n * multiplier) / multiplier\n\ntotal_fuel_required = 0\n#Read lines from input file\nwith open(\"day1_input.txt\", \"r\") as file:\n line = file.readline()\n while line:\n #removing whitespace characters\n line = line.strip()\n #checking if the input lines are all integers\n try:\n line = int(line)\n #print(str(line))\n #for each input line calculate fuel requirement and add the fuel requirement to total requirement\n module_fuel_required = round_down(line / 3) - 2\n #print(\"module_fuel_required:\",int(module_fuel_required))\n total_fuel_required = int(total_fuel_required) + int(module_fuel_required)\n except:\n print(\"Input is not integer\",line)\n line = file.readline()\nprint(\"Result: \" + str(total_fuel_required))","sub_path":"adventofcode/2019/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"173117636","text":"# TIPO ABSTRATO DE DADOS - TAD\n#CONJUNTO DE VALORES E CONJUNTO DE OPERAÇÕES SOBRE ESTES VALORES\n\n# LIFO - LAST IN-FIRT OUT ---STATIC\n'''\npush = inserirInicio\npop = removerInicio\ngetTopo = getPrim\nestaVazia = estaVazia\n'''\n\nclass Les():\n def __init__(self):\n self.vet = [None, None, None, None, None, None]\n self.quant = 0\n def inserirFim(self, valor):\n self.vet[self.quant] = valor\n self.quant += 1\n def remover(self, valor):\n qt = i = 0\n while i bytes: # used because int can't fit as bytes function's input\n o = [0] * 32\n for x in range(32):\n o[31 - x] = i & 0xFF\n i >>= 8\n return bytes(o)\n\n\ndef extract32(data: bytearray, i: int) -> int:\n if i >= len(data):\n return 0\n o = data[i : min(i + 32, len(data))]\n o.extend(bytearray(32 - len(o)))\n return bytearray_to_int(o)\n\n\ndef ecrecover(data: Union[bytes, str, List[int]]) -> bytes:\n # TODO: Add type hints\n try:\n data = bytearray(data)\n v = extract32(data, 32)\n r = extract32(data, 64)\n s = extract32(data, 96)\n except TypeError:\n raise NativeContractException\n\n message = b\"\".join([ALL_BYTES[x] for x in data[0:32]])\n if r >= secp256k1n or s >= secp256k1n or v < 27 or v > 28:\n return []\n try:\n pub = ecrecover_to_pub(message, v, r, s)\n except Exception as e:\n log.debug(\"An error has occured while extracting public key: \" + e)\n return []\n o = [0] * 12 + [x for x in sha3(pub)[-20:]]\n return o\n\n\ndef sha256(data: Union[bytes, str, List[int]]) -> bytes:\n try:\n data = bytes(data)\n except TypeError:\n raise NativeContractException\n return hashlib.sha256(data).digest()\n\n\ndef ripemd160(data: Union[bytes, str, List[int]]) -> bytes:\n try:\n data = bytes(data)\n except TypeError:\n raise NativeContractException\n digest = hashlib.new(\"ripemd160\", data).digest()\n padded = 12 * [0] + list(digest)\n return bytes(padded)\n\n\ndef identity(data: Union[bytes, str, List[int]]) -> bytes:\n # Group up into an array of 32 byte words instead\n # of an array of bytes. If saved to memory, 32 byte\n # words are currently needed, but a correct memory\n # implementation would be byte indexed for the most\n # part.\n return data\n result = []\n for i in range(0, len(data), 32):\n result.append(simplify(Concat(data[i : i + 32])))\n return result\n\n\ndef native_contracts(address: int, data: BaseCalldata):\n \"\"\"\n takes integer address 1, 2, 3, 4\n \"\"\"\n functions = (ecrecover, sha256, ripemd160, identity)\n\n if isinstance(data, ConcreteCalldata):\n data = data.concrete(None)\n else:\n raise NativeContractException()\n\n return functions[address - 1](data)\n","sub_path":"mythril/laser/ethereum/natives.py","file_name":"natives.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"615403751","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('register/',views.register),\n path('register_handle/',views.register_handle),\n path('login/',views.login),\n path('login_handle/',views.login_handle),\n path('info/',views.info),\n path('order/',views.order),\n path('site/',views.site),\n]","sub_path":"project01/user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"450323489","text":"from enum import Enum\n\nclass EnumMariaParameterType(Enum):\n Object = 0\n Char = 1\n Int = 2\n Numeric = 3\n DateTime = 4\n\nclass MariaParameter:\n strOperator = None\n objValue = None\n enumType = EnumMariaParameterType.Object\n strKey = None\n\n def __init__(self, objValue, enumType, strOperator=None):\n self.strOperator = strOperator\n self.objValue = objValue\n self.enumType = enumType\n\n def setParameterKey(self, strKey):\n self.strKey = strKey\n return True\n\n def getSQLCommand(self):\n strSQLCommand = \"\"\n strValue = \"\"\n\n if self.objValue == None:\n if self.strOperator == \"<>\":\n strSQLCommand = self.strKey + \" IS NOT NULL\"\n elif self.strOperator == \"=\":\n strSQLCommand = self.strKey + \" IS NULL\"\n else:\n strSQLCommand = \"NULL\"\n elif isinstance(self.objValue, list) and self.strOperator == \"IN\":\n strSQLCommand = self.strKey + \" IN \" + \"('\" +\"','\".join(self.objValue) + \"')\"\n else:\n strValue = str(self.objValue).replace(\"'\", \"''\")\n\n if self.enumType == EnumMariaParameterType.Object:\n strSQLCommand = strValue\n elif self.enumType == EnumMariaParameterType.Char or self.enumType == EnumMariaParameterType.DateTime:\n if self.strOperator == None:\n strSQLCommand = \"'\" + strValue + \"'\"\n else:\n strSQLCommand = self.strKey + self.strOperator + \"'\" + strValue + \"'\"\n elif self.enumType == EnumMariaParameterType.Int or self.enumType == EnumMariaParameterType.Numeric:\n if self.strOperator == None:\n strSQLCommand = strValue\n else:\n strSQLCommand = self.strKey + self.strOperator + strValue\n\n return strSQLCommand\n","sub_path":"CODE/WantTech/WantTechPython/WantTech/Entity/MariaEntity.py","file_name":"MariaEntity.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"217321295","text":"import os\r\nimport json\r\nimport random\r\n\r\nfrom bot.module.commands.processor import Processor\r\n\r\n\r\nclass InfoProcessor(Processor):\r\n \"\"\"Processor for all information that a viewer may request.\r\n\r\n Attributes:\r\n motd_data: message of the day.\r\n who_data: information about the current streamer.\r\n twitter_accounts: list of twitter accounts loaded from file\r\n \"\"\"\r\n\r\n def __init__(self):\r\n self.motd_data = 'Aucun message.'\r\n self.who_data = 'Aucune info sur le streamer actuel.'\r\n\r\n with open(os.path.join(os.path.dirname(__file__),\r\n 'twitters.json')) as json_data:\r\n self.twitter_accounts = json.load(json_data)\r\n\r\n self.commands.extend([{\r\n 'aliases': ['help', 'aide', 'h'],\r\n 'command': self.help\r\n }, {\r\n 'aliases': ['who', 'qui'],\r\n 'command': self.who\r\n }])\r\n if self.bot.config['TWITTER'].getboolean('enabled', False):\r\n self.commands.append({\r\n 'aliases': ['twitter', 't'],\r\n 'command': self.twitter\r\n })\r\n if self.bot.config['MOTD'].getboolean('enabled', False):\r\n self.commands.append({\r\n 'aliases': ['motd', 'mdj'],\r\n 'command': self.motd\r\n })\r\n if self.bot.config['YOUTUBE'].getboolean('enabled', False):\r\n self.commands.append({\r\n 'aliases': ['youtube', 'y'],\r\n 'command': self.youtube\r\n })\r\n\r\n def help(self, param_line, sender, is_admin):\r\n \"\"\"Returns all the commands the bot is listening to.\"\"\"\r\n command_names = []\r\n\r\n for command in self.get_commands().commands:\r\n command_names.append(command['aliases'][0])\r\n\r\n line = \"Les commandes sont: {0}.\".format(', '.join(sorted(command_names)))\r\n\r\n self.get_irc().send_msg(line)\r\n\r\n def motd(self, param_line, sender, is_admin):\r\n \"\"\"Display an informative message for the viewers.\r\n\r\n Only admins are able to change the message.\r\n \"\"\"\r\n if is_admin and param_line is not None:\r\n self.motd_data = 'Message du jour: {0}'.format(param_line)\r\n self.get_irc().send_msg(self.motd_data)\r\n\r\n def who(self, param_line, sender, is_admin):\r\n \"\"\"Display current streamers.\r\n\r\n Only admins are able to change the message.\r\n \"\"\"\r\n if is_admin and param_line is not None:\r\n self.who_data = 'Streamers actuels: {0}'.format(param_line)\r\n self.get_irc().send_msg(self.who_data)\r\n\r\n def youtube(self, param_line, sender, is_admin):\r\n \"\"\"Print the youtube official channel of the FroggedTV\"\"\"\r\n self.get_irc().send_msg('Le YouTube de la chaîne est: ' +\r\n self.get_bot().config['YOUTUBE']['youtube_url'])\r\n\r\n def twitter(self, param_line, sender, is_admin):\r\n \"\"\"Display the Twitter acco unt of the asked streamer.\"\"\"\r\n if param_line is not None:\r\n twitter = self.find_twitter(param_line.lower())\r\n else:\r\n twitter = self.find_twitter('froggedtv')\r\n\r\n if twitter is not None:\r\n line = '{0}: {1}'.format(twitter['pretty_name'], twitter['link'])\r\n self.get_irc().send_msg(line)\r\n\r\n def find_twitter(self, name):\r\n \"\"\"Find the twitter account linked to a streamer name.\r\n\r\n Args:\r\n name: name of the twitter account requested.\r\n Returns:\r\n The twitter account information with name as one of it aliases,\r\n or None if no account is found.\r\n \"\"\"\r\n for twitter_account in self.twitter_accounts:\r\n if name in twitter_account['aliases']:\r\n return twitter_account\r\n\r\n return None\r\n","sub_path":"bot/module/commands/info/info_processor.py","file_name":"info_processor.py","file_ext":"py","file_size_in_byte":3849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"190036528","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\n\ndef wait():\n k = cv2.waitKey(0)\n if k == 27: # wait for ESC key to exit\n cv2.destroyAllWindows()\n elif k == ord('s'): # wait for 's' key to save and exit\n cv2.imwrite('./resources/test.png',img)\n cv2.destroyAllWindows()\n\ndef print_image_pixel(img):\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n rgb = cv2.split(img)\n extent = 0, 500, 0, 500\n\n plt.subplot(2, 2, 1) \n plt.title('Origin image', fontweight =\"bold\")\n plt.imshow(img, interpolation ='nearest', extent = extent)\n\n plt.subplot(2, 2, 2) \n plt.title('Red image', fontweight =\"bold\")\n plt.imshow(rgb[0], cmap =\"binary_r\", interpolation ='nearest', extent = extent)\n\n plt.subplot(2, 2, 3) \n plt.title('Green image', fontweight =\"bold\")\n plt.imshow(rgb[1], cmap =\"binary_r\", interpolation ='nearest', extent = extent)\n\n plt.subplot(2, 2, 4) \n plt.title('Blue image', fontweight =\"bold\")\n plt.imshow(rgb[2], cmap =\"binary_r\", interpolation ='nearest', extent = extent)\n\n plt.show()\n \n\ndef rotate_image(image, angle):\n image_center = tuple(np.array(image.shape[1::-1]) / 2)\n rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)\n result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_CUBIC)\n return result\n\ndef flip_image(img,axes):\n if (axes == 0) :\n #horizental flip\n return cv2.flip( img, 0 )\n elif(axes == 1):\n #vertical flip\n return cv2.flip( img, 1 )\n elif(axes == -1):\n #both direction\n return cv2.flip( img, -1 )\n\ndef crop_image(img, xStart, xEnd, yStart, yEnd):\n return img[xStart:xEnd, yStart:yEnd]\n\ndef resize_image(img, fx, fy, interpolation):\n return cv2.resize(img,None,fx=fx, fy=fy, interpolation = interpolation)\n\ndef translate_image(img, tx, ty):\n (h, w, d) = img.shape\n M = np.float32([\n [1, 0, ty],\n [0, 1, tx]\n ])\n return cv2.warpAffine(img,M,(w,h))\n\ndef shear_image(img, shx, shy):\n (h, w, d) = img.shape\n M2 = np.float32([[1, 0, 0], [1, 2, 0]])\n # M2[0,2] = -M2[0,1] * w/2\n # M2[1,2] = -M2[1,0] * h/2\n return cv2.warpAffine(img, M2, (w, h))\n\n# origin image\nimg = cv2.imread('./images/origin.jpg', cv2.IMREAD_UNCHANGED)\n\nprint_image_pixel(img)\n\n# rotation\nrotate = rotate_image(img, 30)\n\n# resize\nresize = resize_image(img, 0.5, 0.5, cv2.INTER_CUBIC)\n\n# translation\ntrans = translate_image(img, 100, 200)\n\n# shear\naff = shear_image(img, 1, 1)\n\n# crop\ncrop = crop_image(img, 0, 100, 0, 200)\n\n# flip\nhflip = flip_image(resize, 0)\nvflip = flip_image(resize, 1)\nhvflip = flip_image(resize, -1)\n\n# cv2.imshow('Original Image', img)\n# cv2.imshow('Rotate 30 deg Image', rotate)\n# cv2.imshow('Resize Image', resize)\n# cv2.imshow('Translate Image', trans)\n# cv2.imshow('Shear Image', aff)\n# cv2.imshow('Crop Image', crop)\n# cv2.imshow('H Flip Image', hflip)\n# cv2.imshow('V Flip Image', vflip)\n# cv2.imshow('HV Flip Image', hvflip)\n\nwait()","sub_path":"210408/geometric.py","file_name":"geometric.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"389363058","text":"#!/usr/bin/env python3\n\n# Make a simple request thru a intercepting proxy like Burpsuite\n# By Stian Kristoffersen\n\n\nimport requests\n\n\n# Fake headers\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Accept-Encoding': 'gzip, deflate'\n }\n\n\n# Define address and port for intercepting proxy\nproxies = {\n 'https': 'localhost:8080',\n 'http' : 'localhost:8080'\n}\n\n\n# URLs for testing\nurl1 = 'https://www.vg.no'\nurl2 = 'http://www.jsfuck.com'\n\n\n# Request\nr = requests.get(url2, headers=headers, proxies=proxies, verify=False)\n","sub_path":"request-burp.py","file_name":"request-burp.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"211830297","text":"from jose import jwt\n\nfrom openid_connect.errors import Forbidden\n\n\ndef verify(client, id_token, **params):\n\ttry:\n\t\tdata = jwt.decode(\n\t\t\tid_token,\n\t\t\tclient.keys,\n\t\t\taudience = client.client_id,\n\t\t\toptions = dict(\n\t\t\t\tverify_iss = False,\n\t\t\t\tverify_at_hash = False,\n\t\t\t),\n\t\t)\n\texcept jwt.JWTError as e:\n\t\traise Forbidden(\"Invalid ID token.\") from e\n\n\t# Work around Google bug\n\tif data['iss'] == 'accounts.google.com':\n\t\tdata['iss'] = 'https://accounts.google.com'\n\n\tif data['iss'] != client.issuer:\n\t\traise Forbidden(\"Invalid ID token.\")\n\n\treturn data\n","sub_path":"openid_connect/_verify.py","file_name":"_verify.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"58768628","text":"import os\nimport sys\nimport shutil\nimport glob\nimport pdb\n\n\ndef read_data_dir(source_dir):\n wav_list = glob.glob(source_dir + \"/T*/*/*.wav\")\n return wav_list\n\ndef utt2x_to_x2utt(utt2x_dict):\n x2utt_dict = {}\n for utt, x in utt2x_dict.items():\n if not x in x2utt_dict:\n x2utt_dict[x] = []\n x2utt_dict[x].append(utt)\n return x2utt_dict\n\ndef analysis_wav_list(wav_list):\n wav_scp_dic = {}\n utt2spk_dic = {}\n\n for wav in wav_list:\n spk = wav.split('/')[-3]\n utt = wav.split('/')[-1][:-4]\n \n wav_scp_dic[utt] = wav\n utt2spk_dic[utt] = spk\n spk2utt_dic = utt2x_to_x2utt(utt2spk_dic)\n return wav_scp_dic, utt2spk_dic, spk2utt_dic\n\ndef output(output_dir, wav_scp_dic, utt2spk_dic, spk2utt_dic):\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n \n # wav_scp\n h_file = open(os.path.join(output_dir, 'wav.scp'),'w')\n for utt in sorted(wav_scp_dic.keys()):\n h_file.write(\"%s %s\\n\" % (utt, wav_scp_dic[utt]))\n h_file.close()\n\n # utt2spk\n h_file = open(os.path.join(output_dir, 'utt2spk'),'w')\n for utt in sorted(utt2spk_dic.keys()):\n h_file.write(\"%s %s\\n\" % (utt, utt2spk_dic[utt]))\n h_file.close()\n\n # spk2utt\n h_file = open(os.path.join(output_dir, 'spk2utt'),'w')\n for spk in sorted(spk2utt_dic.keys()):\n h_file.write(\"%s %s\\n\" % (spk, \" \".join(spk2utt_dic[spk])))\n h_file.close()\n\ndef main():\n source_dir = sys.argv[1]\n output_dir = sys.argv[2]\n\n wav_list = read_data_dir(source_dir)\n\n wav_scp_dic, utt2spk_dic, spk2utt_dic = analysis_wav_list(wav_list)\n output(output_dir, wav_scp_dic, utt2spk_dic, spk2utt_dic)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"local/prepare_train_data.py","file_name":"prepare_train_data.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"311440451","text":"import logging, verboselogs\nimport sys\nimport inspect\nfrom datetime import datetime\n\nfrom obspy.core import UTCDateTime\n\ndef setup_log(stream_log_level=logging.INFO):\n global logger\n ts = datetime.today().strftime('%Y%m%dT%H%M')\n logging.basicConfig(filename=f'run_{ts}.log',\n # format='%(asctime)s %(caller)-25s %(levelname)-8s %(message)s',\n format='%(asctime)s %(levelname)-8s %(message)s',\n datefmt='%m-%d %H:%M',\n filemode='w',\n level=logging.VERBOSE)\n console = logging.StreamHandler()\n console.setLevel(stream_log_level)\n f = logging.Formatter('%(levelname)-8s %(message)s')\n console.setFormatter(f)\n logger = verboselogs.VerboseLogger('')\n logger.addHandler(logging.getLogger(''))\n # logger = logging.getLogger('')\n if len(logger.handlers) == 1:\n logger.addHandler(console)\n else:\n logger.handlers[1] = console\n\ndef log(string, level=\"info\"):\n \"\"\"\n Prints a string and logs to file\n\n :param level: the log level\n \"\"\"\n global logger\n caller = inspect.stack()[1]\n caller_str = caller[3] + '()'\n level = level.upper()\n extra = {'caller':caller_str}\n if level == \"INFO\":\n #print(bc.BRIGHTGREEN + full_str + bc.RESET)\n logger.info(string, extra=extra)\n elif level == \"VERBOSE\":\n logger.verbose(string, extra=extra)\n elif level == \"DEBUG\":\n logger.debug(string, extra=extra)\n elif level == \"ERROR\":\n logger.error(string, extra=extra)\n elif level == 'WARNING':\n logger.warning(string, extra=extra)\n elif level == 'CRITICAL':\n logger.critical(string, extra=extra)\n else:\n logger.warning(string, extra=extra)\n # sys.stdout.flush()\n\n\nclass bc:\n RED = '\\033[30m'\n BRIGHTRED = '\\033[1;31m'\n BRIGHTGREEN = '\\033[0;32m'\n BRIGHTYELLOW = '\\033[1;33m'\n BRIGHTBLUE = '\\033[1;34m'\n BRIGHTMAGENTA = '\\033[1;35m'\n BRIGHTCYAN = '\\033[1;36m'\n BRIGHTWHITE = '\\033[1;37m'\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n RESET = '\\033[0m'\n ENDC = '\\033[1;m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n","sub_path":"build/lib/ps_picker/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"491700514","text":"\n\nfrom xai.brain.wordbase.nouns._climb import _CLIMB\n\n#calss header\nclass _CLIMBS(_CLIMB, ):\n\tdef __init__(self,): \n\t\t_CLIMB.__init__(self)\n\t\tself.name = \"CLIMBS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"climb\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_climbs.py","file_name":"_climbs.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"152018034","text":"import sys,random\nimport pygame\n\n\nclass Jeu:\n # contenir toutes les variables ainsi que les fonctions utiles pour le bon deroulement du jeu\n\n def __init__(self):\n \"\"\"\n\n :rtype: object\n \"\"\"\n self.ecran = pygame.display.set_mode((800, 600))# defini la resoultion de la fenetre ,tuple(longueur,largeur)\n\n pygame.display.set_caption('Jeu Snake')# attribue un titre a la fenetre\n self.jeu_encours = True\n\n # creer les variables de position et de direction du serpent\n self.serpent_position_x = 300\n self.serpent_position_y = 300\n self.serpent_direction_x = 0\n self.serpent_direction_y = 0\n self.serpent_corps = 10\n\n # cree la position pour la pomme\n\n self.pomme_position_x = random.randrange(110,690,10)\n self.pomme_position_y = random.randrange(110,590,10)\n self.pomme = 10\n # fixer les fps\n self.clock = pygame.time.Clock()\n\n #creer une liste qui rescence toutes les positions du serpent\n self.positions_serpent = []\n\n # creer la variable en rapport avec la taille du serpent\n self.taille_du_serpent = 1\n\n self.ecran_du_debut = True\n\n self.image_tete_serpent = pygame.image.load('la_tete_du_serpent.png')\n\n\n # Charger l'image\n\n self.image = pygame.image.load('snake-game.jpg')\n # retrecir l'image\n self.image_titre = pygame.transform.scale(self.image,(200,100))\n\n # creer la variable score\n\n\n self.score = 0\n\n def fonction_principale(self):\n\n # permet de gerer les evenements , d'afficher certains composants du jeu grace au while loop\n\n while self.ecran_du_debut:\n\n for evenement in pygame.event.get():# verifier les evenements lorsque le jeu est en cours\n #print(evenement)\n if evenement.type == pygame.QUIT:\n sys.exit()\n\n if evenement.type == pygame.KEYDOWN:\n if evenement.key == pygame.K_RETURN:\n\n self.ecran_du_debut = False\n\n self.ecran.fill((0,0,0))\n\n self.ecran.blit(self.image_titre,(300,50,100,50))\n #self.creer_message('petite','Snake',(300,300,100,50),(255,255,255))\n self.creer_message('petite','Le but du jeu est que le serpent se développe '\n , (250, 200, 200, 5), (240, 240, 240))\n self.creer_message('petite',' pour cela , il a besoin de pomme ,mangez-en autant que possible !!',\n (190, 220, 200, 5), (240, 240, 240))\n self.creer_message('moyenne','Appuyer sur Enter pour commencer', (200, 450, 200, 5),\n (255, 255, 255))\n\n pygame.display.flip()\n\n\n\n\n while self.jeu_encours:\n\n # creer un while loop pour creer l'ecran de debut /events /afficher l'image ...\n\n for evenement in pygame.event.get():# verifier les evenements lorsque le jeu est en cours\n #print(evenement)\n if evenement.type == pygame.QUIT:\n sys.exit()\n\n # creer les evenements qui permettent de bouger le serpent\n\n if evenement.type == pygame.KEYDOWN:\n\n if evenement.key == pygame.K_RIGHT:\n # lorsque l'on presse la touche 'fleche droite'\n self.serpent_direction_x = 10\n self.serpent_direction_y = 0\n #print('Droite')\n\n if evenement.key == pygame.K_LEFT:\n # lorsque l'on presse la touche 'fleche gauche'\n\n self.serpent_direction_x = -10\n self.serpent_direction_y = 0\n #print('LEFT')\n\n if evenement.key == pygame.K_DOWN:\n # lorsque l'on presse la touche 'fleche vers le bas'\n\n self.serpent_direction_y = 10\n self.serpent_direction_x = 0\n #print('En bas')\n\n if evenement.key == pygame.K_UP:\n # lorsque l'on presse la touche 'fleche vers le haut'\n\n self.serpent_direction_y = -10\n self.serpent_direction_x = 0\n #print('En haut ')\n\n\n\n # faire bouger le serpent si il se trouve dans les limites du jeu\n\n if self.serpent_position_x <= 100 or self.serpent_position_x >= 700 \\\n or self.serpent_position_y <= 100 or self.serpent_position_y >= 600 :\n # si la position du serpent depasse les limites alors le jeu s'arrete\n sys.exit()\n\n\n\n\n self.serpent_mouvement()\n\n # cree la cond si le serpent mange la pomme\n\n if self.pomme_position_y == self.serpent_position_y and self.serpent_position_x == self.pomme_position_x:\n\n print('ok')\n\n self.pomme_position_x = random.randrange(110,690,10)\n self.pomme_position_y = random.randrange(110,590,10)\n\n # augmenter la taille du serpent\n\n self.taille_du_serpent += 1\n #augmenter le score\n self.score += 1\n\n # creer une liste pour les qui stocke la position de la tete du serpent\n la_tete_du_serpent = []\n la_tete_du_serpent.append(self.serpent_position_x)\n la_tete_du_serpent.append(self.serpent_position_y)\n\n\n # append dans la liste des positions du serpent\n\n self.positions_serpent.append(la_tete_du_serpent)\n\n # cond pour resoudre le probleme des positions du serpent avec la taille du serpent\n if len(self.positions_serpent) > self.taille_du_serpent:\n\n self.positions_serpent.pop(0)\n print(self.positions_serpent)\n\n\n self.afficher_les_elements()\n self.se_mord(la_tete_du_serpent)\n\n self.creer_message('grande','Snake Game', (320, 10, 100, 50), (255, 255, 255), )\n self.creer_message('grande','{}'.format(str(self.score)), (375, 50, 50, 50), (255, 255, 255), )\n\n # afficher les limites\n self.creer_limites()\n self.clock.tick(30)\n\n pygame.display.flip()# mettre a jour l'ecran\n\n\n # creer une fonction qui permet de creer un rectangle qui representera les limites du jeu (dimension 100,100,600,500),3\n\n\n def creer_limites(self):\n # afficher les limites du jeu\n\n pygame.draw.rect(self.ecran,(255,255,255),(100,100,600,500),3)\n\n def serpent_mouvement(self):\n\n # faire bouger le serpent\n\n self.serpent_position_x += self.serpent_direction_x # faire bouger le serpent a gauche ou a droite\n self.serpent_position_y += self.serpent_direction_y # faire bouger le serpent en haut ou en bas\n\n # print(self.serpent_position_x,self.serpent_position_y)\n\n\n def afficher_les_elements(self):\n\n self.ecran.fill((0, 0, 0)) # attriubue la couleur noir a l'ecran\n\n # Afficher le serpent\n #pygame.draw.rect(self.ecran, (0, 255, 0), (self.serpent_position_x, self.serpent_position_y,\n #self.serpent_corps, self.serpent_corps))\n\n self.ecran.blit(self.image_tete_serpent,(self.serpent_position_x,self.serpent_position_y,\n self.serpent_corps,self.serpent_corps))\n\n # afficher la pomme\n pygame.draw.rect(self.ecran, (255, 0, 0),\n (self.pomme_position_x, self.pomme_position_y, self.pomme, self.pomme))\n\n self.afficher_Serpent()\n\n\n def afficher_Serpent(self):\n # afficher les autres parties du serpent\n\n for partie_du_serpent in self.positions_serpent[:-1]:\n pygame.draw.rect(self.ecran, (0, 255, 0),\n (partie_du_serpent[0], partie_du_serpent[1], self.serpent_corps, self.serpent_corps))\n\n def se_mord(self,tete_serpent):\n\n\n # le seprent se mord\n\n for partie_serpent in self.positions_serpent[:-1]:\n if partie_serpent == tete_serpent :\n sys.exit()\n# creer une fonction qui permet d'afficher des messages\n\n def creer_message(self,font,message,message_rectangle,couleur):\n\n if font == 'petite':\n font = pygame.font.SysFont('Lato',20,False)\n\n elif font == 'moyenne':\n font = pygame.font.SysFont('Lato',30,False)\n\n elif font == 'grande':\n font = pygame.font.SysFont('Lato',40,True)\n\n message = font.render(message,True,couleur)\n\n self.ecran.blit(message,message_rectangle)\n\n\n\n\n\n\n\n\n\n\n\n\n# creer une fonction qui permet d'afficher les messages\n\n\n\nif __name__ == '__main__':\n\n pygame.init()# initie pygame\n Jeu().fonction_principale()\n pygame.quit()# quitte pygame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"417220245","text":"\nfrom random import randint\nfrom common.node import Node\nfrom common.cluster import Cluster\nimport common.distances as dists\nimport common.centroidformulas as centrform\n\ndef kmeans(nodes, k, similarity_func=dists.euclidean, avg_func=centrform.numericalmean):\n oldclusters = random_clusters(nodes, k, avg_func)\n matrix = [[0 for _ in range(k)] for _ in range(len(nodes))]\n hasfinished = False\n while not hasfinished:\n calculate_distances(nodes, oldclusters, matrix, similarity_func)\n newclusters = reallocate_nodes(nodes, oldclusters, matrix, avg_func)\n if theres_an_empty_cluster(newclusters):\n newclusters = random_clusters(nodes, k, avg_func)\n hasfinished = False\n else:\n hasfinished = no_cluster_has_changed(oldclusters, newclusters)\n oldclusters = newclusters\n return oldclusters\n\ndef random_clusters(nodes, k, avg_func):\n clusters = [Cluster([nodes[randint(0, len(nodes) - 1)]], avg_func) for _ in range(k)]\n return clusters\n\ndef calculate_distances(nodes, clusters, matrix, similarity_func):\n k = len(clusters)\n for i in range(len(nodes)):\n for j in range(len(clusters)):\n centroid = clusters[j].centr\n matrix[i][j] = similarity_func(nodes[i], centroid)\n\ndef theres_an_empty_cluster(clusters):\n answers = [x.is_empty() for x in clusters]\n return any(answers)\n\ndef no_cluster_has_changed(oldclusters, newclusters):\n answers = [x == y for x, y in zip(oldclusters, newclusters)]\n return all(answers)\n\ndef reallocate_nodes(nodes, clusters, matrix, avg_func):\n k = len(clusters)\n nodes_per_cluster = [[] for _ in range(k)]\n for i in range(len(nodes)):\n similarities = matrix[i]\n minimum = min(similarities)\n indexof = similarities.index(minimum)\n nodes_per_cluster[indexof].append(nodes[i])\n newclusters = [Cluster(nds, avg_func) for nds in nodes_per_cluster]\n return newclusters\n","sub_path":"kmeans/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":1960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"349256999","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\n\nfrom odoo import models, fields, api\n\n\nclass FourriereFourriere(models.TransientModel):\n _name = \"quitance.wizard\"\n\n num_quitance = fields.Char('Numéro de quitance')\n date_quitance = fields.Date('Date quitance', default=fields.Datetime.today())\n doc_quitance = fields.Binary('Document de quitance')\n\n def act_validate(self):\n if self._context.get('active_id', False):\n fourriere_id = self.env['fourriere.fourriere'].browse(self._context['active_id'])\n fourriere_id.write({\n 'date_out': self.date_quitance,\n 'num_quitance': self.num_quitance,\n 'doc_quitance': self.doc_quitance,\n 'state': 'sortit'\n })\n","sub_path":"fourriere/wizard/quitance_wizard.py","file_name":"quitance_wizard.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"446834744","text":"#Función de tratamiento del fichero de configuración de la red .configuración\n\nfrom auxiliares import *\n\ndef leeconf():\n\n conf_salida = [] #A devolver\n volcado = []\n fichero = open('red.conf', \"r\")\n\n paradalectura = False\n while not paradalectura:\n linea = fichero.readline()\n if linea!='':\n if linea!='\\n' and linea[0]!='#':\n volcado.append(linea) #no hay else\n else:\n paradalectura = True\n fichero.close()\n\n #Ahora proceso el volcado:\n\n #Separo los números\n datos = []\n for linea in volcado:\n aux = []\n troceado0 = linea.split('\\n') #Primero separo por el retorno de carro.\n troceado1 = troceado0[0].split('#') #Permito comentarios en la misma línea.\n troceado2 = troceado1[0].split(' ') #troceo la linea usando espacios\n for elem in troceado2:\n if num_valido(elem): #sin else\n aux.append(elem)\n\n datos.append(aux)\n \n\n #Ajusto y compruebo correctitud.\n\n capas_o=0\n if len(datos)==9: #numero de elementos correctos, no deben faltar ni sobrar.\n\n if len(datos[0])==1 and datos[0][0].isdigit() and int(datos[0][0])>=0 : #el numero de capas es correcto\n capas_o=int(datos[0][0])\n conf_salida.append(capas_o) #<--Vuelco primer dato\n\n #Compruebo que haya tantos datos como se indican en las capas.\n if len(datos[1])==capas_o: \n aux=[]\n for num in datos[1]:\n if num.isdigit():\n aux.append(int(num))\n else:\n conf_salida = -1\n break\n if conf_salida!=-1: # <-- Si no ha habido ningun error, vuelco los datos.\n conf_salida.append(aux) \n\n elif len(datos[1])==1 and datos[1][0]=='0' and capas_o == 0: #Para el caso particular de que haya 0 capas\n conf_salida.append(0)\n else:\n conf_salida = -1 \n\n #compruebo biases\n if conf_salida!=-1:\n if len(datos[2])==capas_o+1:\n datos[2] = [float(x) for x in datos[2]]\n conf_salida.append(datos[2])\n else:\n conf_salida=-1\n\n #compruebo conex\n if conf_salida!=-1:\n if len(datos[3])==capas_o+1:\n datos[3] = [float(x) for x in datos[3]]\n conf_salida.append(datos[3])\n else:\n conf_salida=-1\n\n\n #compruebo factor de aprendizaje\n if conf_salida!=-1:\n if len(datos[4])==1:\n conf_salida.append(float(datos[4][0]))\n else:\n conf_salida=-1\n\n #compruebo cota umbral\n if conf_salida!=-1:\n if len(datos[5])==1:\n conf_salida.append(float(datos[5][0]))\n else:\n conf_salida=-1\n \n #compruebo iteraciones\n if conf_salida!=-1:\n if len(datos[6])==1:\n conf_salida.append(int(datos[6][0]))\n else:\n conf_salida=-1\n\n #compruebo factor compresión\n if conf_salida!=-1:\n if len(datos[7])==1 and int(datos[7][0])>0:\n conf_salida.append(int(datos[7][0]))\n else:\n conf_salida=-1\n \n #compruebo momentum\n if conf_salida!=-1:\n if len(datos[8])==1 and float(datos[8][0])>0.0 and float(datos[8][0])<1.0:\n conf_salida.append(float(datos[8][0]))\n else:\n conf_salida=-1\n\n else:\n conf_salida = -1\n \n else:\n conf_salida = -1\n\n return conf_salida","sub_path":"Desarrollo/Algoritmo_con_momentum/lectorconf.py","file_name":"lectorconf.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"414968146","text":"import FWCore.ParameterSet.Config as cms\n\n\n# Energy scale corrections and MC smearing\n# from EgammaCalibratedGsfElectrons.CalibratedElectronProducers.calibratedGsfElectrons_cfi import calibratedGsfElectrons as gsfElectrons\n# gsfElectrons.updateEnergyError = cms.bool(True)\n# gsfElectrons.isAOD = cms.bool(True)\n# RandomNumberGeneratorService = cms.Service(\"RandomNumberGeneratorService\",\n# gsfElectrons = cms.PSet(\n# initialSeed = cms.untracked.uint32(1),\n# engineName = cms.untracked.string('TRandom3')\n# ),\n# )\n\n# prepare reco information\n# from PhysicsTools.PatAlgos.recoLayer0.electronId_cff import *\nfrom PhysicsTools.PatAlgos.recoLayer0.electronIsolation_cff import *\n\n\n# add PAT specifics\nfrom PhysicsTools.PatAlgos.mcMatchLayer0.electronMatch_cfi import *\nfrom PhysicsTools.PatAlgos.producersLayer1.electronProducer_cfi import *\n\nmakePatElectrons = cms.Sequence(\n # reco pre-production\n # patElectronId *\n # patElectronIsolation *\n # pat specifics\n electronMatch *\n # object production\n patElectrons\n )\n\n\nfrom PhysicsTools.PatAlgos.selectionLayer1.electronSelector_cfi import selectedPatElectrons\n\n# from PhysicsTools.PatAlgos.patSequences_cff import *\n\nfrom CMGTools.Common.PAT.patLeptModifiedIsoDeposit_cff import *\n\n# NOTE dunno why this is needed, but necessary to run on V5 PFAOD\n# - Taejeong?\npatElectrons.pfElectronSource = 'particleFlow'\n\n# PF isolation\n\nfrom CommonTools.ParticleFlow.Isolation.pfElectronIsolation_cff import *\n\n# 44X need to remove spurious sequences from the path\nfrom CMGTools.Common.Tools.cmsswRelease import cmsswIs44X\nif cmsswIs44X():\n pfElectronIsolationSequence.remove( pfElectronIsoDepositsSequence )\n pfElectronIsolationSequence.remove( pfElectronIsolationFromDepositsSequence )\n\nsourceElectrons = 'gsfElectrons'\n\nelPFIsoDepositCharged.src = sourceElectrons\nelPFIsoDepositChargedAll.src = sourceElectrons\nelPFIsoDepositNeutral.src = sourceElectrons\nelPFIsoDepositGamma.src = sourceElectrons\nelPFIsoDepositPU.src = sourceElectrons\n\nelPFIsoDepositCharged.ExtractorPSet.DR_Max = 0.5\nelPFIsoDepositChargedAll.ExtractorPSet.DR_Max = 0.5\nelPFIsoDepositNeutral.ExtractorPSet.DR_Max = 0.5\nelPFIsoDepositGamma.ExtractorPSet.DR_Max = 0.5\nelPFIsoDepositPU.ExtractorPSet.DR_Max = 0.5\n\n\npatElectrons.isoDeposits = cms.PSet(\n pfChargedHadrons = cms.InputTag(\"elPFIsoDepositCharged\" ),\n pfChargedAll = cms.InputTag(\"elPFIsoDepositChargedAll\" ),\n pfPUChargedHadrons = cms.InputTag(\"elPFIsoDepositPU\" ),\n pfNeutralHadrons = cms.InputTag(\"elPFIsoDepositNeutral\" ),\n pfPhotons = cms.InputTag(\"elPFIsoDepositGamma\" ),\n tracker = cms.InputTag(\"eleIsoDepositTk\")\n )\n\nelectronUserIsolation = cms.PSet(\n user = cms.VPSet(\n cms.PSet( src = cms.InputTag(\"eleIsoFromDepsTkOptimized5\") ),\n cms.PSet( src = cms.InputTag(\"eleIsoFromDepsTkOptimized7\") ),\n ) \n)\n\npatElectrons.isolationValues = cms.PSet(\n pfChargedHadrons = cms.InputTag(\"elPFIsoValueCharged04PFId\"),\n pfChargedAll = cms.InputTag(\"elPFIsoValueChargedAll04PFId\"),\n pfPUChargedHadrons = cms.InputTag(\"elPFIsoValuePU04PFId\" ),\n pfNeutralHadrons = cms.InputTag(\"elPFIsoValueNeutral04PFId\" ),\n pfPhotons = cms.InputTag(\"elPFIsoValueGamma04PFId\" ),\n )\n\npatElectrons.userIsolation.user = electronUserIsolation.user\n\n#NOTE the following should not be used for now, but we keep them just in case.\npatElectrons.isolationValuesNoPFId = cms.PSet(\n pfChargedHadrons = cms.InputTag(\"elPFIsoValueCharged04NoPFId\"),\n pfChargedAll = cms.InputTag(\"elPFIsoValueChargedAll04NoPFId\"),\n pfPUChargedHadrons = cms.InputTag(\"elPFIsoValuePU04NoPFId\" ),\n pfNeutralHadrons = cms.InputTag(\"elPFIsoValueNeutral04NoPFId\" ),\n pfPhotons = cms.InputTag(\"elPFIsoValueGamma04NoPFId\" )\n )\n\n# identification\n\nfrom CMGTools.Common.PAT.patElectronID_cff import *\npatElectrons.addElectronID = True\nfrom CMGTools.Common.PAT.electronIDs_cfi import electronIDs\npatElectrons.electronIDSources = electronIDs.clone()\n\npatElectrons.embedTrack = True\n\nselectedPatElectrons.cut = 'pt()>0'\n\nfrom CMGTools.Common.PAT.patElectronsWithTrigger_cff import * \n# from CMGTools.Common.PAT.patElectronsWithMVA_cfi import * \nfrom CMGTools.Common.PAT.patElectronsWithRegressionVars_cfi import * \nfrom CMGTools.Common.PAT.patElectronsWithRegression_cfi import * \nfrom CMGTools.Common.PAT.patElectronsWithCalibrations_cfi import * \nfrom CMGTools.Common.PAT.patElectronsWithMomenta_cfi import * \nfrom CMGTools.Common.PAT.patElectronsWithDirectionalIsolation_cfi import * \n\n\n\n# conversions\nfrom CMGTools.Common.PAT.patConversions_cfi import patConversions\n\nPATElectronSequence = cms.Sequence(\n pfElectronIsolationSequence +\n detElectronIsoDepositSequence + \n patElectronIDSequence + \n makePatElectrons +\n selectedPatElectrons + \n # patElectronsWithMVA + # not used, and creates problem in git migration\n patElectronsWithDirectionalIsolation +\n patElectronsWithRegressionVars +\n patElectronsWithRegression +\n patElectronsWithCalibrations +\n patElectronsWithMomenta +\n patElectronsWithTriggerSequence +\n patConversions \n )\n\n# Skip this since calibration can now be applied on the cmgTuples\n# if cmsswIs44X():\n# PATElectronSequence.insert( 0, gsfElectrons )\n","sub_path":"CMGTools/Common/python/PAT/PATElectrons_cff.py","file_name":"PATElectrons_cff.py","file_ext":"py","file_size_in_byte":5245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"554942007","text":"# -*- encoding:utf-8 -*-\n\nimport sys\nimport os\nimport time\n\nUPPER_ALPHA = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nDID_ALPHA_IDX = [0, 0, 0, 0, 0]\n\nDID_FORMAT = \"DEVUPUS-000029-\"\nINITSTRING_FORMAT = \"EBGCFGBJKDJMGAJPECGEFGEJHMMJHHNOGDFFBJCKBGJOLDLBDNALCBOHGBLAJNLBAGMALHDDOAMHABCNJINBIEAO:devuplus19kn\"\nTEST_MODE = 0\nPROGRAM_NAME = \"ReadWriteTester64\"\n\nif __name__ == \"__main__\":\n\tMODE = TEST_MODE\n\tINITSTRING = INITSTRING_FORMAT\n\t\n\tstart_time = time.time()\n\twhile(True):\n\t\tfor i in range(4, 0, -1):\n\t\t\tif DID_ALPHA_IDX[i] == 26:\n\t\t\t\tDID_ALPHA_IDX[i] = 0\n\t\t\t\tDID_ALPHA_IDX[i-1] += 1\n\t\tDID_ALPHA = \"\".join([UPPER_ALPHA[i] for i in DID_ALPHA_IDX])\n\t\t\n\t\tret = os.system(\"./{} {} {} {}\".format(PROGRAM_NAME, MODE, DID_FORMAT + DID_ALPHA, INITSTRING))\n\t\t\n\t\tDID_ALPHA_IDX[-1] += 1\n\t\tprint(\"\\n\")\n","sub_path":"bruteforce_p2pid_2.py","file_name":"bruteforce_p2pid_2.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"24864498","text":"#!/usr/bin/env python\n\n#\n# Run frames on different streams through a reader/writer tray, verify that extra\n# cruft doesn't get in to the files\n#\nfrom icecube import icetray, dataclasses, dataio\nimport sys\n\n#\n# Generate .i3 file\n#\n\ni3f = dataio.I3File(\"tmp3.i3\", 'w')\n\nstreams = ['A', 'B', 'C', 'D', 'E', 'F']\n\nfor st in streams:\n print(\"=====%s=====\" % st)\n theframe = icetray.I3Frame(icetray.I3Frame.Stream(st))\n theframe[st] = icetray.I3Int(ord(st))\n\n i3f.push(theframe)\n\ni3f.close()\n\ni3f2 = dataio.I3File(\"tmp3.i3\")\n\nframe = i3f2.pop_frame(icetray.I3Frame.Stream('N'))\n\nprint(frame)\nassert frame\nstop = frame.Stop\nassert stop.id == 'A'\n\nframe = i3f2.pop_frame()\nassert frame\nprint(frame)\nassert frame.Stop.id == 'B'\n\nframe = i3f2.pop_frame(icetray.I3Frame.Stream('C'))\nassert frame\nprint(frame)\nassert frame.Stop.id == 'C'\n\nframe = i3f2.pop_frame()\nassert frame\nprint(frame)\nassert frame.Stop.id == 'D'\n\n# verify that rewind works\nwhile(i3f2.more()):\n i3f2.pop_frame()\n\ni3f2.rewind()\nassert i3f2.more()\ni3f2.pop_frame()\n\n\n\n\n\n","sub_path":"dataio/resources/test/pop_frame.py","file_name":"pop_frame.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"427519585","text":"import numpy as np\n\narray = np.array([[[1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3]]])\n\narray_trans = np.sum(array, axis=2)\n\na = np.array([1,2,3])\n\nb = a.reshape(-1,1)\n\nc = b.reshape(1,3)\n\nprint(\"debug\")\n","sub_path":"numpy_1.py","file_name":"numpy_1.py","file_ext":"py","file_size_in_byte":204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"47194496","text":"def sentence_seg(para):\n sentence = []\n quote = re.split(r'(\\w*:?“.*?”\\D*\\W?|\\w*:?\".*?\"\\D*\\W?|\\w*【.*?】\\D*\\W?|{.*?}\\D*\\W?)',para,re.M) # 将带引用符号的子句拆分,本数据集中只有这四种引用符\n\n for q in quote:\n f = re.search(r'[‘|“|【|\\[|\\(|\\'|\\\"]',q) # 对不带引用符号的句子进一步拆分\n if f == None:\n q = re.sub('([,。;!?])(.*?)', r\"\\1\\n\\2\",q,re.M) # 按中文标点拆分\n q = re.sub('(.*)(\\d\\.\\.*)',r\"\\1\\n\\2\",q,re.M) # 将形如“1.balabala”的句子拆开\n q = q.split('\\n')\n for s in q:\n if s != '':\n sentence.append(s)\n else:\n sentence.append(q)\n return sentence\n\n","sub_path":"HW/NLP/code/sentence_seg.py","file_name":"sentence_seg.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"288984246","text":"import gym\nfrom gym import error, spaces, utils\nfrom gym.utils import seeding\n\nimport sys\nfrom six import StringIO\nimport numpy as np\n\nMAP = [\n \"+-------------+\",\n \"| |\",\n \"| ==>=A=>== |\",\n \"| = = |\",\n \"| = = |\",\n \"| = = |\",\n \"| =<==B=<== |\",\n \"| |\",\n \"+-------------+\",\n]\n\nclass RailwayEnv(gym.Env):\n metadata = {'render.modes': ['human']}\n\n def __init__(self):\n self.desc = np.asarray(MAP, dtype='c')\n self.locs = locs = [(1,4), (5,4)]\n\n def step(self, action):\n ...\n def reset(self):\n ...\n def render(self, mode='human'):\n outfile = StringIO() if mode == 'ansi' else sys.stdout\n\n out = self.desc.copy().tolist()\n out = [[c.decode('utf-8') for c in line] for line in out]\n\n outfile.write(\"\\n\".join([\"\".join(row) for row in out]) + \"\\n\")\n\n def close(self):\n ...\n","sub_path":"gym-railway/gym_railway/envs/railway_env.py","file_name":"railway_env.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"396722822","text":"import pandas as pd\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA\nfrom sklearn.preprocessing import StandardScaler\nimport cv2 as cv\nfrom skimage import feature\nfrom sklearn.utils import shuffle\n\n\nimage_size = 28\nnumber_class = 10\nimage_shape = (image_size, image_size)\nimage_size_flat = image_size*image_size\n\n\ndef read_data():\n train = pd.read_csv('train.csv')\n test = pd.read_csv('test.csv')\n label = train['label']\n train = train.drop(\"label\", axis=1)\n # print(train.shape, label.shape)\n return label, train, test\n\n\ndef one_hot(y):\n m = []\n for i in y:\n xx = np.zeros((10))\n xx[i] = 1\n m.append(xx)\n return np.array(m)\n\n\ndef weights(shape, mu=0, std=0.05):\n return tf.Variable(tf.truncated_normal(shape, mu, std), dtype=tf.float32)\n\n\ndef biases(length, value=0):\n return tf.Variable(tf.constant(value, dtype=tf.float32, shape=[length]), dtype=tf.float32)\n\n\ndef new_fc_layer(input, num_inputs, num_outputs, activation=\"no\"):\n Wi = weights(shape=[num_inputs, num_outputs])\n Bi = biases(length=num_outputs)\n layer = tf.matmul(input, Wi) + Bi\n if activation==\"softmax\":\n layer = tf.nn.softmax(input)\n elif activation==\"relu\":\n layer = tf.nn.relu(layer)\n elif activation==\"sigmoid\":\n layer = tf.nn.sigmoid(layer)\n elif activation==\"tanh\":\n layer = tf.nn.tanh(layer)\n elif activation==\"leaky\":\n layer = tf.nn.leaky_relu(layer)\n return layer, Wi, Bi\n\n\ndef model(X_train, Y_train, X_test, learning_rate=0.875):\n x = tf.placeholder(tf.float32, [None, image_size_flat], name=\"x\")\n y = tf.placeholder(tf.float32, [None, number_class], name='y')\n layer1, W1, B1 = new_fc_layer(input=x, num_inputs=X_train.shape[1], num_outputs=number_class, activation=\"no\")\n layer2, _, _ = new_fc_layer(input=layer1, num_inputs=number_class, num_outputs=number_class, activation=\"softmax\")\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=layer1, labels=y)\n regularizer = tf.nn.l2_loss(W1)\n # beta = 1e-7\n cost = tf.reduce_mean(cross_entropy)\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n session = tf.Session()\n session.run(tf.global_variables_initializer())\n correct_prediction = tf.equal(layer2, y)\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n def print_accuracy(feed, val=True):\n acc = session.run(accuracy, feed_dict=feed)\n if val:\n print(\"Accuracy on val-set: {0:.3%}\".format(acc))\n else:\n print(\"Accuracy on train-set: {0:.3%}\".format(acc))\n return acc\n\n def optimize(num_iterations, learning_rate):\n acc = []\n abb = []\n for i in range(num_iterations):\n print(\"===============================================\")\n print(\"epoch \", i+1)\n print(\"learning_rate\", learning_rate)\n print(\"===============================================\")\n if i % 50 is 0 and i is not 0:\n rng_state = np.random.get_state()\n np.random.shuffle(X_train)\n np.random.set_state(rng_state)\n np.random.shuffle(Y_train)\n\n # X_train, Y_train = shuffle(X_train, Y_train)\n feed_dict_train = {x: X_train[:41000, :], y: Y_train[:41000]}\n feed_dict_val = {x: X_train[41000:, :], y: Y_train[41000:]}\n feed_dict = {x: X_train, y: Y_train}\n session.run(optimizer, feed_dict=feed_dict)\n acc.append(print_accuracy(feed_dict))\n # abb.append(print_accuracy(feed_dict_train, False))\n if i % 25 is 0 and i is not 0:\n learning_rate /= 2\n if i is 50:\n learning_rate=0.875\n # plt.plot(np.arange(0, len(abb)), abb, 'r')\n plt.plot(np.arange(0, len(acc)), acc, 'b')\n plt.show()\n optimize(100, learning_rate)\n preds = session.run(tf.argmax(layer2, axis=1), feed_dict={x: X_test})\n pd.DataFrame({\"ImageId\": list(range(1, len(preds) + 1)), \"Label\": preds}).to_csv(\"MLP_baby.csv\", index=False, header=True)\n session.close()\n\n\ndef main():\n class_label, train_image, test_image = read_data()\n X_train = train_image.values\n Y_train = class_label.values\n # X_train_normalized = (X_train-np.mean(X_train))/np.std(X_train)\n # print(np.histogram(Y_train[41000:]))\n X_test = test_image.values\n Y_train = one_hot(Y_train)\n model(X_train=X_train, Y_train=Y_train, X_test=X_test)\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"arrow.py","file_name":"arrow.py","file_ext":"py","file_size_in_byte":4690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"540678139","text":"class Solution(object):\n def firstMissingPositive(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if (len(nums) == 0):\n return 1\n minNr = 0\n ct = 0;\n map = {minNr: minNr + 1}\n\n while ct < len(nums):\n crt = nums[ct]\n if crt >= 0:\n map[crt] = crt + 1\n ct = ct + 1\n\n crt = minNr + 1\n\n while True:\n if crt in map:\n crt = map[crt]\n else:\n return crt\n\n\ns = Solution()\nprint(s.firstMissingPositive([-2,-4,-1]))","sub_path":"41_firstMissingPositive.py","file_name":"41_firstMissingPositive.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"622717779","text":"import os\nimport vtk, qt, ctk, slicer\nimport logging\nfrom SegmentEditorEffects import *\nimport numpy as np\nfrom RFReconstruction import RFReconstructionLogic\nfrom RFViewerHomeLib import ExportDirectorySettings\n# from oct2py import *\n# from SegmentEditorSurfaceCutLib import SegmentEditorEffect\n\n@slicer.util.translatable\nclass SegmentEditorThresholdEffect(AbstractScriptedSegmentEditorEffect):\n \"\"\" ThresholdEffect is an Effect implementing the global threshold\n operation in the segment editor\n\n This is also an example for scripted effects, and some methods have no\n function. The methods that are not needed (i.e. the default implementation in\n qSlicerSegmentEditorAbstractEffect is satisfactory) can simply be omitted.\n \"\"\"\n\n def __init__(self, scriptedEffect):\n AbstractScriptedSegmentEditorEffect.__init__(self, scriptedEffect)\n scriptedEffect.name = 'Threshold'\n\n self.segment2DFillOpacity = None\n self.segment2DOutlineOpacity = None\n self.previewedSegmentID = None\n\n # Effect-specific members\n import vtkITK\n self.autoThresholdCalculator = vtkITK.vtkITKImageThresholdCalculator()\n\n self.timer = qt.QTimer()\n self.previewState = 0\n self.previewStep = 1\n self.previewSteps = 5\n self.timer.connect('timeout()', self.preview)\n\n self.previewPipelines = {}\n self.histogramPipeline = None\n self.setupPreviewDisplay()\n\n # Histogram stencil setup\n self.stencil = vtk.vtkPolyDataToImageStencil()\n\n # Histogram reslice setup\n self.reslice = vtk.vtkImageReslice()\n self.reslice.AutoCropOutputOff()\n self.reslice.SetOptimization(1)\n self.reslice.SetOutputOrigin(0, 0, 0)\n self.reslice.SetOutputSpacing(1, 1, 1)\n self.reslice.SetOutputDimensionality(3)\n self.reslice.GenerateStencilOutputOn()\n\n self.imageAccumulate = vtk.vtkImageAccumulate()\n self.imageAccumulate.SetInputConnection(0, self.reslice.GetOutputPort())\n self.imageAccumulate.SetInputConnection(1, self.stencil.GetOutputPort())\n\n self.selectionStartPosition = None\n self.selectionEndPosition = None\n\n def clone(self):\n import qSlicerSegmentationsEditorEffectsPythonQt as effects\n clonedEffect = effects.qSlicerSegmentEditorScriptedEffect(None)\n clonedEffect.setPythonSource(__file__.replace('\\\\','/'))\n return clonedEffect\n\n def icon(self):\n iconPath = os.path.join(os.path.dirname(__file__), 'Resources/Icons/Threshold.png')\n if os.path.exists(iconPath):\n return qt.QIcon(iconPath)\n return qt.QIcon()\n\n def helpText(self):\n# return self.tr(\"\"\"Fill segment based on master volume intensity range
. Options:

\n#

\"\"\")\n return \"\"\n\n def activate(self):\n \n self.setCurrentSegmentTransparent()\n\n # Update intensity range\n self.masterVolumeNodeChanged()\n\n # Setup and start preview pulse\n self.setupPreviewDisplay()\n self.timer.start(200)\n\n def deactivate(self):\n self.restorePreviewedSegmentTransparency()\n\n # Clear preview pipeline and stop timer\n self.clearPreviewDisplay()\n self.clearHistogramDisplay()\n self.timer.stop()\n\n def setCurrentSegmentTransparent(self):\n \"\"\"Save current segment opacity and set it to zero\n to temporarily hide the segment so that threshold preview\n can be seen better.\n It also restores opacity of previously previewed segment.\n Call restorePreviewedSegmentTransparency() to restore original\n opacity.\n \"\"\"\n segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode()\n if not segmentationNode:\n return\n displayNode = segmentationNode.GetDisplayNode()\n if not displayNode:\n return\n segmentID = self.scriptedEffect.parameterSetNode().GetSelectedSegmentID()\n\n if segmentID == self.previewedSegmentID:\n # already previewing the current segment\n return\n\n # If an other segment was previewed before, restore that.\n if self.previewedSegmentID:\n self.restorePreviewedSegmentTransparency()\n\n # Make current segment fully transparent\n if segmentID:\n self.segment2DFillOpacity = displayNode.GetSegmentOpacity2DFill(segmentID)\n self.segment2DOutlineOpacity = displayNode.GetSegmentOpacity2DOutline(segmentID)\n self.previewedSegmentID = segmentID\n displayNode.SetSegmentOpacity2DFill(segmentID, 0)\n displayNode.SetSegmentOpacity2DOutline(segmentID, 0)\n\n def restorePreviewedSegmentTransparency(self):\n \"\"\"Restore previewed segment's opacity that was temporarily\n made transparen by calling setCurrentSegmentTransparent().\"\"\"\n segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode()\n if not segmentationNode:\n return\n displayNode = segmentationNode.GetDisplayNode()\n if not displayNode:\n return\n if not self.previewedSegmentID:\n # already previewing the current segment\n return\n displayNode.SetSegmentOpacity2DFill(self.previewedSegmentID, self.segment2DFillOpacity)\n displayNode.SetSegmentOpacity2DOutline(self.previewedSegmentID, self.segment2DOutlineOpacity)\n self.previewedSegmentID = None\n\n def setupOptionsFrame(self):\n self.thresholdSliderLabel = qt.QLabel(self.tr(\"Threshold Range:\"))\n self.thresholdSliderLabel.setToolTip(self.tr(\"Set the range of the background values that should be labeled.\"))\n self.scriptedEffect.addOptionsWidget(self.thresholdSliderLabel)\n\n self.thresholdSlider = ctk.ctkRangeWidget()\n self.thresholdSlider.spinBoxAlignment = qt.Qt.AlignTop\n self.thresholdSlider.singleStep = 0.01\n self.scriptedEffect.addOptionsWidget(self.thresholdSlider)\n # add\n # self.thresholdSlider.minimumValue = -500\n # self.thresholdSlider.maximumValue = 100\n \n self.thresholdSlider1 = ctk.ctkRangeWidget()\n self.thresholdSlider1.spinBoxAlignment = qt.Qt.AlignTop\n self.thresholdSlider1.singleStep = 1\n self.scriptedEffect.addOptionsWidget(self.thresholdSlider1)\n \n self.autoThresholdModeSelectorComboBox = qt.QComboBox()\n self.autoThresholdModeSelectorComboBox.addItem(self.tr(\"auto->maximum\"), MODE_SET_LOWER_MAX)\n self.autoThresholdModeSelectorComboBox.addItem(self.tr(\"minimum->auto\"), MODE_SET_MIN_UPPER)\n self.autoThresholdModeSelectorComboBox.addItem(self.tr(\"as lower\"), MODE_SET_LOWER)\n self.autoThresholdModeSelectorComboBox.addItem(self.tr(\"as upper\"), MODE_SET_UPPER)\n self.autoThresholdModeSelectorComboBox.setToolTip(self.tr(\n \"How to set lower and upper threshold values. Current refers to keeping the current value.\"))\n self.autoThresholdModeSelectorComboBox.hide()\n self.autoThresholdMethodSelectorComboBox = qt.QComboBox()\n self.autoThresholdMethodSelectorComboBox.addItem(self.tr(\"Otsu\"), METHOD_OTSU)\n self.autoThresholdMethodSelectorComboBox.addItem(self.tr(\"Huang\"), METHOD_HUANG)\n self.autoThresholdMethodSelectorComboBox.addItem(self.tr(\"IsoData\"), METHOD_ISO_DATA)\n # Kittler-Illingworth sometimes fails with an exception, but it does not cause any major issue,\n # it just logs an error message and does not compute a new threshold value\n self.autoThresholdMethodSelectorComboBox.addItem(self.tr(\"Kittler-Illingworth\"), METHOD_KITTLER_ILLINGWORTH)\n # Li sometimes crashes (index out of range error in\n # ITK/Modules/Filtering/Thresholding/include/itkLiThresholdCalculator.hxx#L94)\n # We can add this method back when issue is fixed in ITK.\n #self.autoThresholdMethodSelectorComboBox.addItem(\"Li\", METHOD_LI)\n self.autoThresholdMethodSelectorComboBox.addItem(self.tr(\"Maximum entropy\"), METHOD_MAXIMUM_ENTROPY)\n self.autoThresholdMethodSelectorComboBox.addItem(self.tr(\"Moments\"), METHOD_MOMENTS)\n self.autoThresholdMethodSelectorComboBox.addItem(self.tr(\"Renyi entropy\"), METHOD_RENYI_ENTROPY)\n self.autoThresholdMethodSelectorComboBox.addItem(self.tr(\"Shanbhag\"), METHOD_SHANBHAG)\n self.autoThresholdMethodSelectorComboBox.addItem(self.tr(\"Triangle\"), METHOD_TRIANGLE)\n self.autoThresholdMethodSelectorComboBox.addItem(self.tr(\"Yen\"), METHOD_YEN)\n self.autoThresholdMethodSelectorComboBox.addItem(self.tr(\"Custom\"), METHOD_CUSTOM)\n self.autoThresholdMethodSelectorComboBox.setToolTip(self.tr(\n \"Select method to compute threshold value automatically.\"))\n # self.autoThresholdMethodSelectorComboBox.hide()\n self.selectPreviousAutoThresholdButton = qt.QToolButton()\n self.selectPreviousAutoThresholdButton.text = \"<\"\n self.selectPreviousAutoThresholdButton.setToolTip(self.tr(\n \"Select previous thresholding method and set thresholds. Useful for iterating through all available methods.\"))\n\n self.selectNextAutoThresholdButton = qt.QToolButton()\n self.selectNextAutoThresholdButton.text = \">\"\n self.selectNextAutoThresholdButton.setToolTip(self.tr(\n \"Select next thresholding method and set thresholds. Useful for iterating through all available methods.\"))\n\n self.setAutoThresholdButton = qt.QPushButton(self.tr(\"Set\"))\n self.setAutoThresholdButton.setToolTip(self.tr(\"Set threshold using selected method.\"))\n\n # qt.QSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Expanding)\n # fails on some systems, therefore set the policies using separate method calls\n qSize = qt.QSizePolicy()\n qSize.setHorizontalPolicy(qt.QSizePolicy.Expanding)\n self.setAutoThresholdButton.setSizePolicy(qSize)\n\n autoThresholdFrame = qt.QHBoxLayout()\n autoThresholdFrame.addWidget(self.autoThresholdModeSelectorComboBox)\n autoThresholdFrame.addWidget(self.autoThresholdMethodSelectorComboBox)\n autoThresholdFrame.addWidget(self.selectPreviousAutoThresholdButton)\n autoThresholdFrame.addWidget(self.selectNextAutoThresholdButton)\n autoThresholdFrame.addWidget(self.setAutoThresholdButton)\n\n autoThresholdGroupBox = ctk.ctkCollapsibleGroupBox()\n autoThresholdGroupBox.setTitle(self.tr(\"Automatic threshold\"))\n autoThresholdGroupBox.setLayout(autoThresholdFrame)\n autoThresholdGroupBox.collapsed = True\n self.scriptedEffect.addOptionsWidget(autoThresholdGroupBox)\n # autoThresholdGroupBox.hide()\n histogramFrame = qt.QVBoxLayout()\n\n histogramBrushFrame = qt.QHBoxLayout()\n histogramFrame.addLayout(histogramBrushFrame)\n\n self.histogramBrushButtonGroup = qt.QButtonGroup()\n self.histogramBrushButtonGroup.setExclusive(True)\n\n self.boxROIButton = qt.QPushButton()\n self.boxROIButton.setText(self.tr(\"Box\"))\n self.boxROIButton.setCheckable(True)\n self.boxROIButton.clicked.connect(self.updateMRMLFromGUI)\n histogramBrushFrame.addWidget(self.boxROIButton)\n self.histogramBrushButtonGroup.addButton(self.boxROIButton)\n\n self.circleROIButton = qt.QPushButton()\n self.circleROIButton.setText(self.tr(\"Circle\"))\n self.circleROIButton.setCheckable(True)\n self.circleROIButton.clicked.connect(self.updateMRMLFromGUI)\n histogramBrushFrame.addWidget(self.circleROIButton)\n self.histogramBrushButtonGroup.addButton(self.circleROIButton)\n\n self.drawROIButton = qt.QPushButton()\n self.drawROIButton.setText(self.tr(\"Draw\"))\n self.drawROIButton.setCheckable(True)\n self.drawROIButton.clicked.connect(self.updateMRMLFromGUI)\n histogramBrushFrame.addWidget(self.drawROIButton)\n self.histogramBrushButtonGroup.addButton(self.drawROIButton)\n\n self.lineROIButton = qt.QPushButton()\n self.lineROIButton.setText(self.tr(\"Line\"))\n self.lineROIButton.setCheckable(True)\n self.lineROIButton.clicked.connect(self.updateMRMLFromGUI)\n histogramBrushFrame.addWidget(self.lineROIButton)\n self.histogramBrushButtonGroup.addButton(self.lineROIButton)\n\n self.histogramView = ctk.ctkTransferFunctionView()\n histogramFrame.addWidget(self.histogramView)\n scene = self.histogramView.scene()\n\n self.histogramFunction = vtk.vtkPiecewiseFunction()\n self.histogramFunctionContainer = ctk.ctkVTKPiecewiseFunction(self.scriptedEffect)\n self.histogramFunctionContainer.setPiecewiseFunction(self.histogramFunction)\n self.histogramFunctionItem = ctk.ctkTransferFunctionBarsItem(self.histogramFunctionContainer)\n self.histogramFunctionItem.barWidth = 1.0\n self.histogramFunctionItem.logMode = ctk.ctkTransferFunctionBarsItem.NoLog\n self.histogramFunctionItem.setZValue(1)\n scene.addItem(self.histogramFunctionItem)\n\n self.histogramEventFilter = HistogramEventFilter()\n self.histogramEventFilter.setThresholdEffect(self)\n self.histogramFunctionItem.installEventFilter(self.histogramEventFilter)\n\n self.minMaxFunction = vtk.vtkPiecewiseFunction()\n self.minMaxFunctionContainer = ctk.ctkVTKPiecewiseFunction(self.scriptedEffect)\n self.minMaxFunctionContainer.setPiecewiseFunction(self.minMaxFunction)\n self.minMaxFunctionItem = ctk.ctkTransferFunctionBarsItem(self.minMaxFunctionContainer)\n self.minMaxFunctionItem.barWidth = 0.03\n self.minMaxFunctionItem.logMode = ctk.ctkTransferFunctionBarsItem.NoLog\n self.minMaxFunctionItem.barColor = qt.QColor(200, 0, 0)\n self.minMaxFunctionItem.setZValue(0)\n scene.addItem(self.minMaxFunctionItem)\n\n self.averageFunction = vtk.vtkPiecewiseFunction()\n self.averageFunctionContainer = ctk.ctkVTKPiecewiseFunction(self.scriptedEffect)\n self.averageFunctionContainer.setPiecewiseFunction(self.averageFunction)\n self.averageFunctionItem = ctk.ctkTransferFunctionBarsItem(self.averageFunctionContainer)\n self.averageFunctionItem.barWidth = 0.03\n self.averageFunctionItem.logMode = ctk.ctkTransferFunctionBarsItem.NoLog\n self.averageFunctionItem.barColor = qt.QColor(225, 150, 0)\n self.averageFunctionItem.setZValue(-1)\n scene.addItem(self.averageFunctionItem)\n\n # Window level gradient\n self.backgroundColor = [1.0, 1.0, 0.7]\n self.backgroundFunction = vtk.vtkColorTransferFunction()\n self.backgroundFunctionContainer = ctk.ctkVTKColorTransferFunction(self.scriptedEffect)\n self.backgroundFunctionContainer.setColorTransferFunction(self.backgroundFunction)\n self.backgroundFunctionItem = ctk.ctkTransferFunctionGradientItem(self.backgroundFunctionContainer)\n self.backgroundFunctionItem.setZValue(-2)\n scene.addItem(self.backgroundFunctionItem)\n\n histogramItemFrame = qt.QHBoxLayout()\n histogramFrame.addLayout(histogramItemFrame)\n\n ###\n # Lower histogram threshold buttons\n\n lowerGroupBox = qt.QGroupBox(self.tr(\"Lower\"))\n lowerHistogramLayout = qt.QHBoxLayout()\n lowerGroupBox.setLayout(lowerHistogramLayout)\n histogramItemFrame.addWidget(lowerGroupBox)\n self.histogramLowerMethodButtonGroup = qt.QButtonGroup()\n self.histogramLowerMethodButtonGroup.setExclusive(True)\n\n self.histogramLowerThresholdMinimumButton = qt.QPushButton()\n self.histogramLowerThresholdMinimumButton.setText(self.tr(\"Minimum\"))\n self.histogramLowerThresholdMinimumButton.setCheckable(True)\n self.histogramLowerThresholdMinimumButton.clicked.connect(self.updateMRMLFromGUI)\n lowerHistogramLayout.addWidget(self.histogramLowerThresholdMinimumButton)\n self.histogramLowerMethodButtonGroup.addButton(self.histogramLowerThresholdMinimumButton)\n\n self.histogramLowerThresholdLowerButton = qt.QPushButton()\n self.histogramLowerThresholdLowerButton.setText(self.tr(\"Lower\"))\n self.histogramLowerThresholdLowerButton.setCheckable(True)\n self.histogramLowerThresholdLowerButton.clicked.connect(self.updateMRMLFromGUI)\n lowerHistogramLayout.addWidget(self.histogramLowerThresholdLowerButton)\n self.histogramLowerMethodButtonGroup.addButton(self.histogramLowerThresholdLowerButton)\n\n self.histogramLowerThresholdAverageButton = qt.QPushButton()\n self.histogramLowerThresholdAverageButton.setText(self.tr(\"Average\"))\n self.histogramLowerThresholdAverageButton.setCheckable(True)\n self.histogramLowerThresholdAverageButton.clicked.connect(self.updateMRMLFromGUI)\n lowerHistogramLayout.addWidget(self.histogramLowerThresholdAverageButton)\n self.histogramLowerMethodButtonGroup.addButton(self.histogramLowerThresholdAverageButton)\n\n lowerGroupBox.hide()\n ###\n # Upper histogram threshold buttons\n\n upperGroupBox = qt.QGroupBox(self.tr(\"Upper\"))\n upperHistogramLayout = qt.QHBoxLayout()\n upperGroupBox.setLayout(upperHistogramLayout)\n histogramItemFrame.addWidget(upperGroupBox)\n self.histogramUpperMethodButtonGroup = qt.QButtonGroup()\n self.histogramUpperMethodButtonGroup.setExclusive(True)\n\n self.histogramUpperThresholdAverageButton = qt.QPushButton()\n self.histogramUpperThresholdAverageButton.setText(self.tr(\"Average\"))\n self.histogramUpperThresholdAverageButton.setCheckable(True)\n self.histogramUpperThresholdAverageButton.clicked.connect(self.updateMRMLFromGUI)\n upperHistogramLayout.addWidget(self.histogramUpperThresholdAverageButton)\n self.histogramUpperMethodButtonGroup.addButton(self.histogramUpperThresholdAverageButton)\n\n self.histogramUpperThresholdUpperButton = qt.QPushButton()\n self.histogramUpperThresholdUpperButton.setText(self.tr(\"Upper\"))\n self.histogramUpperThresholdUpperButton.setCheckable(True)\n self.histogramUpperThresholdUpperButton.clicked.connect(self.updateMRMLFromGUI)\n upperHistogramLayout.addWidget(self.histogramUpperThresholdUpperButton)\n self.histogramUpperMethodButtonGroup.addButton(self.histogramUpperThresholdUpperButton)\n\n self.histogramUpperThresholdMaximumButton = qt.QPushButton()\n self.histogramUpperThresholdMaximumButton.setText(self.tr(\"Maximum\"))\n self.histogramUpperThresholdMaximumButton.setCheckable(True)\n self.histogramUpperThresholdMaximumButton.clicked.connect(self.updateMRMLFromGUI)\n upperHistogramLayout.addWidget(self.histogramUpperThresholdMaximumButton)\n self.histogramUpperMethodButtonGroup.addButton(self.histogramUpperThresholdMaximumButton)\n \n upperGroupBox.hide()\n\n histogramGroupBox = ctk.ctkCollapsibleGroupBox()\n histogramGroupBox.setTitle(self.tr(\"Local histogram\"))\n histogramGroupBox.setLayout(histogramFrame)\n histogramGroupBox.collapsed = True\n self.scriptedEffect.addOptionsWidget(histogramGroupBox)\n # histogramGroupBox.hide()\n self.useForPaintButton = qt.QPushButton(self.tr(\"Use for masking\"))\n self.useForPaintButton.setToolTip(self.tr(\"Use specified intensity range for masking and switch to Paint effect.\"))\n self.scriptedEffect.addOptionsWidget(self.useForPaintButton)\n # self.useForPaintButton.hide()\n \n \n self.applyButton = qt.QPushButton(\"Apply\")\n self.applyButton.objectName = self.__class__.__name__ + 'Apply'\n self.applyButton.setToolTip(self.tr(\"Fill selected segment in regions that are in the specified intensity range.\"))\n self.scriptedEffect.addOptionsWidget(self.applyButton)\n\n self.useForPaintButton.connect('clicked()', self.onUseForPaint)\n self.thresholdSlider.connect('valuesChanged(double,double)', self.onThresholdValuesChanged)\n self.thresholdSlider1.connect('valuesChanged(double,double)', self.onThresholdValuesChanged1)\n self.autoThresholdMethodSelectorComboBox.connect(\"activated(int)\", self.onSelectedAutoThresholdMethod)\n self.autoThresholdModeSelectorComboBox.connect(\"activated(int)\", self.onSelectedAutoThresholdMethod)\n self.selectPreviousAutoThresholdButton.connect('clicked()', self.onSelectPreviousAutoThresholdMethod)\n self.selectNextAutoThresholdButton.connect('clicked()', self.onSelectNextAutoThresholdMethod)\n self.setAutoThresholdButton.connect('clicked()', self.onAutoThreshold)\n self.applyButton.connect('clicked()', self.onApply)\n\n\n # add\n self.thresholdSlider1.setRange(0, 1000)\n self.thresholdSlider1.minimumValue = 10\n self.thresholdSlider1.maximumValue = 200\n \n self.maxvalue = 200\n self.minvalue = 10\n\n def createCursor(self, widget):\n # Turn off effect-specific cursor for this effect\n return slicer.util.mainWindow().cursor\n\n def masterVolumeNodeChanged(self):\n # Set scalar range of master volume image data to threshold slider\n import vtkSegmentationCorePython as vtkSegmentationCore\n masterImageData = self.scriptedEffect.masterVolumeImageData()\n \n if masterImageData:\n lo, hi = masterImageData.GetScalarRange()\n # print(\"lo\")\n # print(lo)\n # print(hi)\n if lo < -10000:\n lo = -10000\n if hi > 20000:\n hi = 20000 \n lo = lo / 10\n hi = hi / 10 \n self.thresholdSlider.setRange(lo, hi)\n self.thresholdSlider.singleStep = (hi - lo) / 1000.\n if (self.scriptedEffect.doubleParameter(\"MinimumThreshold\") == self.scriptedEffect.doubleParameter(\"MaximumThreshold\")):\n # has not been initialized yet\n self.scriptedEffect.setParameter(\"MinimumThreshold\", (lo+(hi-lo)*0.25) * 10)\n self.scriptedEffect.setParameter(\"MaximumThreshold\", hi * 10)\n # self.thresholdSlider1.setRange(0,10000)\n def layoutChanged(self):\n self.setupPreviewDisplay()\n\n def setMRMLDefaults(self):\n self.scriptedEffect.setParameterDefault(\"MinimumThreshold\", 0.)\n self.scriptedEffect.setParameterDefault(\"MaximumThreshold\", 0)\n self.scriptedEffect.setParameterDefault(\"AutoThresholdMethod\", METHOD_OTSU)\n self.scriptedEffect.setParameterDefault(\"AutoThresholdMode\", MODE_SET_LOWER_MAX)\n self.scriptedEffect.setParameterDefault(HISTOGRAM_BRUSH_TYPE_PARAMETER_NAME, HISTOGRAM_BRUSH_TYPE_CIRCLE)\n self.scriptedEffect.setParameterDefault(HISTOGRAM_SET_LOWER_PARAMETER_NAME, HISTOGRAM_SET_LOWER)\n self.scriptedEffect.setParameterDefault(HISTOGRAM_SET_UPPER_PARAMETER_NAME, HISTOGRAM_SET_UPPER)\n\n def updateGUIFromMRML(self):\n self.thresholdSlider.blockSignals(True)\n self.thresholdSlider.setMinimumValue(self.scriptedEffect.doubleParameter(\"MinimumThreshold\") / 10)\n self.thresholdSlider.setMaximumValue(self.scriptedEffect.doubleParameter(\"MaximumThreshold\") / 10)\n self.thresholdSlider.blockSignals(False)\n\n autoThresholdMethod = self.autoThresholdMethodSelectorComboBox.findData(self.scriptedEffect.parameter(\"AutoThresholdMethod\"))\n wasBlocked = self.autoThresholdMethodSelectorComboBox.blockSignals(True)\n self.autoThresholdMethodSelectorComboBox.setCurrentIndex(autoThresholdMethod)\n self.autoThresholdMethodSelectorComboBox.blockSignals(wasBlocked)\n\n autoThresholdMode = self.autoThresholdModeSelectorComboBox.findData(self.scriptedEffect.parameter(\"AutoThresholdMode\"))\n wasBlocked = self.autoThresholdModeSelectorComboBox.blockSignals(True)\n self.autoThresholdModeSelectorComboBox.setCurrentIndex(autoThresholdMode)\n self.autoThresholdModeSelectorComboBox.blockSignals(wasBlocked)\n\n histogramBrushType = self.scriptedEffect.parameter(HISTOGRAM_BRUSH_TYPE_PARAMETER_NAME)\n self.boxROIButton.checked = (histogramBrushType == HISTOGRAM_BRUSH_TYPE_BOX)\n self.circleROIButton.checked = (histogramBrushType == HISTOGRAM_BRUSH_TYPE_CIRCLE)\n self.drawROIButton.checked = (histogramBrushType == HISTOGRAM_BRUSH_TYPE_DRAW)\n self.lineROIButton.checked = (histogramBrushType == HISTOGRAM_BRUSH_TYPE_LINE)\n\n histogramSetModeLower = self.scriptedEffect.parameter(HISTOGRAM_SET_LOWER_PARAMETER_NAME)\n self.histogramLowerThresholdMinimumButton.checked = (histogramSetModeLower == HISTOGRAM_SET_MINIMUM)\n self.histogramLowerThresholdLowerButton.checked = (histogramSetModeLower == HISTOGRAM_SET_LOWER)\n self.histogramLowerThresholdAverageButton.checked = (histogramSetModeLower == HISTOGRAM_SET_AVERAGE)\n\n histogramSetModeUpper = self.scriptedEffect.parameter(HISTOGRAM_SET_UPPER_PARAMETER_NAME)\n self.histogramUpperThresholdAverageButton.checked = (histogramSetModeUpper == HISTOGRAM_SET_AVERAGE)\n self.histogramUpperThresholdUpperButton.checked = (histogramSetModeUpper == HISTOGRAM_SET_UPPER)\n self.histogramUpperThresholdMaximumButton.checked = (histogramSetModeUpper == HISTOGRAM_SET_MAXIMUM)\n\n self.updateHistogramBackground()\n\n def updateMRMLFromGUI(self):\n # add\n # self.thresholdSlider.minimumValue = 10\n # self.thresholdSlider.maximumValue = 20000\n with slicer.util.NodeModify(self.scriptedEffect.parameterSetNode()):\n # add\n # self.thresholdSlider.minimumValue = -500\n # self.thresholdSlider.maximumValue = 100\n # if self.thresholdSlider.minimumValue < 10:\n # self.thresholdSlider.minimumValue = 100\n # if self.thresholdSlider.maximumValue > 20000:\n # self.thresholdSlider.maximumValue = 20000\n self.scriptedEffect.setParameter(\"MinimumThreshold\", (self.thresholdSlider.minimumValue) * 10)\n self.scriptedEffect.setParameter(\"MaximumThreshold\", self.thresholdSlider.maximumValue * 10)\n\n methodIndex = self.autoThresholdMethodSelectorComboBox.currentIndex\n autoThresholdMethod = self.autoThresholdMethodSelectorComboBox.itemData(methodIndex)\n self.scriptedEffect.setParameter(\"AutoThresholdMethod\", autoThresholdMethod)\n\n modeIndex = self.autoThresholdModeSelectorComboBox.currentIndex\n autoThresholdMode = self.autoThresholdModeSelectorComboBox.itemData(modeIndex)\n self.scriptedEffect.setParameter(\"AutoThresholdMode\", autoThresholdMode)\n\n histogramParameterChanged = False\n\n histogramBrushType = HISTOGRAM_BRUSH_TYPE_CIRCLE\n if self.boxROIButton.checked:\n histogramBrushType = HISTOGRAM_BRUSH_TYPE_BOX\n elif self.circleROIButton.checked:\n histogramBrushType = HISTOGRAM_BRUSH_TYPE_CIRCLE\n elif self.drawROIButton.checked:\n histogramBrushType = HISTOGRAM_BRUSH_TYPE_DRAW\n elif self.lineROIButton.checked:\n histogramBrushType = HISTOGRAM_BRUSH_TYPE_LINE\n\n if histogramBrushType != self.scriptedEffect.parameter(HISTOGRAM_BRUSH_TYPE_PARAMETER_NAME):\n self.scriptedEffect.setParameter(HISTOGRAM_BRUSH_TYPE_PARAMETER_NAME, histogramBrushType)\n histogramParameterChanged = True\n\n histogramSetModeLower = HISTOGRAM_SET_LOWER\n if self.histogramLowerThresholdMinimumButton.checked:\n histogramSetModeLower = HISTOGRAM_SET_MINIMUM\n elif self.histogramLowerThresholdLowerButton.checked:\n histogramSetModeLower = HISTOGRAM_SET_LOWER\n elif self.histogramLowerThresholdAverageButton.checked:\n histogramSetModeLower = HISTOGRAM_SET_AVERAGE\n if histogramSetModeLower != self.scriptedEffect.parameter(HISTOGRAM_SET_LOWER_PARAMETER_NAME):\n self.scriptedEffect.setParameter(HISTOGRAM_SET_LOWER_PARAMETER_NAME, histogramSetModeLower)\n histogramParameterChanged = True\n\n histogramSetModeUpper = HISTOGRAM_SET_UPPER\n if self.histogramUpperThresholdAverageButton.checked:\n histogramSetModeUpper = HISTOGRAM_SET_AVERAGE\n elif self.histogramUpperThresholdUpperButton.checked:\n histogramSetModeUpper = HISTOGRAM_SET_UPPER\n elif self.histogramUpperThresholdMaximumButton.checked:\n histogramSetModeUpper = HISTOGRAM_SET_MAXIMUM\n if histogramSetModeUpper != self.scriptedEffect.parameter(HISTOGRAM_SET_UPPER_PARAMETER_NAME):\n self.scriptedEffect.setParameter(HISTOGRAM_SET_UPPER_PARAMETER_NAME, histogramSetModeUpper)\n histogramParameterChanged = True\n\n if histogramParameterChanged:\n self.updateHistogram()\n\n #\n # Effect specific methods (the above ones are the API methods to override)\n #\n def onThresholdValuesChanged(self,min,max):\n self.scriptedEffect.updateMRMLFromGUI()\n def onThresholdValuesChanged1(self,min,max):\n self.minvalue = min\n self.maxvalue = max\n def onUseForPaint(self):\n minimumSize = int(self.minvalue) * 1000 \n maximumSize = int(self.maxvalue) * 1000\n \n self.scriptedEffect.parameterSetNode().SetOverwriteMode(slicer.vtkMRMLSegmentEditorNode.OverwriteNone)\n \n # self.splitSegments(minimumSize = minimumSize, split = False)\n selectedSegmentID = self.scriptedEffect.parameterSetNode().GetSelectedSegmentID()\n segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode()\n air_segment_id = selectedSegmentID\n \n segmentation = segmentationNode.GetSegmentation()\n segmentEditorWidget = slicer.modules.segmenteditor.widgetRepresentation().self().editor\n segmentEditorWidget.setActiveEffectByName(\"Logical operators\")\n print(minimumSize)\n \n segment_id1 = segmentation.AddEmptySegment()\n segmentEditorWidget.setCurrentSegmentID(segment_id1)\n effect = segmentEditorWidget.activeEffect()\n effect.setParameter(\"Operation\", \"COPY\")\n effect.setParameter(\"ModifierSegmentID\", air_segment_id)\n effect.self().onApply()\n segmentEditorWidget.setActiveEffectByName(\"Islands\")\n effect = segmentEditorWidget.activeEffect()\n effect.setParameter(\"Operation\",\"REMOVE_SMALL_ISLANDS\")\n effect.setParameter(\"MinimumSize\", minimumSize)\n effect.setParameter(\"MaxNumberOfSegments\", 1000)\n effect.setParameter(\"Split\", False)\n effect.self().onApply()\n print(maximumSize)\n\n segment_id2 = segmentation.AddEmptySegment()\n segmentEditorWidget.setCurrentSegmentID(segment_id2)\n segmentEditorWidget.setActiveEffectByName(\"Logical operators\")\n effect = segmentEditorWidget.activeEffect()\n effect.setParameter(\"Operation\", \"COPY\")\n effect.setParameter(\"ModifierSegmentID\", air_segment_id)\n effect.self().onApply()\n segmentEditorWidget.setActiveEffectByName(\"Islands\")\n effect = segmentEditorWidget.activeEffect()\n effect.setParameter(\"Operation\",\"REMOVE_SMALL_ISLANDS\")\n effect.setParameter(\"MinimumSize\", maximumSize)\n effect.setParameter(\"MaxNumberOfSegments\", 1000)\n effect.setParameter(\"Split\", False)\n effect.self().onApply()\n \n\n result_id = segmentation.AddEmptySegment()\n segmentEditorWidget.setCurrentSegmentID(result_id)\n segmentEditorWidget.setActiveEffectByName('Logical operators')\n effect = segmentEditorWidget.activeEffect()\n effect.setParameter(\"Operation\", \"COPY\")\n effect.setParameter(\"ModifierSegmentID\", segment_id1)\n effect.self().onApply()\n effect.setParameter(\"Operation\", \"SUBTRACT\")\n effect.setParameter(\"ModifierSegmentID\", segment_id2) \n effect.self().onApply()\n \n\n # segmentationNode.RemoveSegment(air_segment_id)\n # segmentationNode.RemoveSegment(segment_id1)\n # segmentationNode.RemoveSegment(segment_id2)\n\n # self.scriptedEffect.parameterSetNode().SetOverwriteMode(slicer.vtkMRMLSegmentEditorNode.OverwriteVisibleSegments)\n # # selectedSegmentID = self.scriptedEffect.parameterSetNode().GetSelectedSegmentID()\n # segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode()\n # # segmentation = segmentationNode.GetSegmentation()\n # # selectedSegment = segmentation.GetSegment(selectedSegmentID)\n\n # slicer.util.selectModule('SegmentEditor')\n # segmentEditorWidget = slicer.modules.segmenteditor.widgetRepresentation().self().editor\n # segmentEditorWidget.setActiveEffectByName(\"Logical operators\")\n # effect = segmentEditorWidget.activeEffect()\n # # segmentationNode = getNode('Segmentation')\n # segmentation = segmentationNode.GetSegmentation()\n # air_segment_id = segmentation.GetSegmentIdBySegmentName(\"AirwaySegment\")\n\n # # air_segment_id = selectedSegmentID\n # print(air_segment_id)\n # low_to_max_segment_id = segmentation.AddEmptySegment()\n # segmentEditorWidget.setCurrentSegmentID(low_to_max_segment_id)\n # effect = segmentEditorWidget.activeEffect()\n # effect.setParameter(\"Operation\", \"COPY\")\n # effect.setParameter(\"ModifierSegmentID\", air_segment_id)\n # effect.self().onApply()\n # segmentEditorWidget.setActiveEffectByName(\"Islands\")\n # effect = segmentEditorWidget.activeEffect()\n # effect.setParameter(\"Operation\",\"REMOVE_SMALL_ISLANDS\")\n # effect.setParameter(\"MinimumSize\", minimumSize)\n # effect.self().onApply()\n # print(low_to_max_segment_id)\n # # all_id = segmentation.AddEmptySegment()\n # # segmentEditorWidget.setCurrentSegmentID(all_id)\n # # segmentEditorWidget.setActiveEffectByName('Logical operators')\n # # effect = segmentEditorWidget.activeEffect()\n # # effect.setParameter(\"Operation\", \"COPY\")\n # # effect.setParameter(\"ModifierSegmentID\", air_segment_id)\n # # effect.self().onApply()\n\n\n # high_to_max_segment_id = segmentation.AddEmptySegment()\n # segmentEditorWidget.setCurrentSegmentID(high_to_max_segment_id)\n # segmentEditorWidget.setActiveEffectByName('Logical operators')\n # effect = segmentEditorWidget.activeEffect()\n # effect.setParameter(\"Operation\", \"COPY\")\n # effect.setParameter(\"ModifierSegmentID\", air_segment_id)\n # effect.self().onApply()\n # print(high_to_max_segment_id)\n # segmentEditorWidget.setActiveEffectByName('Islands')\n # effect = segmentEditorWidget.activeEffect()\n # effect.setParameter('Operation','REMOVE_SMALL_ISLANDS')\n # effect.setParameter('MinimumSize', maximumSize)\n # effect.self().onApply()\n\n # all_id = segmentation.AddEmptySegment()\n # segmentEditorWidget.setCurrentSegmentID(all_id)\n # segmentEditorWidget.setActiveEffectByName('Logical operators')\n # effect = segmentEditorWidget.activeEffect()\n # effect.setParameter(\"Operation\", \"COPY\")\n # effect.setParameter(\"ModifierSegmentID\", air_segment_id)\n # effect.self().onApply()\n # segmentEditorWidget.setActiveEffectByName('Islands')\n # effect = segmentEditorWidget.activeEffect()\n # effect.setParameter('Operation','REMOVE_SMALL_ISLANDS')\n # effect.setParameter('MinimumSize', 10)\n # effect.self().onApply()\n\n # tmp_high_id = segmentation.AddEmptySegment()\n # segmentEditorWidget.setCurrentSegmentID(tmp_high_id)\n # segmentEditorWidget.setActiveEffectByName('Logical operators')\n # effect = segmentEditorWidget.activeEffect()\n # effect.setParameter(\"Operation\", \"COPY\")\n # effect.setParameter(\"ModifierSegmentID\", air_segment_id)\n # effect.self().onApply()\n # effect.setParameter(\"Operation\", \"SUBTRACT\")\n # effect.setParameter(\"ModifierSegmentID\", high_to_max_segment_id) \n # effect.self().onApply()\n\n # tmp_low_id = segmentation.AddEmptySegment()\n # segmentEditorWidget.setCurrentSegmentID(tmp_low_id)\n # segmentEditorWidget.setActiveEffectByName('Logical operators')\n # effect = segmentEditorWidget.activeEffect()\n # effect.setParameter(\"Operation\", \"COPY\")\n # effect.setParameter(\"ModifierSegmentID\", air_segment_id)\n # effect.self().onApply()\n # effect.setParameter(\"Operation\", \"SUBTRACT\")\n # effect.setParameter(\"ModifierSegmentID\", low_to_max_segment_id) \n # effect.self().onApply()\n\n # result_id = segmentation.AddEmptySegment()\n # segmentEditorWidget.setCurrentSegmentID(result_id)\n # segmentEditorWidget.setActiveEffectByName('Logical operators')\n # effect = segmentEditorWidget.activeEffect()\n # effect.setParameter(\"Operation\", \"COPY\")\n # effect.setParameter(\"ModifierSegmentID\", tmp_high_id)\n # effect.self().onApply()\n # effect.setParameter(\"Operation\", \"SUBTRACT\")\n # effect.setParameter(\"ModifierSegmentID\", tmp_low_id) \n # effect.self().onApply()\n\n # low_to_high_segment_id = segmentation.AddEmptySegment()\n # segmentEditorWidget.setCurrentSegmentID(low_to_high_segment_id)\n # segmentEditorWidget.setActiveEffectByName('Logical operators')\n # effect = segmentEditorWidget.activeEffect()\n # effect.setParameter(\"Operation\", \"COPY\")\n # effect.setParameter(\"ModifierSegmentID\", low_to_max_segment_id)\n # effect.self().onApply()\n # effect.setParameter(\"Operation\", \"SUBTRACT\")\n # effect.setParameter(\"ModifierSegmentID\", high_to_max_segment_id) \n # effect.self().onApply()\n\n # result_id = segmentation.AddEmptySegment()\n # segmentEditorWidget.setCurrentSegmentID(result_id)\n # segmentEditorWidget.setActiveEffectByName('Logical operators')\n # effect = segmentEditorWidget.activeEffect()\n # effect.setParameter(\"Operation\", \"COPY\")\n # effect.setParameter(\"ModifierSegmentID\", all_id)\n # effect.self().onApply()\n # effect.setParameter(\"Operation\", \"SUBTRACT\")\n # effect.setParameter(\"ModifierSegmentID\", low_to_high_segment_id) \n # effect.self().onApply()\n\n # segmentationNode.RemoveSegment(all_id)\n # segmentationNode.RemoveSegment(tmp_low_id)\n # segmentationNode.RemoveSegment(tmp_high_id)\n # segmentationNode.RemoveSegment(high_to_max_segment_id)\n # segmentationNode.RemoveSegment(low_to_max_segment_id)\n # segmentationNode.RemoveSegment(air_segment_id)\n\n # selectedSegment = segmentation.GetSegment(all_id)\n # selectedSegment.SetColor(0, 1, 0)\n # slicer.mrmlScene.RemoveNode(segmentationNode)\n\n \n #\n # Switch to segment editor and pick logical effects, and get the segment to work on.\n #\n # slicer.util.selectModule('SegmentEditor')\n # segmentEditorWidget = slicer.modules.segmenteditor.widgetRepresentation().self().editor\n # segmentEditorWidget.setActiveEffectByName(\"Logical operators\")\n # effect = segmentEditorWidget.activeEffect()\n \n # segmentationNode = slicer.mrmlScene.AddNewNodeByClass(\"vtkMRMLSegmentationNode\")\n # segmentationNode.CreateDefaultDisplayNodes() # only needed for display\n # segmentationNode.SetReferenceImageGeometryParameterFromVolumeNode(masterVolumeNode)\n # segmentation = segmentationNode.GetSegmentation()\n \n # air_segment_id = segmentationNode.GetSegmentation().AddEmptySegment(\"skin\")\n\n # #\n # # Make a low to max by coping original and removing islands smaller than low.\n # #\n # segmentation = segmentationNode.GetSegmentation()\n # low_to_max_segment_id = segmentation.AddEmptySegment()\n # segmentEditorWidget.setCurrentSegmentID(low_to_max_segment_id)\n # effect.setParameter(\"Operation\", \"COPY\")\n # effect.setParameter(\"ModifierSegmentID\", air_segment_id)\n # effect.self().onApply()\n # segmentEditorWidget.setActiveEffectByName('Islands')\n # effect = segmentEditorWidget.activeEffect()\n # effect.setParameter('Operation','REMOVE_SMALL_ISLANDS')\n # effect.setParameter('MinimumSize', low_island_size)\n # effect.self().onApply()\n\n # #\n # # Make a high to max in the same fashion.\n # #\n # high_to_max_segment_id = segmentation.AddEmptySegment()\n # segmentEditorWidget.setCurrentSegmentID(high_to_max_segment_id)\n # segmentEditorWidget.setActiveEffectByName('Logical operators')\n # effect = segmentEditorWidget.activeEffect()\n # effect.setParameter(\"Operation\", \"COPY\")\n # effect.setParameter(\"ModifierSegmentID\", air_segment_id)\n # effect.self().onApply()\n # segmentEditorWidget.setActiveEffectByName('Islands')\n # effect = segmentEditorWidget.activeEffect()\n # effect.setParameter('Operation','REMOVE_SMALL_ISLANDS')\n # effect.setParameter('MinimumSize', high_island_size)\n # effect.self().onApply()\n\n # #\n # # Finally, make a low to high segment bu subtracting high to max from low to max.\n # #\n # low_to_high_segment_id = segmentation.AddEmptySegment()\n # segmentEditorWidget.setCurrentSegmentID(low_to_high_segment_id)\n # segmentEditorWidget.setActiveEffectByName('Logical operators')\n # effect = segmentEditorWidget.activeEffect()\n # effect.setParameter(\"Operation\", \"COPY\")\n # effect.setParameter(\"ModifierSegmentID\", low_to_max_segment_id)\n # effect.self().onApply()\n # effect.setParameter(\"Operation\", \"SUBTRACT\")\n # effect.setParameter(\"ModifierSegmentID\", high_to_max_segment_id) \n # effect.self().onApply()\n\n # parameterSetNode = self.scriptedEffect.parameterSetNode()\n # parameterSetNode.MasterVolumeIntensityMaskOn()\n # self.scriptedEffect.setParameter(\"Operation\", \"FILL_OUTSIDE\")\n # parameterSetNode.SetMasterVolumeIntensityMaskRange(100, 2000)\n # masterVolumeNode = self.scriptedEffect.parameterSetNode().GetMasterVolumeNode()\n # self.scriptedEffect.setParameter(\"FillValue\", str(masterVolumeNode.GetImageData().GetScalarRange()[0]))\n # # Switch to paint effect\n # self.scriptedEffect.self().onApply()\n # segefforts = SegmentEditorLogicalEffect(self)\n # segefforts.setMRMLDefaults()\n # segefforts.onApply()\n # print(segefforts)\n def onSelectPreviousAutoThresholdMethod(self):\n self.autoThresholdMethodSelectorComboBox.currentIndex = (self.autoThresholdMethodSelectorComboBox.currentIndex - 1) \\\n % self.autoThresholdMethodSelectorComboBox.count\n self.onSelectedAutoThresholdMethod()\n\n def onSelectNextAutoThresholdMethod(self):\n self.autoThresholdMethodSelectorComboBox.currentIndex = (self.autoThresholdMethodSelectorComboBox.currentIndex + 1) \\\n % self.autoThresholdMethodSelectorComboBox.count\n self.onSelectedAutoThresholdMethod()\n\n def onSelectedAutoThresholdMethod(self):\n self.updateMRMLFromGUI()\n self.onAutoThreshold()\n self.updateGUIFromMRML()\n \n def onAutoThreshold(self):\n autoThresholdMethod = self.scriptedEffect.parameter(\"AutoThresholdMethod\")\n autoThresholdMode = self.scriptedEffect.parameter(\"AutoThresholdMode\")\n self.autoThreshold(autoThresholdMethod, autoThresholdMode)\n\n def autoThreshold(self, autoThresholdMethod, autoThresholdMode):\n if autoThresholdMethod == METHOD_HUANG:\n self.autoThresholdCalculator.SetMethodToHuang()\n elif autoThresholdMethod == METHOD_INTERMODES:\n self.autoThresholdCalculator.SetMethodToIntermodes()\n elif autoThresholdMethod == METHOD_ISO_DATA:\n self.autoThresholdCalculator.SetMethodToIsoData()\n elif autoThresholdMethod == METHOD_KITTLER_ILLINGWORTH:\n self.autoThresholdCalculator.SetMethodToKittlerIllingworth()\n elif autoThresholdMethod == METHOD_LI:\n self.autoThresholdCalculator.SetMethodToLi()\n elif autoThresholdMethod == METHOD_MAXIMUM_ENTROPY:\n self.autoThresholdCalculator.SetMethodToMaximumEntropy()\n elif autoThresholdMethod == METHOD_MOMENTS:\n self.autoThresholdCalculator.SetMethodToMoments()\n elif autoThresholdMethod == METHOD_OTSU:\n self.autoThresholdCalculator.SetMethodToOtsu()\n elif autoThresholdMethod == METHOD_RENYI_ENTROPY:\n self.autoThresholdCalculator.SetMethodToRenyiEntropy()\n elif autoThresholdMethod == METHOD_SHANBHAG:\n self.autoThresholdCalculator.SetMethodToShanbhag()\n elif autoThresholdMethod == METHOD_TRIANGLE:\n self.autoThresholdCalculator.SetMethodToTriangle()\n elif autoThresholdMethod == METHOD_YEN:\n self.autoThresholdCalculator.SetMethodToYen()\n elif autoThresholdMethod == METHOD_CUSTOM:\n self.autoThresholdCalculator.SetMethodToHuang()\n\n else:\n logging.error(\"Unknown AutoThresholdMethod {0}\".format(autoThresholdMethod))\n\n masterImageData = self.scriptedEffect.masterVolumeImageData()\n self.autoThresholdCalculator.SetInputData(masterImageData)\n\n self.autoThresholdCalculator.Update()\n computedThreshold = self.autoThresholdCalculator.GetThreshold()\n\n masterVolumeMin, masterVolumeMax = masterImageData.GetScalarRange()\n \n if autoThresholdMethod == METHOD_CUSTOM:\n mnri_file_path = os.path.join(ExportDirectorySettings.load(), \"NAOMICT_UTF8.mnri\")\n mnri_settings = RFReconstructionLogic.MNRISettings(mnri_file_path)\n GGOsettingvalue = qt.QSettings() # File must be next to RFViewer.ini\n selected_preset = int(mnri_settings.value('Frame/GGOSetting'))\n print(\"selected_preset\")\n print(GGOsettingvalue)\n print('GGOMin'+str(selected_preset))\n masterVolumeMin1 = float(GGOsettingvalue.value('GGOMin'+str(selected_preset), -80))\n print(GGOsettingvalue.value('GGOMin1'))\n masterVolumeMax1 = float(GGOsettingvalue.value('GGOMax'+str(selected_preset), -40))\n print(masterVolumeMax)\n # if masterVolumeMin < -100 :\n # masterVolumeMin = -100\n\n computedThreshold = computedThreshold / 10\n masterVolumeMin = masterVolumeMin / 10\n masterVolumeMax = masterVolumeMax / 10\n if autoThresholdMethod == METHOD_CUSTOM:\n computedThreshold = -10000\n computedThreshold = masterVolumeMin1 * 10\n\n masterVolumeMax = masterVolumeMax1 * 10\n masterVolumeMin = masterVolumeMin1 * 10\n if autoThresholdMode == MODE_SET_UPPER:\n self.scriptedEffect.setParameter(\"MaximumThreshold\", computedThreshold)\n elif autoThresholdMode == MODE_SET_LOWER:\n self.scriptedEffect.setParameter(\"MinimumThreshold\", computedThreshold)\n elif autoThresholdMode == MODE_SET_MIN_UPPER:\n self.scriptedEffect.setParameter(\"MinimumThreshold\", masterVolumeMin)\n self.scriptedEffect.setParameter(\"MaximumThreshold\", computedThreshold)\n elif autoThresholdMode == MODE_SET_LOWER_MAX:\n self.scriptedEffect.setParameter(\"MinimumThreshold\", computedThreshold)\n self.scriptedEffect.setParameter(\"MaximumThreshold\", masterVolumeMax)\n else:\n logging.error(\"Unknown AutoThresholdMode {0}\".format(autoThresholdMode))\n\n def onApply(self):\n try:\n # Get master volume image data\n import vtkSegmentationCorePython as vtkSegmentationCore\n masterImageData = self.scriptedEffect.masterVolumeImageData()\n # Get modifier labelmap\n modifierLabelmap = self.scriptedEffect.defaultModifierLabelmap()\n originalImageToWorldMatrix = vtk.vtkMatrix4x4()\n modifierLabelmap.GetImageToWorldMatrix(originalImageToWorldMatrix)\n # Get parameters\n min = self.scriptedEffect.doubleParameter(\"MinimumThreshold\")\n\n max = self.scriptedEffect.doubleParameter(\"MaximumThreshold\")\n\n self.scriptedEffect.saveStateForUndo()\n\n \n # Perform thresholding\n thresh = vtk.vtkImageThreshold()\n thresh.SetInputData(masterImageData)\n thresh.ThresholdBetween(min, max)\n thresh.SetInValue(1)\n thresh.SetOutValue(0)\n thresh.SetOutputScalarType(modifierLabelmap.GetScalarType())\n thresh.Update()\n modifierLabelmap.DeepCopy(thresh.GetOutput())\n\n except IndexError:\n logging.error('apply: Failed to threshold master volume!')\n pass\n\n # Apply changes\n self.scriptedEffect.modifySelectedSegmentByLabelmap(modifierLabelmap, slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet)\n\n # De-select effect\n self.scriptedEffect.selectEffect(\"\")\n \n masterVolumeNode = self.scriptedEffect.parameterSetNode().GetMasterVolumeNode()\n voxelArray = slicer.util.arrayFromVolume(masterVolumeNode)\n print(\"volumeArray:\")\n print(voxelArray)\n voxelMax = np.max(voxelArray) - 1\n voxelMin = np.min(voxelArray) + 1\n print(voxelMax)\n print(voxelMin)\n # voxelMax = np.maximum(voxelArray)\n # voxelMin = np.minimum(voxelArray)\n # print(voxelMax)\n # print(voxelMin)\n indices = np.where(voxelArray > voxelMax)\n numberOfVoxels = len(indices[0])\n print(numberOfVoxels)\n indices = np.where(voxelArray < voxelMin)\n numberOfVoxels = len(indices[0])\n print(numberOfVoxels)\n\n def splitSegments(self, minimumSize = 0, maxNumberOfSegments = 0, split = True):\n \"\"\"\n minimumSize: if 0 then it means that all islands are kept, regardless of size\n maxNumberOfSegments: if 0 then it means that all islands are kept, regardless of how many\n \"\"\"\n # This can be a long operation - indicate it to the user\n qt.QApplication.setOverrideCursor(qt.Qt.WaitCursor)\n\n self.scriptedEffect.saveStateForUndo()\n\n # Get modifier labelmap\n selectedSegmentLabelmap = self.scriptedEffect.selectedSegmentLabelmap()\n\n castIn = vtk.vtkImageCast()\n castIn.SetInputData(selectedSegmentLabelmap)\n castIn.SetOutputScalarTypeToUnsignedInt()\n\n # Identify the islands in the inverted volume and\n # find the pixel that corresponds to the background\n # islandMath = vtkITK.vtkITKIslandMath()\n # islandMath.SetInputConnection(castIn.GetOutputPort())\n # islandMath.SetFullyConnected(False)\n # islandMath.SetMinimumSize(minimumSize)\n # islandMath.SetMaximumSize(maximumSize)\n # islandMath.Update()\n # islandCount = islandMath.GetNumberOfIslands()\n # print(islandCount)\n\n # islandMath1 = vtkITK.vtkITKIslandMath()\n # islandMath1.SetInputConnection(castIn.GetOutputPort())\n # islandMath1.SetFullyConnected(False)\n # islandMath1.SetMinimumSize(maximumSize)\n # islandMath1.SetMaximumSize(maximumSize)\n # islandMath1.Update()\n # islandCount1 = islandMath1.GetMaximumSize()\n # print(islandCount1)\n\n # islandMath = vtkITK.vtkITKIslandMath()\n # islandMath.SetInputConnection(castIn.GetOutputPort())\n # islandMath.SetFullyConnected(False)\n # islandMath.SetMaximumSize(maximumSize)\n # islandMath.Update()\n # islandCount = islandMath.GetNumberOfIslands()\n # print(islandCount)\n\n islandMath = vtkITK.vtkITKIslandMath()\n islandMath.SetInputConnection(castIn.GetOutputPort())\n islandMath.SetFullyConnected(True)\n islandMath.SetMinimumSize(minimumSize)\n islandMath.Update()\n islandCount = islandMath.GetNumberOfIslands()\n print(islandCount)\n\n islandImage = slicer.vtkOrientedImageData()\n islandImage.ShallowCopy(islandMath.GetOutput())\n selectedSegmentLabelmapImageToWorldMatrix = vtk.vtkMatrix4x4()\n selectedSegmentLabelmap.GetImageToWorldMatrix(selectedSegmentLabelmapImageToWorldMatrix)\n islandImage.SetImageToWorldMatrix(selectedSegmentLabelmapImageToWorldMatrix)\n\n islandCount = islandMath.GetNumberOfIslands()\n islandOrigCount = islandMath.GetOriginalNumberOfIslands()\n ignoredIslands = islandOrigCount - islandCount\n logging.info( \"%d islands created (%d ignored)\" % (islandCount, ignoredIslands) )\n\n baseSegmentName = \"Label\"\n selectedSegmentID = self.scriptedEffect.parameterSetNode().GetSelectedSegmentID()\n segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode()\n with slicer.util.NodeModify(segmentationNode):\n segmentation = segmentationNode.GetSegmentation()\n selectedSegment = segmentation.GetSegment(selectedSegmentID)\n selectedSegmentName = selectedSegment.GetName()\n if selectedSegmentName is not None and selectedSegmentName != \"\":\n baseSegmentName = selectedSegmentName\n\n labelValues = vtk.vtkIntArray();\n slicer.vtkSlicerSegmentationsModuleLogic.GetAllLabelValues(labelValues, islandImage);\n\n # Erase segment from in original labelmap.\n # Individuall islands will be added back later.\n threshold = vtk.vtkImageThreshold()\n threshold.SetInputData(selectedSegmentLabelmap)\n threshold.ThresholdBetween(0, 0)\n threshold.SetInValue(0)\n threshold.SetOutValue(0)\n threshold.Update()\n emptyLabelmap = slicer.vtkOrientedImageData()\n emptyLabelmap.ShallowCopy(threshold.GetOutput())\n emptyLabelmap.CopyDirections(selectedSegmentLabelmap)\n self.scriptedEffect.modifySegmentByLabelmap(segmentationNode, selectedSegmentID, emptyLabelmap,\n slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet)\n\n for i in range(labelValues.GetNumberOfTuples()):\n if (maxNumberOfSegments > 0 and i >= maxNumberOfSegments):\n # We only care about the segments up to maxNumberOfSegments.\n # If we do not want to split segments, we only care about the first.\n break\n\n labelValue = int(labelValues.GetTuple1(i))\n segment = selectedSegment\n segmentID = selectedSegmentID\n # if i != 0 and split:\n # segment = slicer.vtkSegment()\n # name = baseSegmentName + \"_\" + str(i+1)\n # segment.SetName(name)\n # segment.AddRepresentation(slicer.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName(),\n # selectedSegment.GetRepresentation(slicer.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName()));\n # segmentation.AddSegment(segment)\n # segmentID = segmentation.GetSegmentIdBySegment(segment)\n # segment.SetLabelValue(segmentation.GetUniqueLabelValueForSharedLabelmap(selectedSegmentID))\n\n threshold = vtk.vtkImageThreshold()\n threshold.SetInputData(islandMath.GetOutput())\n threshold.ThresholdBetween(labelValue, labelValue)\n threshold.SetInValue(1)\n threshold.SetOutValue(0)\n threshold.Update()\n print(threshold)\n modificationMode = slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeAdd\n if i == 0:\n modificationMode = slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet\n\n # Create oriented image data from output\n modifierImage = slicer.vtkOrientedImageData()\n modifierImage.DeepCopy(threshold.GetOutput())\n selectedSegmentLabelmapImageToWorldMatrix = vtk.vtkMatrix4x4()\n selectedSegmentLabelmap.GetImageToWorldMatrix(selectedSegmentLabelmapImageToWorldMatrix)\n modifierImage.SetGeometryFromImageToWorldMatrix(selectedSegmentLabelmapImageToWorldMatrix)\n # We could use a single slicer.vtkSlicerSegmentationsModuleLogic.ImportLabelmapToSegmentationNode\n # method call to import all the resulting segments at once but that would put all the imported segments\n # in a new layer. By using modifySegmentByLabelmap, the number of layers will not increase.\n self.scriptedEffect.modifySegmentByLabelmap(segmentationNode, segmentID, modifierImage, modificationMode)\n\n qt.QApplication.restoreOverrideCursor()\n\n\n def clearPreviewDisplay(self):\n for sliceWidget, pipeline in self.previewPipelines.items():\n self.scriptedEffect.removeActor2D(sliceWidget, pipeline.actor)\n self.previewPipelines = {}\n\n def clearHistogramDisplay(self):\n if self.histogramPipeline is None:\n return\n self.histogramPipeline.removeActors()\n self.histogramPipeline = None\n\n def setupPreviewDisplay(self):\n # Clear previous pipelines before setting up the new ones\n self.clearPreviewDisplay()\n\n layoutManager = slicer.app.layoutManager()\n if layoutManager is None:\n return\n\n # Add a pipeline for each 2D slice view\n for sliceViewName in layoutManager.sliceViewNames():\n sliceWidget = layoutManager.sliceWidget(sliceViewName)\n if not self.scriptedEffect.segmentationDisplayableInView(sliceWidget.mrmlSliceNode()):\n continue\n renderer = self.scriptedEffect.renderer(sliceWidget)\n if renderer is None:\n logging.error(\"setupPreviewDisplay: Failed to get renderer!\")\n continue\n\n # Create pipeline\n pipeline = PreviewPipeline()\n self.previewPipelines[sliceWidget] = pipeline\n\n # Add actor\n self.scriptedEffect.addActor2D(sliceWidget, pipeline.actor)\n\n def preview(self):\n\n opacity = 0.5 + self.previewState / (2. * self.previewSteps)\n min = self.scriptedEffect.doubleParameter(\"MinimumThreshold\")\n max = self.scriptedEffect.doubleParameter(\"MaximumThreshold\")\n\n # Get color of edited segment\n segmentationNode = self.scriptedEffect.parameterSetNode().GetSegmentationNode()\n if not segmentationNode:\n # scene was closed while preview was active\n return\n displayNode = segmentationNode.GetDisplayNode()\n if displayNode is None:\n logging.error(\"preview: Invalid segmentation display node!\")\n color = [0.5,0.5,0.5]\n segmentID = self.scriptedEffect.parameterSetNode().GetSelectedSegmentID()\n\n # Make sure we keep the currently selected segment hidden (the user may have changed selection)\n if segmentID != self.previewedSegmentID:\n self.setCurrentSegmentTransparent()\n\n r,g,b = segmentationNode.GetSegmentation().GetSegment(segmentID).GetColor()\n\n # Set values to pipelines\n for sliceWidget in self.previewPipelines:\n pipeline = self.previewPipelines[sliceWidget]\n pipeline.lookupTable.SetTableValue(1, r, g, b, opacity)\n layerLogic = self.getMasterVolumeLayerLogic(sliceWidget)\n pipeline.thresholdFilter.SetInputConnection(layerLogic.GetReslice().GetOutputPort())\n pipeline.thresholdFilter.ThresholdBetween(min, max)\n pipeline.actor.VisibilityOn()\n sliceWidget.sliceView().scheduleRender()\n\n self.previewState += self.previewStep\n if self.previewState >= self.previewSteps:\n self.previewStep = -1\n if self.previewState <= 0:\n self.previewStep = 1\n\n def processInteractionEvents(self, callerInteractor, eventId, viewWidget):\n abortEvent = False\n\n masterImageData = self.scriptedEffect.masterVolumeImageData()\n if masterImageData is None:\n return abortEvent\n\n # Only allow for slice views\n if viewWidget.className() != \"qMRMLSliceWidget\":\n return abortEvent\n\n # Clicking in a view should remove all previous pipelines\n if eventId == vtk.vtkCommand.LeftButtonPressEvent and not callerInteractor.GetShiftKey():\n self.clearHistogramDisplay()\n\n if self.histogramPipeline is None:\n self.createHistogramPipeline(viewWidget)\n\n xy = callerInteractor.GetEventPosition()\n ras = self.xyToRas(xy, viewWidget)\n\n if eventId == vtk.vtkCommand.LeftButtonPressEvent and not callerInteractor.GetShiftKey():\n self.histogramPipeline.state = HISTOGRAM_STATE_MOVING\n self.histogramPipeline.addPoint(ras)\n self.updateHistogram()\n abortEvent = True\n elif eventId == vtk.vtkCommand.LeftButtonReleaseEvent:\n self.histogramPipeline.state = HISTOGRAM_STATE_PLACED\n elif eventId == vtk.vtkCommand.MouseMoveEvent:\n if self.histogramPipeline.state == HISTOGRAM_STATE_MOVING:\n self.histogramPipeline.addPoint(ras)\n self.updateHistogram()\n return abortEvent\n\n def createHistogramPipeline(self, sliceWidget):\n brushType = HISTOGRAM_BRUSH_TYPE_CIRCLE\n if self.boxROIButton.checked:\n brushType = HISTOGRAM_BRUSH_TYPE_BOX\n elif self.drawROIButton.checked:\n brushType = HISTOGRAM_BRUSH_TYPE_DRAW\n elif self.lineROIButton.checked:\n brushType = HISTOGRAM_BRUSH_TYPE_LINE\n pipeline = HistogramPipeline(self, self.scriptedEffect, sliceWidget, brushType)\n self.histogramPipeline = pipeline\n\n def processViewNodeEvents(self, callerViewNode, eventId, viewWidget):\n if self.histogramPipeline is not None:\n self.histogramPipeline.updateBrushModel()\n\n def onHistogramMouseClick(self, pos, button):\n self.selectionStartPosition = pos\n self.selectionEndPosition = pos\n if (button == qt.Qt.RightButton):\n self.selectionStartPosition = None\n self.selectionEndPosition = None\n self.minMaxFunction.RemoveAllPoints()\n self.averageFunction.RemoveAllPoints()\n self.updateHistogram()\n\n def onHistogramMouseMove(self, pos, button):\n self.selectionEndPosition = pos\n if (button == qt.Qt.RightButton):\n return\n self.updateHistogram()\n\n def onHistogramMouseRelease(self, pos, button):\n self.selectionEndPosition = pos\n if (button == qt.Qt.RightButton):\n return\n self.updateHistogram()\n\n def getMasterVolumeLayerLogic(self, sliceWidget):\n masterVolumeNode = self.scriptedEffect.parameterSetNode().GetMasterVolumeNode()\n sliceLogic = sliceWidget.sliceLogic()\n\n backgroundLogic = sliceLogic.GetBackgroundLayer()\n backgroundVolumeNode = backgroundLogic.GetVolumeNode()\n if masterVolumeNode == backgroundVolumeNode:\n return backgroundLogic\n\n foregroundLogic = sliceLogic.GetForegroundLayer()\n foregroundVolumeNode = foregroundLogic.GetVolumeNode()\n if masterVolumeNode == foregroundVolumeNode:\n return foregroundLogic\n\n logging.warning(\"Master volume is not set as either the foreground or background\")\n\n foregroundOpacity = 0.0\n if foregroundVolumeNode:\n compositeNode = sliceLogic.GetSliceCompositeNode()\n foregroundOpacity = compositeNode.GetForegroundOpacity()\n\n if foregroundOpacity > 0.5:\n return foregroundLogic\n\n return backgroundLogic\n\n def updateHistogram(self):\n masterImageData = self.scriptedEffect.masterVolumeImageData()\n if masterImageData is None or self.histogramPipeline is None:\n self.histogramFunction.RemoveAllPoints()\n return\n\n # Ensure that the brush is in the correct location\n self.histogramPipeline.updateBrushModel()\n\n self.stencil.SetInputConnection(self.histogramPipeline.worldToSliceTransformer.GetOutputPort())\n\n self.histogramPipeline.worldToSliceTransformer.Update()\n brushPolydata = self.histogramPipeline.worldToSliceTransformer.GetOutput()\n brushBounds = brushPolydata.GetBounds()\n brushExtent = [0, -1, 0, -1, 0, -1]\n for i in range(3):\n brushExtent[2*i] = vtk.vtkMath.Floor(brushBounds[2*i])\n brushExtent[2*i+1] = vtk.vtkMath.Ceil(brushBounds[2*i+1])\n if brushExtent[0] > brushExtent[1] or brushExtent[2] > brushExtent[3] or brushExtent[4] > brushExtent[5]:\n self.histogramFunction.RemoveAllPoints()\n return\n\n layerLogic = self.getMasterVolumeLayerLogic(self.histogramPipeline.sliceWidget)\n self.reslice.SetInputConnection(layerLogic.GetReslice().GetInputConnection(0, 0))\n self.reslice.SetResliceTransform(layerLogic.GetReslice().GetResliceTransform())\n self.reslice.SetInterpolationMode(layerLogic.GetReslice().GetInterpolationMode())\n self.reslice.SetOutputExtent(brushExtent)\n\n maxNumberOfBins = 1000\n masterImageData = self.scriptedEffect.masterVolumeImageData()\n scalarRange = masterImageData.GetScalarRange()\n numberOfBins = int(scalarRange[1] - scalarRange[0]) + 1\n if numberOfBins > maxNumberOfBins:\n numberOfBins = maxNumberOfBins\n binSpacing = (scalarRange[1] - scalarRange[0] + 1) / numberOfBins\n\n self.imageAccumulate.SetComponentExtent(0, numberOfBins - 1, 0, 0, 0, 0)\n self.imageAccumulate.SetComponentSpacing(binSpacing, binSpacing, binSpacing)\n self.imageAccumulate.SetComponentOrigin(scalarRange[0], scalarRange[0], scalarRange[0])\n\n self.imageAccumulate.Update()\n\n self.histogramFunction.RemoveAllPoints()\n tableSize = self.imageAccumulate.GetOutput().GetPointData().GetScalars().GetNumberOfTuples()\n for i in range(tableSize):\n value = self.imageAccumulate.GetOutput().GetPointData().GetScalars().GetTuple1(i)\n self.histogramFunction.AddPoint(binSpacing * i + scalarRange[0], value)\n self.histogramFunction.AdjustRange(scalarRange)\n\n lower = self.imageAccumulate.GetMin()[0]\n average = self.imageAccumulate.GetMean()[0]\n upper = self.imageAccumulate.GetMax()[0]\n\n # If there is a selection, then set the threshold based on that\n if self.selectionStartPosition is not None and self.selectionEndPosition is not None:\n\n # Clamp selection based on scalar range\n startX = min(scalarRange[1], max(scalarRange[0], self.selectionStartPosition[0]))\n endX = min(scalarRange[1], max(scalarRange[0], self.selectionEndPosition[0]))\n\n lower = min(startX, endX)\n average = (startX + endX) / 2.0\n upper = max(startX, endX)\n\n epsilon = 0.00001\n self.minMaxFunction.RemoveAllPoints()\n self.minMaxFunction.AddPoint(lower - epsilon, 0.0)\n self.minMaxFunction.AddPoint(lower, 1.0)\n self.minMaxFunction.AddPoint(lower + epsilon, 0.0)\n self.minMaxFunction.AddPoint(upper - epsilon, 0.0)\n self.minMaxFunction.AddPoint(upper, 1.0)\n self.minMaxFunction.AddPoint(upper + epsilon, 0.0)\n self.minMaxFunction.AdjustRange(scalarRange)\n\n self.averageFunction.RemoveAllPoints()\n self.averageFunction.AddPoint(average - epsilon, 0.0)\n self.averageFunction.AddPoint(average, 1.0)\n self.averageFunction.AddPoint(average + epsilon, 0.0)\n self.averageFunction.AdjustRange(scalarRange)\n\n minimumThreshold = lower\n maximumThreshold = upper\n\n histogramSetModeLower = self.scriptedEffect.parameter(HISTOGRAM_SET_LOWER_PARAMETER_NAME)\n if histogramSetModeLower == HISTOGRAM_SET_MINIMUM:\n minimumThreshold = scalarRange[0]\n elif histogramSetModeLower == HISTOGRAM_SET_LOWER:\n minimumThreshold = lower\n elif histogramSetModeLower == HISTOGRAM_SET_AVERAGE:\n minimumThreshold = average\n\n histogramSetModeUpper = self.scriptedEffect.parameter(HISTOGRAM_SET_UPPER_PARAMETER_NAME)\n if histogramSetModeUpper == HISTOGRAM_SET_AVERAGE:\n maximumThreshold = average\n elif histogramSetModeUpper == HISTOGRAM_SET_UPPER:\n maximumThreshold = upper\n elif histogramSetModeUpper == HISTOGRAM_SET_MAXIMUM:\n maximumThreshold = scalarRange[1]\n\n self.scriptedEffect.setParameter(\"MinimumThreshold\", minimumThreshold)\n self.scriptedEffect.setParameter(\"MaximumThreshold\", maximumThreshold)\n\n def updateHistogramBackground(self):\n self.backgroundFunction.RemoveAllPoints()\n\n masterImageData = self.scriptedEffect.masterVolumeImageData()\n if masterImageData is None:\n return\n\n scalarRange = masterImageData.GetScalarRange()\n\n epsilon = 0.00001\n low = self.scriptedEffect.doubleParameter(\"MinimumThreshold\")\n upper = self.scriptedEffect.doubleParameter(\"MaximumThreshold\")\n low = max(scalarRange[0] + epsilon, low)\n upper = min(scalarRange[1] - epsilon, upper)\n\n self.backgroundFunction.AddRGBPoint(scalarRange[0], 1, 1, 1)\n self.backgroundFunction.AddRGBPoint(low - epsilon, 1, 1, 1)\n self.backgroundFunction.AddRGBPoint(low, self.backgroundColor[0], self.backgroundColor[1], self.backgroundColor[2])\n self.backgroundFunction.AddRGBPoint(upper, self.backgroundColor[0], self.backgroundColor[1], self.backgroundColor[2])\n self.backgroundFunction.AddRGBPoint(upper + epsilon, 1, 1, 1)\n self.backgroundFunction.AddRGBPoint(scalarRange[1], 1, 1, 1)\n self.backgroundFunction.SetAlpha(1.0)\n self.backgroundFunction.Build()\n\n#\n# PreviewPipeline\n#\nclass PreviewPipeline(object):\n \"\"\" Visualization objects and pipeline for each slice view for threshold preview\n \"\"\"\n\n def __init__(self):\n self.lookupTable = vtk.vtkLookupTable()\n self.lookupTable.SetRampToLinear()\n self.lookupTable.SetNumberOfTableValues(2)\n self.lookupTable.SetTableRange(0, 1)\n self.lookupTable.SetTableValue(0, 0, 0, 0, 0)\n self.colorMapper = vtk.vtkImageMapToRGBA()\n self.colorMapper.SetOutputFormatToRGBA()\n self.colorMapper.SetLookupTable(self.lookupTable)\n self.thresholdFilter = vtk.vtkImageThreshold()\n self.thresholdFilter.SetInValue(1)\n self.thresholdFilter.SetOutValue(0)\n self.thresholdFilter.SetOutputScalarTypeToUnsignedChar()\n\n # Feedback actor\n self.mapper = vtk.vtkImageMapper()\n self.dummyImage = vtk.vtkImageData()\n self.dummyImage.AllocateScalars(vtk.VTK_UNSIGNED_INT, 1)\n self.mapper.SetInputData(self.dummyImage)\n self.actor = vtk.vtkActor2D()\n self.actor.VisibilityOff()\n self.actor.SetMapper(self.mapper)\n self.mapper.SetColorWindow(255)\n self.mapper.SetColorLevel(128)\n\n # Setup pipeline\n self.colorMapper.SetInputConnection(self.thresholdFilter.GetOutputPort())\n self.mapper.SetInputConnection(self.colorMapper.GetOutputPort())\n\n###\n#\n# Histogram threshold\n#\nclass HistogramEventFilter(qt.QObject):\n thresholdEffect = None\n def setThresholdEffect(self, thresholdEffect):\n self.thresholdEffect = thresholdEffect\n\n def eventFilter(self, object, event):\n if self.thresholdEffect is None:\n return\n\n if (event.type() == qt.QEvent.GraphicsSceneMousePress or\n event.type() == qt.QEvent.GraphicsSceneMouseMove or\n event.type() == qt.QEvent.GraphicsSceneMouseRelease):\n transferFunction = object.transferFunction()\n if transferFunction is None:\n return\n\n representation = transferFunction.representation()\n x = representation.mapXFromScene(event.pos().x())\n y = representation.mapYFromScene(event.pos().y())\n position = (x, y)\n\n if event.type() == qt.QEvent.GraphicsSceneMousePress:\n self.thresholdEffect.onHistogramMouseClick(position, event.button())\n elif event.type() == qt.QEvent.GraphicsSceneMouseMove:\n self.thresholdEffect.onHistogramMouseMove(position, event.button())\n elif event.type() == qt.QEvent.GraphicsSceneMouseRelease:\n self.thresholdEffect.onHistogramMouseRelease(position, event.button())\n return True\n return False\n\n\nclass HistogramPipeline(object):\n\n def __init__(self, thresholdEffect, scriptedEffect, sliceWidget, brushMode):\n self.thresholdEffect = thresholdEffect\n self.scriptedEffect = scriptedEffect\n self.sliceWidget = sliceWidget\n self.brushMode = brushMode\n self.state = HISTOGRAM_STATE_OFF\n\n self.point1 = None\n self.point2 = None\n\n # Actor setup\n self.brushCylinderSource = vtk.vtkCylinderSource()\n self.brushCylinderSource.SetResolution(32)\n\n self.brushCubeSource = vtk.vtkCubeSource()\n\n self.brushLineSource = vtk.vtkLineSource()\n self.brushTubeSource = vtk.vtkTubeFilter()\n self.brushTubeSource.SetInputConnection(self.brushLineSource.GetOutputPort())\n self.brushTubeSource.SetNumberOfSides(50)\n self.brushTubeSource.SetCapping(True)\n\n self.brushToWorldOriginTransform = vtk.vtkTransform()\n self.brushToWorldOriginTransformer = vtk.vtkTransformPolyDataFilter()\n self.brushToWorldOriginTransformer.SetTransform(self.brushToWorldOriginTransform)\n self.brushToWorldOriginTransformer.SetInputConnection(self.brushCylinderSource.GetOutputPort())\n\n self.normalFilter = vtk.vtkPolyDataNormals()\n self.normalFilter.AutoOrientNormalsOn()\n self.normalFilter.SetInputConnection(self.brushToWorldOriginTransformer.GetOutputPort())\n\n # Brush to RAS transform\n self.worldOriginToWorldTransform = vtk.vtkTransform()\n self.worldOriginToWorldTransformer = vtk.vtkTransformPolyDataFilter()\n self.worldOriginToWorldTransformer.SetTransform(self.worldOriginToWorldTransform)\n self.worldOriginToWorldTransformer.SetInputConnection(self.normalFilter.GetOutputPort())\n\n # RAS to XY transform\n self.worldToSliceTransform = vtk.vtkTransform()\n self.worldToSliceTransformer = vtk.vtkTransformPolyDataFilter()\n self.worldToSliceTransformer.SetTransform(self.worldToSliceTransform)\n self.worldToSliceTransformer.SetInputConnection(self.worldOriginToWorldTransformer.GetOutputPort())\n\n # Cutting takes place in XY coordinates\n self.slicePlane = vtk.vtkPlane()\n self.slicePlane.SetNormal(0, 0, 1)\n self.slicePlane.SetOrigin(0, 0, 0)\n self.cutter = vtk.vtkCutter()\n self.cutter.SetCutFunction(self.slicePlane)\n self.cutter.SetInputConnection(self.worldToSliceTransformer.GetOutputPort())\n\n self.rasPoints = vtk.vtkPoints()\n lines = vtk.vtkCellArray()\n self.polyData = vtk.vtkPolyData()\n self.polyData.SetPoints(self.rasPoints)\n self.polyData.SetLines(lines)\n\n # Thin line\n self.thinRASPoints = vtk.vtkPoints()\n thinLines = vtk.vtkCellArray()\n self.thinPolyData = vtk.vtkPolyData()\n self.thinPolyData.SetPoints(self.rasPoints)\n self.thinPolyData.SetLines(thinLines)\n\n self.mapper = vtk.vtkPolyDataMapper2D()\n self.mapper.SetInputConnection(self.cutter.GetOutputPort())\n\n # Add actor\n self.actor = vtk.vtkActor2D()\n self.actor.SetMapper(self.mapper)\n actorProperty = self.actor.GetProperty()\n actorProperty.SetColor(1,1,0)\n actorProperty.SetLineWidth(2)\n renderer = self.scriptedEffect.renderer(sliceWidget)\n if renderer is None:\n logging.error(\"pipelineForWidget: Failed to get renderer!\")\n return None\n self.scriptedEffect.addActor2D(sliceWidget, self.actor)\n\n self.thinActor = None\n if self.brushMode == HISTOGRAM_BRUSH_TYPE_DRAW:\n self.worldToSliceTransformer.SetInputData(self.polyData)\n self.mapper.SetInputConnection(self.worldToSliceTransformer.GetOutputPort())\n\n self.thinWorldToSliceTransformer = vtk.vtkTransformPolyDataFilter()\n self.thinWorldToSliceTransformer.SetInputData(self.thinPolyData)\n self.thinWorldToSliceTransformer.SetTransform(self.worldToSliceTransform)\n\n self.thinMapper = vtk.vtkPolyDataMapper2D()\n self.thinMapper.SetInputConnection(self.thinWorldToSliceTransformer.GetOutputPort())\n\n self.thinActor = vtk.vtkActor2D()\n self.thinActor.SetMapper(self.thinMapper)\n thinActorProperty = self.thinActor.GetProperty()\n thinActorProperty.SetColor(1,1,0)\n thinActorProperty.SetLineWidth(1)\n self.scriptedEffect.addActor2D(sliceWidget, self.thinActor)\n elif self.brushMode == HISTOGRAM_BRUSH_TYPE_LINE:\n self.worldToSliceTransformer.SetInputConnection(self.brushTubeSource.GetOutputPort())\n\n def removeActors(self):\n if self.actor is not None:\n self.scriptedEffect.removeActor2D(self.sliceWidget, self.actor)\n if self.thinActor is not None:\n self.scriptedEffect.removeActor2D(self.sliceWidget, self.thinActor)\n\n def setPoint1(self, ras):\n self.point1 = ras\n self.updateBrushModel()\n\n def setPoint2(self, ras):\n self.point2 = ras\n self.updateBrushModel()\n\n def addPoint(self, ras):\n if self.brushMode == HISTOGRAM_BRUSH_TYPE_DRAW:\n newPointIndex = self.rasPoints.InsertNextPoint(ras)\n previousPointIndex = newPointIndex - 1\n if (previousPointIndex >= 0):\n idList = vtk.vtkIdList()\n idList.InsertNextId(previousPointIndex)\n idList.InsertNextId(newPointIndex)\n self.polyData.InsertNextCell(vtk.VTK_LINE, idList)\n\n thinLines = self.thinPolyData.GetLines()\n thinLines.Initialize()\n idList = vtk.vtkIdList()\n idList.InsertNextId(newPointIndex)\n idList.InsertNextId(0)\n self.thinPolyData.InsertNextCell(vtk.VTK_LINE, idList)\n\n else:\n if self.point1 is None:\n self.setPoint1(ras)\n self.setPoint2(ras)\n\n def updateBrushModel(self):\n if self.brushMode != HISTOGRAM_BRUSH_TYPE_DRAW and (self.point1 is None or self.point2 is None):\n return\n\n # Update slice cutting plane position and orientation\n sliceXyToRas = self.sliceWidget.sliceLogic().GetSliceNode().GetXYToRAS()\n rasToSliceXy = vtk.vtkMatrix4x4()\n vtk.vtkMatrix4x4.Invert(sliceXyToRas, rasToSliceXy)\n self.worldToSliceTransform.SetMatrix(rasToSliceXy)\n\n # brush is rotated to the slice widget plane\n brushToWorldOriginTransformMatrix = vtk.vtkMatrix4x4()\n brushToWorldOriginTransformMatrix.DeepCopy(self.sliceWidget.sliceLogic().GetSliceNode().GetSliceToRAS())\n brushToWorldOriginTransformMatrix.SetElement(0,3, 0)\n brushToWorldOriginTransformMatrix.SetElement(1,3, 0)\n brushToWorldOriginTransformMatrix.SetElement(2,3, 0)\n\n self.brushToWorldOriginTransform.Identity()\n self.brushToWorldOriginTransform.Concatenate(brushToWorldOriginTransformMatrix)\n self.brushToWorldOriginTransform.RotateX(90) # cylinder's long axis is the Y axis, we need to rotate it to Z axis\n\n sliceSpacingMm = self.scriptedEffect.sliceSpacing(self.sliceWidget)\n\n center = [0,0,0]\n if self.brushMode == HISTOGRAM_BRUSH_TYPE_CIRCLE:\n center = self.point1\n\n point1ToPoint2 = [0,0,0]\n vtk.vtkMath.Subtract(self.point1, self.point2, point1ToPoint2)\n radius = vtk.vtkMath.Normalize(point1ToPoint2)\n\n self.brushToWorldOriginTransformer.SetInputConnection(self.brushCylinderSource.GetOutputPort())\n self.brushCylinderSource.SetRadius(radius)\n self.brushCylinderSource.SetHeight(sliceSpacingMm)\n\n elif self.brushMode == HISTOGRAM_BRUSH_TYPE_BOX:\n self.brushToWorldOriginTransformer.SetInputConnection(self.brushCubeSource.GetOutputPort())\n\n length = [0,0,0]\n for i in range(3):\n center[i] = (self.point1[i] + self.point2[i]) / 2.0\n length[i] = abs(self.point1[i] - self.point2[i])\n\n xVector = [1,0,0,0]\n self.brushToWorldOriginTransform.MultiplyPoint(xVector, xVector)\n xLength = abs(vtk.vtkMath.Dot(xVector[:3], length))\n self.brushCubeSource.SetXLength(xLength)\n\n zVector = [0,0,1,0]\n self.brushToWorldOriginTransform.MultiplyPoint(zVector, zVector)\n zLength = abs(vtk.vtkMath.Dot(zVector[:3], length))\n self.brushCubeSource.SetZLength(zLength)\n self.brushCubeSource.SetYLength(sliceSpacingMm)\n\n elif self.brushMode == HISTOGRAM_BRUSH_TYPE_LINE:\n self.brushLineSource.SetPoint1(self.point1)\n self.brushLineSource.SetPoint2(self.point2)\n self.brushTubeSource.SetRadius(sliceSpacingMm)\n\n self.worldOriginToWorldTransform.Identity()\n self.worldOriginToWorldTransform.Translate(center)\n\n self.sliceWidget.sliceView().scheduleRender()\n\nHISTOGRAM_BRUSH_TYPE_PARAMETER_NAME = \"BrushType\"\n\nHISTOGRAM_BRUSH_TYPE_BOX = 'BOX'\nHISTOGRAM_BRUSH_TYPE_CIRCLE = 'CIRCLE'\nHISTOGRAM_BRUSH_TYPE_DRAW = 'DRAW'\nHISTOGRAM_BRUSH_TYPE_LINE = 'LINE'\n\nHISTOGRAM_STATE_OFF = 'OFF'\nHISTOGRAM_STATE_MOVING = 'MOVING'\nHISTOGRAM_STATE_PLACED = 'PLACED'\n\nHISTOGRAM_SET_LOWER_PARAMETER_NAME = 'HistogramSetLower'\nHISTOGRAM_SET_UPPER_PARAMETER_NAME = 'HistogramSetUpper'\n\nHISTOGRAM_SET_MINIMUM = 'MINIMUM'\nHISTOGRAM_SET_LOWER = 'LOWER'\nHISTOGRAM_SET_AVERAGE = 'AVERAGE'\nHISTOGRAM_SET_UPPER = 'UPPER'\nHISTOGRAM_SET_MAXIMUM = 'MAXIMUM'\n\n###\n\nMETHOD_HUANG = 'HUANG'\nMETHOD_INTERMODES = 'INTERMODES'\nMETHOD_ISO_DATA = 'ISO_DATA'\nMETHOD_KITTLER_ILLINGWORTH = 'KITTLER_ILLINGWORTH'\nMETHOD_LI = 'LI'\nMETHOD_MAXIMUM_ENTROPY = 'MAXIMUM_ENTROPY'\nMETHOD_MOMENTS = 'MOMENTS'\nMETHOD_OTSU = 'OTSU'\nMETHOD_RENYI_ENTROPY = 'RENYI_ENTROPY'\nMETHOD_SHANBHAG = 'SHANBHAG'\nMETHOD_TRIANGLE = 'TRIANGLE'\nMETHOD_YEN = 'YEN'\nMETHOD_CUSTOM = 'CUSTOM'\nMODE_SET_UPPER = 'SET_UPPER'\nMODE_SET_LOWER = 'SET_LOWER'\nMODE_SET_MIN_UPPER = 'SET_MIN_UPPER'\nMODE_SET_LOWER_MAX = 'SET_LOWER_MAX'\n","sub_path":"RFViewer-4.11/qt-scripted-modules/SegmentEditorEffects/SegmentEditorThresholdEffect.py","file_name":"SegmentEditorThresholdEffect.py","file_ext":"py","file_size_in_byte":76839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"411344813","text":"import time\r\nimport testing_base as base\r\nimport testing_logger as logger\r\nfrom pymodbus.pdu import ExceptionResponse\r\n\r\n@base.testClass('wdtt')\r\nclass WD_Timer_Testing(base.testingBase):\r\n '''\r\nThis test does a basic modbus watchdog timer test\r\nby reading many registers periodically. If the \r\nwatchdog trips then that is a problem.\r\nUses: -i, -s, -p, -w, -l, -f, -t\r\n'''\r\n def __init__(self, cfg):\r\n self.log = logger.get_logger(\"WD_Timer_Testing\")\r\n self.log.info(\"Look at the modbus watchdog to check for false triggers\")\r\n self.config = cfg\r\n\r\n self.total_resets = 0\r\n self.last_reset = 0.0\r\n base.testingBase.__init__(self, cfg, \"WD_Timer_Testing\")\r\n\r\n def init_test(self):\r\n # just reset the wd counter\r\n self.client.write(65101, 0, arg_type='uint16')\r\n\r\n def iterate_test(self):\r\n # read the watchdog timeout counter and if it's not zero, then \r\n # increment the total and reset it.\r\n value = self.client.decode_holding_args(65101, {'arg_type':'uint16'})\r\n if value != 0:\r\n self.total_resets += value\r\n self.last_reset = time.time()\r\n self.log.error(\"*\"*40)\r\n self.log.error(\"modbus watchdog triggered %d times\"%(self.total_resets))\r\n self.log.debug(\"reset watchdog trigger\")\r\n self.client.write(65101, 0, arg_type='uint16')\r\n\r\n # read bulk data and remember how much time it took\r\n regs = self.client.client.read_holding_registers(0, 100)\r\n if ExceptionResponse is type(regs):\r\n self.log.error(\"read from target failed: %s\"%(str(regs)))\r\n raise Exception(\"failed to read from the target\")\r\n\r\n\r\n def ping_action(self):\r\n # print how many reset there have been and when the last one was\r\n self.log.info(\"there have been %d watchdog resets\"%(self.total_resets))\r\n if self.last_reset != 0.0:\r\n t = time.time() - self.last_reset\r\n self.log.info(\"last reset was %02d:%02d:%02d (%0.3fS) ago\"%(t // 3600, (t % 3600 // 60), (t % 60 // 1), t))\r\n","sub_path":"testing/tests/wd_timer_test.py","file_name":"wd_timer_test.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"209902959","text":"def main(n500, n100, n50, price):\n count = 0\n for i in range(n500 + 1):\n if i * 500 <= price:\n for j in range(n100 + 1):\n if i * 500 + j * 100 <= price:\n for k in range(n50 + 1):\n p = i * 500 + j * 100 + k * 50\n if p == price:\n count += 1\n print(count)\n\n\nif __name__ == \"__main__\":\n n500 = int(input())\n n100 = int(input())\n n50 = int(input())\n price = int(input())\n main(n500, n100, n50, price)\n","sub_path":"Python_codes/p03448/s318598224.py","file_name":"s318598224.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"144475069","text":"\"\"\" Panoramas\n\nThis file has a number of functions that you need to fill out in order to\ncomplete the assignment. Please write the appropriate code, following the\ninstructions on which functions you may or may not use.\n\nGENERAL RULES:\n 1. DO NOT INCLUDE code that saves, shows, displays, writes the image that\n you are being passed in. Do that on your own if you need to save the images\n but the functions should NOT save the image to file.\n\n 2. DO NOT import any other libraries aside from those that we provide.\n You may not import anything else, and you should be able to complete\n the assignment with the given libraries (and in many cases without them).\n\n 3. DO NOT change the format of this file. You may NOT change function\n type signatures (not even named parameters with defaults). You may add\n additional code to this file at your discretion, however it is your\n responsibility to ensure that the autograder accepts your submission.\n\n 4. This file has only been tested in the provided virtual environment.\n You are responsible for ensuring that your code executes properly in the\n virtual machine environment, and that any changes you make outside the\n areas annotated for student code do not impact your performance on the\n autograder system.\n\"\"\"\nimport numpy as np\nimport scipy as sp\nimport cv2\n\n\ndef getImageCorners(image):\n \"\"\"Return the x, y coordinates for the four corners bounding the input\n image and return them in the shape expected by the cv2.perspectiveTransform\n function. (The boundaries should completely encompass the image.)\n\n Parameters\n ----------\n image : numpy.ndarray\n Input can be a grayscale or color image\n\n Returns\n -------\n numpy.ndarray(dtype=np.float32)\n Array of shape (4, 1, 2). The precision of the output is required\n for compatibility with the cv2.warpPerspective function.\n\n Notes\n -----\n (1) Review the documentation for cv2.perspectiveTransform (which will\n be used on the output of this function) to see the reason for the\n unintuitive shape of the output array.\n\n (2) When storing your corners, they must be in (X, Y) order -- keep\n this in mind and make SURE you get it right.\n \"\"\"\n corners = np.zeros((4, 1, 2), dtype=np.float32)\n \n x = image.shape[1]\n y = image.shape[0]\n \n corners[0,0,0] = 0\n corners[0,0,1] = 0\n corners[1,0,0] = x\n corners[1,0,1] = 0\n corners[2,0,0] = 0\n corners[2,0,1] = y\n corners[3,0,0] = x\n corners[3,0,1] = y\n \n return corners\n\n\ndef findMatchesBetweenImages(image_1, image_2, num_matches):\n \"\"\"Return the top list of matches between two input images.\n\n Parameters\n ----------\n image_1 : numpy.ndarray\n The first image (can be a grayscale or color image)\n\n image_2 : numpy.ndarray\n The second image (can be a grayscale or color image)\n\n num_matches : int\n The number of keypoint matches to find. If there are not enough,\n return as many matches as you can.\n\n Returns\n -------\n image_1_kp : list\n A list of keypoint descriptors from image_1\n\n image_2_kp : list\n A list of keypoint descriptors from image_2\n\n matches : list\n A list of the top num_matches matches between the keypoint descriptor\n lists from image_1 and image_2\n\n Notes\n -----\n (1) You will not be graded for this function.\n \"\"\"\n feat_detector = cv2.ORB_create(nfeatures=500)\n image_1_kp, image_1_desc = feat_detector.detectAndCompute(image_1, None)\n image_2_kp, image_2_desc = feat_detector.detectAndCompute(image_2, None)\n bfm = cv2.BFMatcher(normType=cv2.NORM_HAMMING, crossCheck=True)\n matches = sorted(bfm.match(image_1_desc, image_2_desc),\n key=lambda x: x.distance)[:num_matches]\n return image_1_kp, image_2_kp, matches\n\n\ndef findHomography(image_1_kp, image_2_kp, matches):\n \"\"\"Returns the homography describing the transformation between the\n keypoints of image 1 and image 2.\n\n ************************************************************\n Before you start this function, read the documentation\n for cv2.DMatch, and cv2.findHomography\n ************************************************************\n\n Follow these steps:\n\n 1. Iterate through matches and store the coordinates for each\n matching keypoint in the corresponding array (e.g., the\n location of keypoints from image_1_kp should be stored in\n image_1_points).\n\n NOTE: Image 1 is your \"query\" image, and image 2 is your\n \"train\" image. Therefore, you index into image_1_kp\n using `match.queryIdx`, and index into image_2_kp\n using `match.trainIdx`.\n\n 2. Call cv2.findHomography() and pass in image_1_points and\n image_2_points, using method=cv2.RANSAC and\n ransacReprojThreshold=5.0.\n\n 3. cv2.findHomography() returns two values: the homography and\n a mask. Ignore the mask and return the homography.\n\n Parameters\n ----------\n image_1_kp : list\n A list of keypoint descriptors in the first image\n\n image_2_kp : list\n A list of keypoint descriptors in the second image\n\n matches : list\n A list of matches between the keypoint descriptor lists\n\n Returns\n -------\n numpy.ndarray(dtype=np.float64)\n A 3x3 array defining a homography transform between image_1 and image_2\n \"\"\"\n image_1_points = np.zeros((len(matches), 1, 2), dtype=np.float32)\n image_2_points = np.zeros((len(matches), 1, 2), dtype=np.float32)\n \n for i in range(len(matches)):\n queryIdx = matches[i].queryIdx\n trainIdx = matches[i].trainIdx\n \n image_1_points[i,0] = image_1_kp[queryIdx].pt\n image_2_points[i,0] = image_2_kp[trainIdx].pt\n\n homography,_ = cv2.findHomography(image_1_points, image_2_points, cv2.RANSAC, 5.0)\n \n return homography\n\n\ndef getBoundingCorners(corners_1, corners_2, homography):\n \"\"\"Find the coordinates of the top left corner and bottom right corner of a\n rectangle bounding a canvas large enough to fit both the warped image_1 and\n image_2.\n\n Given the 8 corner points (the transformed corners of image 1 and the\n corners of image 2), we want to find the bounding rectangle that\n completely contains both images.\n\n Follow these steps:\n\n 1. Use the homography to transform the perspective of the corners from\n image 1 (but NOT image 2) to get the location of the warped\n image corners.\n\n 2. Get the boundaries in each dimension of the enclosing rectangle by\n finding the minimum x, maximum x, minimum y, and maximum y.\n\n Parameters\n ----------\n corners_1 : numpy.ndarray of shape (4, 1, 2)\n Output from getImageCorners function for image 1\n\n corners_2 : numpy.ndarray of shape (4, 1, 2)\n Output from getImageCorners function for image 2\n\n homography : numpy.ndarray(dtype=np.float64)\n A 3x3 array defining a homography transform between image_1 and image_2\n\n Returns\n -------\n numpy.ndarray(dtype=np.float64)\n 2-element array containing (x_min, y_min) -- the coordinates of the\n top left corner of the bounding rectangle of a canvas large enough to\n fit both images (leave them as floats)\n\n numpy.ndarray(dtype=np.float64)\n 2-element array containing (x_max, y_max) -- the coordinates of the\n bottom right corner of the bounding rectangle of a canvas large enough\n to fit both images (leave them as floats)\n\n Notes\n -----\n (1) The inputs may be either color or grayscale, but they will never\n be mixed; both images will either be color, or both will be grayscale.\n\n (2) Python functions can return multiple values by listing them\n separated by commas.\n\n Ex.\n def foo():\n return [], [], []\n \"\"\"\n \n temp_corners = np.zeros(corners_1.shape)\n \n for i in range(4):\n temp_x = corners_1[i,0,0]\n temp_y = corners_1[i,0,1]\n temp = homography.dot(np.array([[temp_x],[temp_y],[1]]))\n temp_corners[i,0,0] = temp[0]/temp[2]\n temp_corners[i,0,1] = temp[1]/temp[2]\n \n corners_1 = temp_corners\n \n x = np.array([corners_1[0,0,0],corners_1[1,0,0],corners_1[2,0,0],corners_1[3,0,0],\n corners_2[0,0,0],corners_2[1,0,0],corners_2[2,0,0],corners_2[3,0,0]])\n y = np.array([corners_1[0,0,1],corners_1[1,0,1],corners_1[2,0,1],corners_1[3,0,1],\n corners_2[0,0,1],corners_2[1,0,1],corners_2[2,0,1],corners_2[3,0,1]])\n \n min_xy = np.array([min(x),min(y)])\n max_xy = np.array([max(x),max(y)])\n \n return min_xy, max_xy\n\n\ndef warpCanvas(image, homography, min_xy, max_xy):\n \"\"\"Warps the input image according to the homography transform and embeds\n the result into a canvas large enough to fit the next adjacent image\n prior to blending/stitching.\n\n Follow these steps:\n\n 1. Create a translation matrix (numpy.ndarray) that will shift\n the image by x_min and y_min. This looks like this:\n\n [[1, 0, -x_min],\n [0, 1, -y_min],\n [0, 0, 1]]\n\n 2. Compute the dot product of your translation matrix and the\n homography in order to obtain the homography matrix with a\n translation.\n\n NOTE: Matrix multiplication (dot product) is not the same thing\n as the * operator (which performs element-wise multiplication).\n See Numpy documentation for details.\n\n 3. Call cv2.warpPerspective() and pass in image 1, the combined\n translation/homography transform matrix, and a vector describing\n the dimensions of a canvas that will fit both images.\n\n NOTE: cv2.warpPerspective() is touchy about the type of the output\n shape argument, which should be an integer.\n\n Parameters\n ----------\n image : numpy.ndarray\n A grayscale or color image (test cases only use uint8 channels)\n\n homography : numpy.ndarray(dtype=np.float64)\n A 3x3 array defining a homography transform between two sequential\n images in a panorama sequence\n\n min_xy : numpy.ndarray(dtype=np.float64)\n 2x1 array containing the coordinates of the top left corner of a\n canvas large enough to fit the warped input image and the next\n image in a panorama sequence\n\n max_xy : numpy.ndarray(dtype=np.float64)\n 2x1 array containing the coordinates of the bottom right corner of\n a canvas large enough to fit the warped input image and the next\n image in a panorama sequence\n\n Returns\n -------\n numpy.ndarray(dtype=image.dtype)\n An array containing the warped input image embedded in a canvas\n large enough to join with the next image in the panorama; the output\n type should match the input type (following the convention of\n cv2.warpPerspective)\n\n Notes\n -----\n (1) You must explain the reason for multiplying x_min and y_min\n by negative 1 in your writeup.\n \"\"\"\n # canvas_size properly encodes the size parameter for cv2.warpPerspective,\n # which requires a tuple of ints to specify size, or else it may throw\n # a warning/error, or fail silently\n canvas_size = tuple(np.round(max_xy - min_xy).astype(np.int))\n translation = np.array([[1,0,-min_xy[0]],[0,1,-min_xy[1]],[0,0,1]])\n matrix = translation.dot(homography)\n output_image = cv2.warpPerspective(image, matrix, canvas_size)\n \n return output_image\n\n\ndef blendImagePair(image_1, image_2, num_matches):\n \"\"\"This function takes two images as input and fits them onto a single\n canvas by performing a homography warp on image_1 so that the keypoints\n in image_1 aligns with the matched keypoints in image_2.\n\n **************************************************************************\n\n You MUST replace the basic insertion blend provided here to earn\n credit for this function.\n\n The most common implementation is to use alpha blending to take the\n average between the images for the pixels that overlap, but you are\n encouraged to use other approaches.\n\n Be creative -- good blending is the primary way to earn\n Above & Beyond credit on this assignment.\n\n **************************************************************************\n\n Parameters\n ----------\n image_1 : numpy.ndarray\n A grayscale or color image\n\n image_2 : numpy.ndarray\n A grayscale or color image\n\n num_matches : int\n The number of keypoint matches to find between the input images\n\n Returns:\n ----------\n numpy.ndarray\n An array containing both input images on a single canvas\n\n Notes\n -----\n (1) This function is not graded by the autograder. It will be scored\n manually by the TAs.\n\n (2) The inputs may be either color or grayscale, but they will never be\n mixed; both images will either be color, or both will be grayscale.\n\n (3) You can modify this function however you see fit -- e.g., change\n input parameters, return values, etc. -- to develop your blending\n process.\n \"\"\"\n kp1, kp2, matches = findMatchesBetweenImages(\n image_1, image_2, num_matches)\n homography = findHomography(kp1, kp2, matches)\n corners_1 = getImageCorners(image_1)\n corners_2 = getImageCorners(image_2)\n min_xy, max_xy = getBoundingCorners(corners_1, corners_2, homography)\n output_image = warpCanvas(image_1, homography, min_xy, max_xy)\n \n top = homography.dot(np.array([[corners_1[3,0,0]],[corners_1[3,0,1]],[1]]))\n bottom = homography.dot(np.array([[corners_1[1,0,0]],[corners_1[1,0,1]],[1]]))\n x_min = int(-min_xy[0])\n x_max = x_min + int((top[0]/top[2] + bottom[0]/bottom[2]) /2)\n \n for i in range(image_2.shape[0]):\n for j in range(image_2.shape[1]):\n if output_image[i-int(min_xy[1]),j-int(min_xy[0])].any() == 0:\n output_image[i-int(min_xy[1]),j-int(min_xy[0])] = image_2[i,j]\n else:\n coef = min(max((j-int(min_xy[0])-x_min)/(x_max-x_min), 0), 1)\n output_image[i-int(min_xy[1]),j-int(min_xy[0])] = output_image[i-int(min_xy[1]),j-int(min_xy[0])] * (1-coef) + image_2[i,j] * coef\n\n return output_image\n","sub_path":"panorama.py","file_name":"panorama.py","file_ext":"py","file_size_in_byte":14609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"380651107","text":"import os\nfrom glob import glob\nfrom torch.utils.data import Dataset\nfrom torchvision.datasets.folder import default_loader\nfrom numpy.random import RandomState\n\nSEED = 42\nRATIO_TRAIN = 0.85\n\nclass Tuberculosis(Dataset):\n\n def __init__(self, folder, train=True, transform=None):\n self.folder = folder\n self.transform = transform\n rng = RandomState(SEED)\n files = sorted(glob(os.path.join(folder, \"*.png\")))\n rng.shuffle(files)\n nb_train = int(len(files) * RATIO_TRAIN)\n if train:\n self.files = files[0:nb_train]\n else:\n self.files = files[nb_train:]\n self.classes = [0, 1]\n\n def __getitem__(self, index):\n path = self.files[index]\n img = default_loader(path)\n if self.transform:\n img = self.transform(img)\n class_id = int(os.path.basename(path)[-5])#class is encoded in filename\n return img, class_id\n\n def __len__(self):\n return len(self.files)\n","sub_path":"transfer_learning/datasets/tuberculosis.py","file_name":"tuberculosis.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"33382185","text":"import torch\nfrom torch import nn\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ntorch.manual_seed(1) # reproducible\n\n# hyper parameters\nTIME_STEP = 10 # RNN time step=image height\nINPUT_SIZE = 1 # RNN input size=image width\nLR = 0.02 # learning rate\nDOWNLOAD_MNIST = False # set to True if haven't download the data\n\n\n# define RNN Model\nclass RNN(nn.Module):\n def __init__(self):\n super(RNN, self).__init__()\n\n self.rnn = nn.RNN(\n input_size=1,\n hidden_size=32,\n num_layers=1,\n batch_first=True\n )\n self.out = nn.Linear(32, 1)\n\n def forward(self, x, h_state): # keep passing h_state through the process\n # x(batch,time_step,input_size)\n # h_state(n_layers,batch,hidden_size)\n # r_out(batch,time_step,output_size)\n r_out, h_state = self.rnn(x, h_state) # input includes both h_state and x\n\n outs = [] # save predicted value\n for time_step in range(r_out.size(1)): # calculate output for each time step\n outs.append(self.out(r_out[:, time_step, :]))\n return torch.stack(outs, dim=1), h_state\n\n\nrnn = RNN()\nprint(rnn)\n\n# prepare for optimizing RNN parameters\n\noptimizer = torch.optim.Adam(rnn.parameters(), lr=LR)\nloss_func = nn.MSELoss()\nh_state = None # initialize hidden state\n\n# training process\nfor step in range(100):\n start, end = step * np.pi, (step + 1) * np.pi # time steps\n # predict cos value with sin value\n steps = np.linspace(start, end, 10, dtype=np.float32)\n x_np = np.sin(steps)\n y_np = np.cos(steps)\n\n x = torch.from_numpy(x_np[np.newaxis, :, np.newaxis]) # shape(batch,time_step,input_size)\n y = torch.from_numpy(y_np[np.newaxis, :, np.newaxis])\n\n prediction, h_state = rnn(x, h_state)\n\n h_state = h_state.data # debug:h_state itself can not be used as input value directly\n # optimizing routine\n loss = loss_func(prediction, y) # cross entropy loss\n optimizer.zero_grad() # clear gradients for this training step\n loss.backward() # calculate gradients through back propagation\n optimizer.step()\n","sub_path":"RNN_Regression.py","file_name":"RNN_Regression.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"518950190","text":"#!/usr/bin/python3\n\n# required libraries\nimport nltk\nfrom nltk import word_tokenize, sent_tokenize\nstatement1=\"Vishal is good boy\"\nout1=word_tokenize(statement1) # to tokenize the words \nprint(out1)\n\n\nstatement2=\"vishal is cool. he is calm and composed in nature.\"\nout2=sent_tokenize(statement2) # to tokenize sentences\nprint(out2)\n","sub_path":"tokenize.py","file_name":"tokenize.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"148943746","text":"# Створити функцію find_simple(numbers) яка на вхід отримує список цілих невід'ємних чисел і\n# на вихід повертає список простих чисел знайдених у вхідному списку. Якщо одне і те ж число повторюється\n# у вхідних даних, то воно також має повторюватись і у вихідних. Порядок слідування чисел у вихідних даних\n# має бути таким самим як і у вхідних даних\n#\n# Просте число — це натуральне число, яке має рівно два різних натуральних дільники (лише 1 і саме число).\n\n\ndef is_simple(n):\n if n <= 1:\n return False\n elif n == 2:\n return True\n else:\n for i in range(2, n // 2 + 1):\n if n % i == 0:\n return False\n return True\n\n\ndef find_simple(numbers):\n s_lst = [x for x in numbers if is_simple(x)]\n return s_lst\n\n\nprint(find_simple(range(10)))\nprint(find_simple([1, 2, 4, 6, 3, 8, 12, 2, 18, 5, 24, 13]))","sub_path":"домашка/CRDN_PRO_Tests/PASS1/test07_my.py","file_name":"test07_my.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"351223851","text":"\"\"\"\r\nWait for data to arrive in _FTP_FROM_CLIENT and move it to DataIntake folder\r\nThis script needs to be excuted by the sctbns user because only this user has access to the\r\n_FTP_FROM_CLIENT FOLDER\r\n\"\"\"\r\nimport asyncio\r\nimport shutil\r\nimport os\r\nimport argparse\r\nfrom datetime import datetime\r\nimport Glue.FileOrganizer as forg\r\nimport Glue.Utilities as utils\r\nimport re\r\n\r\n\r\nasync def require_file(directory: str, filename: str, wait_time: int = 10, time_out: int = None, message: str = None):\r\n \"\"\"checks if file is present in directory, throws timeout error if takes too long\r\n \r\n Parameters\r\n ----------\r\n filename : str\r\n filename, can also be a regex pattern\r\n wait_time : int, optional\r\n time to wait in between checks in seconds\r\n time_out : int, optional\r\n total time to wait before raising error\r\n message : str, optional\r\n message to console when file is found\r\n \r\n Returns\r\n -------\r\n \r\n Raises\r\n ------\r\n TimeoutError\r\n throws error if waits longer than time_out\r\n \r\n \"\"\"\r\n\r\n # while not os.path.isfile(filename):\r\n # await asyncio.sleep(wait_time)\r\n\r\n start = datetime.now()\r\n\r\n # wait for file by checking directory contents to see if file is there\r\n # ignore case by converting all to lower case\r\n arrived = False\r\n while not arrived:\r\n # check if should time out\r\n if time_out is not None:\r\n if (datetime.now() - start).seconds > time_out:\r\n raise TimeoutError(\"{f} did not arrive\".format(f=filename))\r\n\r\n # look for file in directory contents\r\n dir_contents = [f.lower() for f in os.listdir(directory)]\r\n if len([f for f in dir_contents if re.match(filename.lower(), f)]) == 1:\r\n arrived = True\r\n else:\r\n await asyncio.sleep(wait_time)\r\n\r\n # print message that file exists\r\n if message is None:\r\n message = filename + \" is available\"\r\n print(message)\r\n\r\n return None\r\n\r\n\r\ndef wait_for_files(directory: str, files: list, wait_time=10, time_out: int = None, ):\r\n \"\"\"Checks if each file in files is present in directory. Blocks until all files are there\"\"\r\n \r\n Parameters\r\n ----------\r\n files : list\r\n paths to file\r\n wait_time : int, optional\r\n how long to wait between checks\r\n time_out : int, optional\r\n Description\r\n time_out\r\n \r\n Returns\r\n -------\r\n None\r\n prints availability of filenames as they arrive\r\n \r\n \"\"\"\r\n loop = asyncio.get_event_loop()\r\n tasks = [asyncio.ensure_future(\r\n require_file(directory=directory, filename=f, wait_time=wait_time, time_out=time_out)) for f in files]\r\n loop.run_until_complete(asyncio.gather(*tasks))\r\n loop.close()\r\n\r\n return None\r\n\r\n\r\ndef run(ava_ver: str = None, dialer_ver: str = None, nuance_ver: str = None, version: str = None,\r\n date: str = None, wait_time: int = 10, time_out: int = None):\r\n \"\"\"\r\n waits for ava, nuance, dialer filenames in _FTP_FROM_CLIENT,\r\n moves them to DataIntake\r\n returns dialer date - easier (hackier) than having to compute previous business day\r\n\r\n Parameters\r\n ----------\r\n nuance_ver\r\n time_out\r\n ava_ver : str, optional\r\n version number of ava file\r\n dialer_ver : str, optional\r\n version number of dialer file\r\n version : str, optional\r\n Description\r\n date : str, optional\r\n ending of the file, should be None or a date of format yyyymmdd_file\r\n wait_time : int, optional\r\n how long to wait in between checking of filenames in seconds\r\n \r\n Returns\r\n -------\r\n forg.FtpFrom: class object which contains all the information of FtpFrom Waiting Step\r\n \"\"\"\r\n\r\n # wait for incoming filenames\r\n ftp_from = forg.FtpFrom(date=date, version=version, dialer_ver=dialer_ver,\r\n ava_ver=ava_ver, nuance_ver=nuance_ver)\r\n\r\n files_in = ftp_from.filenames\r\n md5s_in = ftp_from.md5names\r\n\r\n # wait for filenames by checking if the file + _DONE has arrived\r\n # timeout if had to wait too long\r\n try:\r\n wait_for_files(directory=ftp_from.base_dir,\r\n files=[f + \"_DONE\" for f in {**files_in, **md5s_in}.values()],\r\n wait_time=wait_time,\r\n time_out=time_out)\r\n except TimeoutError as error:\r\n print(type(error), error, error.args)\r\n return None\r\n\r\n # outgoing filenames\r\n data_intake = forg.DataIntake(date=date, version=version)\r\n files_out = data_intake.filenames\r\n md5s_out = data_intake.md5names\r\n\r\n # move filenames to DataIntake and delete them from _FTP_FROM_CLIENT\r\n os.makedirs(data_intake.dir, exist_ok=True)\r\n for key in files_in.keys():\r\n if key == \"dialer\" and ftp_from.dialer_date is None:\r\n # reconstruct dialer files from only knowing the pattern without the actual date\r\n # and find the dialer date from the name of the reconstructed file\r\n f_in = utils.file_from_pattern(ftp_from.base_dir, \"^\" + files_in[key] + \"$\")\r\n m_in = utils.file_from_pattern(ftp_from.base_dir, \"^\" + md5s_in[key] + \"$\")\r\n ftp_from.dialer_date = forg.extract_bns_date(f_in)\r\n else:\r\n f_in, m_in = files_in[key], md5s_in[key]\r\n\r\n f_out, m_out = files_out[key], md5s_out[key]\r\n shutil.copy(os.path.join(ftp_from.base_dir, f_in), os.path.join(data_intake.dir, f_out))\r\n shutil.copy(os.path.join(ftp_from.base_dir, m_in), os.path.join(data_intake.dir, m_out))\r\n\r\n # very important - all files need to be removed from _FTP_FROM for tomorrow's cycle\r\n # os.remove(f)\r\n # os.remove(f_in + \"_DONE\")\r\n\r\n return ftp_from\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \"\"\" can run the script as a main \"\"\"\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"--date\", nargs=\"?\", default=None, type=str, help=\"date as tag, format yyddd\")\r\n parser.add_argument(\"--wait\", nargs=\"?\", default=10, type=int)\r\n parser.add_argument(\"--timeout\", nargs=\"?\", default=None, type=int)\r\n parser.add_argument(\"--ava_ver\", nargs=\"?\", default=None, type=str)\r\n parser.add_argument(\"--dialer_ver\", nargs=\"?\", default=None, type=str)\r\n parser.add_argument(\"--version\", nargs=\"?\", default=None, type=str,\r\n help=\"number of times script was run today\")\r\n args = parser.parse_args()\r\n\r\n # check for the filenames and move\r\n run(ava_ver=args.ava_ver, dialer_ver=args.dialer_ver,\r\n version=args.version, date=args.date, wait_time=args.wait, time_out=args.timeout)\r\n","sub_path":"Glue/WaitAndMove.py","file_name":"WaitAndMove.py","file_ext":"py","file_size_in_byte":6649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"49705301","text":"class KeySizeError(Exception):\n pass\n\n\nclass Cipher:\n def __init__(self, key):\n assert isinstance(key, bytes)\n self.s = list(range(256))\n self.i = 0\n self.j = 0\n self.key = key\n\n k = len(key)\n if k < 1 or k > 256:\n raise KeySizeError('crypto/rc4: invalid key size ' + str(k))\n\n j = 0\n for i in range(256):\n j = (j + self.s[i] + key[i % k]) % 256\n self.s[i], self.s[j] = self.s[j], self.s[i]\n\n def __str__(self):\n return f'rc4.Cipher(key={self.key})'\n\n def crypto(self, src, dst):\n i, j = self.i, self.j\n for k, v in enumerate(src):\n i = (i + 1) % 256\n j = (j + self.s[i]) % 256\n self.s[i], self.s[j] = self.s[j], self.s[i]\n dst[k] = v ^ self.s[(self.s[i] + self.s[j]) % 256] % 256\n self.i, self.j = i, j\n\n def stream(self, src, dst):\n c = 65536\n buf = list(range(c))\n while True:\n ctx = src.read(c)\n if not ctx:\n break\n n = len(ctx)\n self.crypto(ctx, buf)\n dst.write(bytes(buf[:n]))\n","sub_path":"rc4.py","file_name":"rc4.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"149538016","text":"# -*- coding: utf-8 -*-\n\n# Noms : Corinne Dumais, Élodie Lescure, Chloé Lavoie-Audet, Aricia Proulx\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nNh = 301 # nombre de noeuds horizontaux\nNv = 51 # nombre de noeuds verticaux\n\n# initialisation de la matrice\ncavite = np.array([[0 for x in range(Nh)] for y in range(Nv)])\n\n# initialisation du potentiel sur la paroi supérieur\nfor n in range(20, Nh):\n cavite[0][n] = 300\n\n# initialisation du potentiel sur la paroi inférieur\nfor n in range(20, Nh):\n cavite[50][n] = 300\n\n# initialisation du potentiel sur la paroi de droite\nfor n in range(Nv):\n cavite[n][300] = 300\n\n# initialisation du potentiel sur la paroi de gauche\nfor n in range(9):\n cavite[n][20] = 300\n\nfor n in range(42, Nv):\n cavite[n][20] = 300\n\nfor n in range(15, 36):\n cavite[n][0] = 300\n\nfor n in range(8, 16):\n cavite[n][10] = 300\n\nfor n in range(35, 43):\n cavite[n][10] = 300\n\nfor n in range(11):\n cavite[15][n] = 300\n\nfor n in range(10, 21):\n cavite[8][n] = 300\n\nfor n in range(11):\n cavite[35][n] = 300\n\nfor n in range(10, 21):\n cavite[42][n] = 300\n\n# assignation d'une valeur au nombre d'itérations\nnb_iterations = 100\nn = 0\n\n# calcul méthode Gauss-Seidel\nwhile n <= nb_iterations:\n for j in range(1, Nv - 1):\n for i in range(1, Nh - 1):\n if 22 < j < 28 and i > 14:\n continue\n elif j < 9 and i < 21:\n continue\n elif i < 11 and j < 16:\n continue\n elif i < 21 and j > 41:\n continue\n elif j > 34 and i < 11:\n continue\n else:\n cavite[j][i] = 0.25*(cavite[j+1][i] + cavite[j-1][i] + cavite[j][i+1] + cavite[j][i-1])\n n += 1\n\n# affichage du graphique 2d\ncolor_map = plt.imshow(cavite, aspect='auto')\ncb = plt.colorbar(orientation='vertical')\nplt.xlabel('X[mm]')\nplt.xticks((50, 100, 150, 200, 250, 300), ('10', '20', '30', '40', '50', '60'))\nplt.yticks((0, 10, 20, 30, 40), ('10', '8', '6', '4', '2'))\nplt.ylabel('Y[mm]')\nplt.text(1.175, 0.5, 'Potentiel[V]', horizontalalignment='left', verticalalignment='center',\n rotation=90, clip_on=False, transform=plt.gca().transAxes)\nplt.title('Potentiel dans la cavité pour ' + str(nb_iterations) + ' itérations avec Gauss-Seidel')\nplt.show()\n","sub_path":"Numero2/GaussSeidel.py","file_name":"GaussSeidel.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"556584835","text":"from mdgen.constants import LINESEPARATOR\nfrom mdgen.core import (MarkdownBoldGenerator, MarkdownHeaderGenerator,\n MarkdownHorizontalRuleGenerator,\n MarkdownImageGenerator, MarkdownItalicGenerator,\n MarkdownLinkGenerator, MarkdownListGenerator,\n MarkdownTableGenerator, MarkdownTextGenerator)\n\n\nclass MarkdownGenerator:\n\n \"\"\" This is the core class that is used to generate markdown text.\n You probably don't want to use this class, unless you are extending\n it somehow. \"\"\"\n\n def new_text(self, text: str):\n \"\"\"\n Returns the `text` as it is.\n\n :param text: A string that will be returned as it is\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_text('This is a test text')\n 'This is a test text'\n\n \"\"\"\n\n text_output = MarkdownTextGenerator()\n output = text_output.new_text(text)\n return output\n\n def new_text_line(self, text: str):\n \"\"\"\n Returns a new text line, and adds a linebreak to its end.\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_text_line('This is a test text line')\n 'This is a test text line\\\\n'\n\n \"\"\"\n text_line = MarkdownTextGenerator()\n output = text_line.new_text_line(text)\n return output\n\n def new_header(self, text: str, header_level: int = 1, linebreak=True, atx=True):\n \"\"\"\n Returns a markdown header, using `text` and `header_level`, adds a\n linebreak to it (default behavior can be changed using\n `linebreak=False`). Smaller the `header_level`, larger the header.\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_header('This is a test header', 2)\n '## This is a test header\\\\n'\n\n \"\"\"\n if not isinstance(header_level, (int,)):\n raise AttributeError(f\"`header_level` must be an instance of or {int}\")\n if not isinstance(linebreak, (bool,)):\n raise AttributeError(f\"`linebreak` must be an instance of or {bool}\")\n if not isinstance(atx, (bool,)):\n raise AttributeError(f\"`atx` must be an instance of or {bool}\")\n header = MarkdownHeaderGenerator(atx)\n output = header.new_header(text, header_level, linebreak)\n return output\n\n def new_bold_text(self, text: str):\n \"\"\"\n Returns the `text` bolded.\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_bold_text('This is a test')\n '**This is a test**'\n\n \"\"\"\n bold_text = MarkdownBoldGenerator()\n output = bold_text.new_bold_text(text)\n return output\n\n def new_italic_text(self, text: str, underscore=True):\n \"\"\"\n Returns the `text` in italics.\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_italic_text('This is a test')\n '_This is a test_'\n\n \"\"\"\n if not isinstance(underscore, (bool,)):\n raise AttributeError(f\"`underscore` must be an instance of or {bool}\")\n italic_text = MarkdownItalicGenerator()\n output = italic_text.new_italic_text(text, underscore)\n return output\n\n def new_bold_and_italic_text(self, text: str, underscore=True):\n \"\"\"\n Returns the `text` bolded and italic.\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_bold_and_italic_text('This is a test')\n '_**This is a test**_'\n\n \"\"\"\n if not isinstance(underscore, (bool,)):\n raise AttributeError(f\"`underscore` must be an instance of or {bool}\")\n bolded = self.new_bold_text(text)\n bolded_and_italic = self.new_italic_text(bolded, underscore)\n return bolded_and_italic\n\n def new_horizontal_rule(self, style: str = 'hyphens'):\n \"\"\"\n Returns a markdown horizontal line used to separate sections.\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_horizontal_rule()\n '---\\\\n'\n\n \"\"\"\n permitted_styles = ['hyphens', 'asterisks', 'underscores']\n if style not in permitted_styles:\n raise AttributeError(f\"`style` must be among {permitted_styles}\")\n horizontal_rule = MarkdownHorizontalRuleGenerator()\n output = horizontal_rule.new_horizontal_rule(style)\n return output\n\n def new_paragraph(self, text: str, paragraph_size: int = 79):\n \"\"\"\n Returns a markdown paragraph, each line formatted to contain\n `paragraph_size` characters each. Defaults to 79.\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_paragraph('hello this is an epic paragraph', 12)\n 'hello this is an \\\\nepic paragraph \\\\n'\n\n \"\"\"\n paragraph = MarkdownTextGenerator(paragraph_size)\n output = paragraph.new_paragraph(text)\n return output\n\n def new_unordered_list_item(self, text: str, style: str = 'asterisk'):\n \"\"\"\n Returns a single unordered markdown list item. an asterisk will be\n prepended by deafult, can be changed by passing `style` argument.\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_unordered_list_item('hello')\n '* hello'\n\n \"\"\"\n permitted_styles = ['asterisk', 'plus', 'minus']\n if style not in permitted_styles:\n raise AttributeError(f\"`style` must be among {permitted_styles}\")\n list_item = MarkdownListGenerator(style)\n output = list_item.new_unordered_list_item(text)\n return output\n\n def new_ordered_list_item(self, text: str, index: int = 1):\n \"\"\"\n Returns a single ordered markdown list item. `index` will be the\n number prepended, and if not supplied, defaults to 1.\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_ordered_list_item('hello')\n '1. hello'\n\n \"\"\"\n list_item = MarkdownListGenerator()\n output = list_item.new_ordered_list_item(text, index)\n return output\n\n def new_unordered_list(self, list_items_list: list, style: str = 'asterisk',\n linebreak: bool = True):\n \"\"\"\n Returns a markdown list of unordered list. `list_items_list` must be a\n list of lists (or tuples).\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_unordered_list(['hello', 'hi', 'how do you do?'])\n '* hello\\\\n* hi\\\\n* how do you do?\\\\n'\n\n \"\"\"\n output = ''\n # indent = 0\n\n for list_item in list_items_list:\n output += (f\"{self.new_unordered_list_item(list_item, style)}\"\n f\"{LINESEPARATOR}\")\n if not linebreak:\n output = output[:-1]\n return output\n\n def new_ordered_list(self, list_items_list: list, linebreak: bool = True):\n \"\"\"\n Returns a markdown list of ordered list. `list_items_list` must be a\n list of lists (or tuples).\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_ordered_list(['hello', 'hi', 'how do you do?'])\n '1. hello\\\\n2. hi\\\\n3. how do you do?\\\\n'\n\n \"\"\"\n output = ''\n for index, list_item in enumerate(list_items_list, 1):\n output += self.new_ordered_list_item(list_item, index)\n output += LINESEPARATOR\n if not linebreak:\n output = output[:-1]\n return output\n\n def new_table(self, list_items_list: list):\n \"\"\"\n Returns a markdown table. `list_items_list` must be a list of list\n (or tuples).\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_table([['hello', 'hi', 'how do you do?'], ['1', '2', '3', '4']])\n '|hello|hi|how do you do?|\\\\n|-----|--|--------------|\\\\n|1|2|3|4|\\\\n'\n\n \"\"\"\n table = MarkdownTableGenerator()\n output = table.new_table(list_items_list)\n return output\n\n def new_link(self, link_text: str, link_url: str = '', linebreak: bool = False):\n \"\"\"\n Returns a markdown link which can be used to link external websites, or\n even internal ones. If `link_url` is not provided, an empty link is\n returned.\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_link('Visit this link')\n '[Visit this link]()'\n >>> m.new_link('Visit this link', 'http://shadyUrl.com/')\n '[Visit this link](http://shadyUrl.com/)'\n\n \"\"\"\n link = MarkdownLinkGenerator()\n output = link.new_link(link_text, link_url, linebreak)\n return output\n\n def new_comment(self, comment_text: str):\n \"\"\" Returns the `comment_text` within markdown comment blocks.\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_comment('This is a comment')\n ''\n\n \"\"\"\n comment_output = MarkdownTextGenerator()\n output = comment_output.new_comment(comment_text)\n return output\n\n def new_image(self, alt_text: str, image_url: str, image_title: str = ''):\n \"\"\"\n Returns a markdown link which can be used to link external websites, or\n even internal ones. If `link_url` is not provided, an empty link is\n returned.\n\n .. code-block:: python\n\n >>> m = MarkdownGenerator()\n >>> m.new_image('image one', 'http://example.org/?image=one')\n '![image one](http://example.org/?image=one)'\n >>> m.new_image('image two', 'http://example.org/?image=second',\n ... 'The 2nd image')\n '![image two](http://example.org/?image=second \"The 2nd image\")'\n\n \"\"\"\n image = MarkdownImageGenerator()\n output = image.new_image(alt_text, image_url, image_title)\n return output\n","sub_path":"mdgen/markdown.py","file_name":"markdown.py","file_ext":"py","file_size_in_byte":10167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"446617993","text":"#coding:gb2312\n'''\nCreated on 2014Äê11ÔÂ4ÈÕ\n\n@author: Administrator\n'''\nimport os\ndef processTestCorpus(originalTestFile):\n testset = open(originalTestFile, 'r')\n allLines = testset.readlines()\n testset.close()\n essay = {}\n for eachline in allLines:\n oneline = eachline.strip()\n essay_content = oneline.split(None, 1)\n essay_content_id = essay_content[0]\n essay_content_token = essay_content[1].split()\n essay_content_list = []\n pos_begin = -1\n pos_end = 0\n for each_token in essay_content_token:\n if isvalid(each_token):\n pos_end = pos_begin + len(each_token)\n pos_begin +=1\n essay_content_list.append([[pos_begin, pos_end], each_token])\n pos_begin = pos_end\n else:\n pos_begin = pos_begin + len(each_token) \n essay[essay_content_id] = essay_content_list\n return essay\n\ndef isvalid(token):\n length = len(token)\n if length > 0 :\n if token[0] == '(' or token[0] == '\"':\n if length > 1:\n token = token[1:]\n length = length - 1\n else:\n return False\n else:\n return False \n while length != 0 and token != None and (token[length-1] == ')' or token[length-1] == ',' or token[length-1] == '.' or token[length-1] == '\"' or token[length-1] == ':' or token[length-1] == ';'):\n if length > 1:\n token = token[0:length-1]\n length = length - 1\n else:\n return False\n return True\n \ndef write_prediction(originalTestCorpus = None, prediction = {}, filename = None):\n testset = open(originalTestCorpus, 'r')\n allLines = testset.readlines()\n testset.close()\n prediction_file = open(filename, \"w\")\n for eachline in allLines:\n oneline = eachline.strip()\n essay_content = oneline.split(None, 1)\n essay_content_id = essay_content[0]\n essay_content_token = essay_content[1].split()\n essay_content_list = []\n pos_begin = -1\n pos_end = 0\n for each_token in essay_content_token:\n if isvalid(each_token):\n pos_end = pos_begin + len(each_token)\n pos_begin +=1\n essay_content_list.append([(pos_begin, pos_end), each_token])\n pos_begin = pos_end\n else:\n pos_begin = pos_begin + len(each_token) \n if essay_content_id in prediction.keys():\n pre_path = prediction[essay_content_id]\n Flag = False\n sentenceID = None\n gene_begin = -1\n gene_end = 0\n gene_name = None\n for i in range(len(pre_path)):\n if pre_path[i] == \"B\":\n Flag = True\n sentenceID = essay_content_id\n current_begin, current_end = essay_content_list[i][0]\n gene_begin = str(current_begin)\n gene_end = str(current_end)\n gene_name = essay_content_list[i][1]\n elif pre_path[i] == \"O\":\n Flag = False\n if sentenceID != None:\n prediction_file.write(sentenceID + \"|\" + gene_begin + \" \" + gene_end + \"|\" + gene_name + \"\\n\")\n sentenceID = None\n elif Flag :\n current_begin, current_end = essay_content_list[i][0]\n gene_end = str(current_end)\n gene_name = gene_name + \" \" + essay_content_list[i][1] \n if sentenceID != None:\n prediction_file.write(sentenceID + \"|\" + gene_begin + \" \" + gene_end + \"|\" + gene_name + \"\\n\")\n prediction_file.close()\ndef post_processing(inputfile = None, outputfile = None):\n readerFile = open(inputfile, \"r\")\n allLines = readerFile.readlines()\n readerFile.close()\n writerFile = open(outputfile, \"w\")\n for eachline in allLines:\n oneline = eachline.strip()\n infor_list = oneline.split(\"|\")\n pos_pair = infor_list[1].split()\n pos_begin = int(pos_pair[0])\n pos_end = int(pos_pair[1])\n gene_name = infor_list[2]\n i = len(gene_name)-1\n while (gene_name[i] == ',' \n or gene_name[i] == '.' \n or gene_name[i] == '\"' \n or gene_name[i] == ':' \n or gene_name[i] == ';'\n or gene_name[i] == '-'):\n i -= 1\n pos_end -= 1\n length = i + 1\n gene_name = gene_name[0:length]\n if gene_name[0] == \"(\" and gene_name[length-1] == \")\" :\n pos_begin += 1\n pos_end -= 1\n gene_name = gene_name[1:length-1]\n elif gene_name[0] == \"(\" and gene_name.find(\")\") == -1:\n pos_begin += 1\n gene_name = gene_name[1:]\n elif gene_name[length-1] == \")\" and gene_name.find(\"(\") == -1 :\n pos_end -=1 \n gene_name = gene_name[:length-1]\n if gene_name.count(\"(\") == gene_name.count(\")\"):\n writerFile.write(infor_list[0] + \"|\" + str(pos_begin) + \" \" + str(pos_end) + \"|\" + gene_name + \"\\n\")\n writerFile.close() \nif __name__ == \"__main__\":\n## processTestCorpus(originalTestCorpus) \n# list = [\"O\", \"O\", \"O\", \"O\", \"O\", \"O\", \"B\", \"I\", \"O\", \"O\", \"B\", \"O\", \"O\", \"O\", \"O\", \"O\", \"B\"]\n# prediction = {\"BC2GM096399526\":list}\n# write_prediction(originalTestCorpus, prediction , \"test_pre.pkl\")\n# currentDir = os.path.dirname(__file__)\n post_processing(\"test.eval\", \"test2.eval\")\n# str = \"alk(\"\n# print str.count(\"(\")","sub_path":"src/com/liu/utils/testCorpus.py","file_name":"testCorpus.py","file_ext":"py","file_size_in_byte":5709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"406520770","text":"'''\nCopyright 2019 Broadcom. The term \"Broadcom\" refers to Broadcom Inc.\nand/or its subsidiaries.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n'''\n\nimport sys\nimport os\nimport stat\nimport socket\n\nimport pytest\n\nfrom ztp.ZTPObjects import Identifier\nfrom ztp.DecodeSysEeprom import sysEeprom\n\nclass TestClass(object):\n\n '''!\n \\brief This class allow to define unit tests for class Identifier\n\n Examples of class usage:\n\n \\code\n pytest-2.7 -v -x test_Logger.py\n \\endcode\n '''\n\n def test_hostname(self):\n '''!\n Test when we call the constructor function using hostname\n '''\n\n id = Identifier('hostname')\n v = id.getIdentifier()\n assert(v == socket.gethostname())\n\n def test_sonic_version(self):\n '''!\n Test when we call the constructor function using sonic-version\n '''\n\n id = Identifier('sonic-version')\n v = id.getIdentifier()\n build_version = None\n with open('/etc/sonic/sonic_version.yml') as fp:\n line = fp.readline()\n while line:\n version_info = line.split(':')\n if version_info[0] == 'build_version':\n ver = version_info[1].strip()\n ver = ver.lstrip('\\'')\n ver = ver.rstrip('\\'')\n build_version = 'SONiC.{}'.format(ver)\n break\n line = fp.readline()\n fp.close()\n assert(v == build_version)\n\n def test_hostname_fqdn(self):\n '''!\n Test when we call the constructor function using hostname-fqdn\n '''\n\n id = Identifier('hostname-fqdn')\n v = id.getIdentifier()\n assert(v == socket.getfqdn())\n\n def test_serial_number(self):\n '''!\n Test when we call the constructor function using the serial number\n '''\n\n id = Identifier('serial-number')\n v = id.getIdentifier()\n assert(v == sysEeprom.get_serial_number())\n\n def test_product_name(self):\n '''!\n Test when we call the constructor function using the product name\n '''\n\n id = Identifier('product-name')\n v = id.getIdentifier()\n assert(v == sysEeprom.get_product_name())\n\n def test_other(self):\n '''!\n Test when we call the constructor function using the product name\n '''\n\n id = Identifier('other')\n v = id.getIdentifier()\n assert(v == 'other')\n\n def test_wrong_parameter1(self):\n dl = [('url', 'other')]\n d = dict(dl)\n id = Identifier(d)\n v = id.getIdentifier()\n assert(v == None)\n\n def test_wrong_parameter2(self):\n dl = [('url', [1])]\n d = dict(dl)\n id = Identifier(d)\n v = id.getIdentifier()\n assert(v == None)\n\n def test_get_url1(self, tmpdir):\n dt = tmpdir.mkdir(\"valid\")\n fh = dt.join(\"input.txt\")\n content = '#!/bin/sh\\n\\necho \"Hello\"'\n fh.write(content)\n dl = [('url', 'file://'+str(fh))]\n d = dict(dl)\n id = Identifier(d)\n v = id.getIdentifier()\n assert(v == 'Hello')\n\n def test_get_url2(self, tmpdir):\n dt = tmpdir.mkdir(\"valid\")\n fh = dt.join(\"input.txt\")\n content = '#!/bin/sh\\n\\necho \"Hello\"'\n fh.write(content)\n dl_url = [('source', 'file://'+str(fh)), ('destination', 'abc')]\n d_url = dict(dl_url)\n dl = [('url', d_url)]\n d = dict(dl)\n id = Identifier(d)\n v = id.getIdentifier()\n assert(v == 'Hello')\n\n def test_get_url3(self, tmpdir):\n dt = tmpdir.mkdir(\"valid\")\n fh = dt.join(\"input.txt\")\n content = 'XYZ ABC'\n fh.write(content)\n dl_url = [('source', 'file://'+str(fh)), ('destination', 'abc')]\n d_url = dict(dl_url)\n dl = [('url', d_url)]\n d = dict(dl)\n id = Identifier(d)\n v = id.getIdentifier()\n assert(v == None)\n\n def test_get_url4(self, tmpdir):\n dt = tmpdir.mkdir(\"valid\")\n fh = dt.join(\"input.txt\")\n content = '#!/bin/sh\\nexit -1'\n fh.write(content)\n dl_url = [('source', 'file://'+str(fh)), ('destination', 'abc')]\n d_url = dict(dl_url)\n dl = [('url', d_url)]\n d = dict(dl)\n id = Identifier(d)\n v = id.getIdentifier()\n assert(v == None)\n\n def test_get_url5(self, tmpdir):\n dt = tmpdir.mkdir(\"valid\")\n fh = dt.join(\"input.txt\")\n content = '#!/bin/sh\\n\\necho \"Hello\"'\n fh.write(content)\n dl = [('url', None)]\n d = dict(dl)\n id = Identifier(d)\n v = id.getIdentifier()\n assert(v == None)\n","sub_path":"tests/test_Identifier.py","file_name":"test_Identifier.py","file_ext":"py","file_size_in_byte":5155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"524901351","text":"from django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom tethys_sdk.gizmos import Button\n\n\n@login_required()\ndef home(request, var1, var2):\n \"\"\"\n Controller for the app home page.\n \"\"\"\n save_button = Button(\n display_text='',\n name='save-button',\n icon='glyphicon glyphicon-floppy-disk',\n style='success',\n attributes={\n 'data-toggle': 'tooltip',\n 'data-placement': 'top',\n 'title': 'Save'\n }\n )\n\n edit_button = Button(\n display_text='',\n name='edit-button',\n icon='glyphicon glyphicon-edit',\n style='warning',\n attributes={\n 'data-toggle': 'tooltip',\n 'data-placement': 'top',\n 'title': 'Edit'\n }\n )\n\n remove_button = Button(\n display_text='',\n name='remove-button',\n icon='glyphicon glyphicon-remove',\n style='danger',\n attributes={\n 'data-toggle': 'tooltip',\n 'data-placement': 'top',\n 'title': 'Remove'\n }\n )\n\n previous_button = Button(\n display_text='Previous',\n name='previous-button',\n attributes={\n 'data-toggle': 'tooltip',\n 'data-placement': 'top',\n 'title': 'Previous'\n }\n )\n\n next_button = Button(\n display_text='Next',\n name='next-button',\n attributes={\n 'data-toggle': 'tooltip',\n 'data-placement': 'top',\n 'title': 'Next'\n }\n )\n\n context = {\n 'save_button': save_button,\n 'edit_button': edit_button,\n 'remove_button': remove_button,\n 'previous_button': previous_button,\n 'next_button': next_button\n }\n\n return render(request, 'test_app/home.html', context)\n","sub_path":"tests/apps/tethysapp-test_app/tethysapp/test_app/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"466153643","text":"# Copyright (c) 2017 The Khronos Group Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n#\n# Imports\n#\n\nimport bpy\n\nfrom ...io.com.gltf2_io_debug import *\n\nfrom ...io.exp.gltf2_io_get import *\n\n#\n# Globals\n#\n\n#\n# Functions\n#\n\ndef _get_from_node_by_node_group(name, shader_node_group):\n \n if shader_node_group is None:\n return None\n \n if not isinstance(shader_node_group, bpy.types.ShaderNodeGroup) and not isinstance(shader_node_group, bpy.types.ShaderNodeBsdfPrincipled):\n return None\n\n if shader_node_group.inputs.get(name) is None:\n return None\n \n if len(shader_node_group.inputs[name].links) == 0:\n return None\n \n from_node = shader_node_group.inputs[name].links[0].from_node\n \n #\n \n if isinstance(from_node, bpy.types.ShaderNodeNormalMap):\n\n name = 'Color'\n\n if len(from_node.inputs[name].links) == 0:\n return None\n\n from_node = from_node.inputs[name].links[0].from_node\n \n #\n\n if not isinstance(from_node, bpy.types.ShaderNodeTexImage):\n return None\n\n return from_node\n\ndef get_texture_index_by_node_group(export_settings, glTF, name, shader_node_group):\n \"\"\"\n Return the texture index in the glTF array.\n \"\"\"\n\n from_node = _get_from_node_by_node_group(name, shader_node_group)\n\n if from_node is None:\n return -1\n\n #\n\n if from_node.image is None or from_node.image.size[0] == 0 or from_node.image.size[1] == 0:\n return -1\n\n return get_texture_index(glTF, from_node.image.name)\n\n\ndef get_texcoord_index_by_node_group(glTF, name, shader_node_group):\n \"\"\"\n Return the texture coordinate index, if assigend and used.\n \"\"\"\n\n from_node = _get_from_node_by_node_group(name, shader_node_group)\n\n if from_node is None:\n return 0\n \n #\n \n if len(from_node.inputs['Vector'].links) == 0:\n return 0\n\n input_node = from_node.inputs['Vector'].links[0].from_node\n \n #\n \n if isinstance(input_node, bpy.types.ShaderNodeMapping):\n\n if len(input_node.inputs['Vector'].links) == 0:\n return 0\n \n input_node = input_node.inputs['Vector'].links[0].from_node\n \n #\n\n if not isinstance(input_node, bpy.types.ShaderNodeUVMap):\n return 0\n \n if input_node.uv_map == '':\n return 0\n \n #\n\n # Try to gather map index. \n for blender_mesh in bpy.data.meshes:\n texCoordIndex = blender_mesh.uv_textures.find(input_node.uv_map)\n if texCoordIndex >= 0:\n return texCoordIndex\n\n return 0\n\n\ndef get_image_uri(export_settings, blender_image):\n \"\"\"\n Return the final URI depending on a filepath.\n \"\"\"\n\n file_format = get_image_format(export_settings, blender_image)\n extension = '.jpg' if file_format == 'JPEG' else '.png'\n\n return get_image_name(blender_image.name) + extension\n\n\ndef get_image_format(export_settings, blender_image):\n \"\"\"\n Return the final output format of the given image. Only PNG and JPEG are\n supported as outputs - all other formats must be converted.\n \"\"\"\n if blender_image.file_format in ['PNG', 'JPEG']:\n return blender_image.file_format\n\n use_alpha = export_settings['filtered_images_use_alpha'].get(blender_image.name)\n\n return 'PNG' if use_alpha else 'JPEG'\n\n\ndef get_node(data_path):\n \"\"\"\n Return Blender node on a given Blender data path.\n \"\"\"\n\n if data_path is None:\n return None\n\n index = data_path.find(\"[\\\"\")\n if (index == -1):\n return None\n\n node_name = data_path[(index + 2):]\n\n index = node_name.find(\"\\\"\")\n if (index == -1):\n return None\n\n return node_name[:(index)]\n\n\ndef get_data_path(data_path):\n \"\"\"\n Return Blender data path.\n \"\"\"\n\n index = data_path.rfind('.')\n \n if index == -1:\n return data_path\n \n return data_path[(index + 1):]\n","sub_path":"addons/io_scene_gltf2/blender/exp/gltf2_blender_get.py","file_name":"gltf2_blender_get.py","file_ext":"py","file_size_in_byte":4382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"403257488","text":"from pygame import *\ninit()\nmixer.pre_init(44100, 16, 2, 4096)\n# size = (500, 500)\nsize = width, height = 500, 480\n\n# creates a window\nwin = display.set_mode(size)\n\n# setting caption\ndisplay.set_caption(\"Game: movement\")\n\nclock = time.Clock()\n\nbulletSound = mixer.Sound('bullet.wav')\n\nmusic = mixer.music.load('images/music.mp3')\nmixer.music.play(-1)\n\nwalkRight = [image.load(\"images/R\" + str(i) + \".png\") for i in range(1, 10)]\nwalkLeft = [image.load(\"images/L\" + str(i) + \".png\") for i in range(1, 10)]\n\nbg = image.load(\"images/bg.jpg\")\nchar = image.load(\"images/standing.png\")\n\nclock = time.Clock()\n\n\nclass player(object):\n def __init__(self, x, y, width, height):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.vel = 5\n self.isJump = False\n self.left = False\n self.right = False\n self.walkCount = 0\n self.jumpCount = 8\n self.standing = True\n self.hitbox = (self.x + 17, self.y + 11, 29, 52)\n\n def draw(self, win):\n if self.walkCount + 1 >= 27:\n self.walkCount = 0\n\n if not self.standing:\n if self.left:\n win.blit(walkLeft[self.walkCount // 3], (self.x, self.y))\n self.walkCount += 1\n elif self.right:\n win.blit(walkRight[self.walkCount // 3], (self.x, self.y))\n self.walkCount += 1\n else:\n if self.right:\n win.blit(walkRight[0], (self.x, self.y))\n else:\n win.blit(walkLeft[0], (self.x, self.y))\n\n self.hitbox = (self.x + 17, self.y + 11, 29, 52)\n # draw.rect(win, (250, 0, 0), self.hitbox, 2)\n\n def hit(self):\n self.isJump = False\n self.jumpCount = 8\n self.x = 60\n self.y = 410\n self.walkCount = 0\n font1 = font.SysFont('comicsans', 100)\n text = font1.render('-5', 1, (255, 0, 0))\n win.blit(text, (250 - (text.get_width() / 2), 200))\n display.update()\n i = 0\n while i < 300:\n time.delay(10)\n i += 1\n for e in event.get():\n if e.type == QUIT:\n i = 301\n quit()\n\nclass projectile(object):\n def __init__(self,x,y,radius,color,facing):\n self.x = x\n self.y = y\n self.radius = radius\n self.color = color\n self.facing = facing\n self.vel = 8 * facing\n\n def draw(self,win):\n draw.circle(win, self.color, (self.x,self.y), self.radius)\n\n\nclass enemy(object):\n walkRight = [image.load(\"images/R\" + str(i) + \"E.png\") for i in range(1, 12)]\n walkLeft = [image.load(\"images/L\" + str(i) + \"E.png\") for i in range(1, 12)]\n\n def __init__(self, x, y, width, height, end):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.path = [x, end]\n self.walkCount = 0\n self.vel = 3\n self.hitbox = (self.x + 17, self.y + 2, 31, 57)\n self.health = 10\n self.visible = True\n\n self.hitCounter = 0\n\n def draw(self, win):\n self.move()\n if self.visible and (self.health > 0):\n if self.walkCount + 1 >= 33:\n self.walkCount = 0\n\n if self.vel > 0:\n win.blit(self.walkRight[self.walkCount // 3], (self.x, self.y))\n self.walkCount += 1\n else:\n win.blit(self.walkLeft[self.walkCount // 3], (self.x, self.y))\n self.walkCount += 1\n\n draw.rect(win, (250, 0, 0), (self.hitbox[0], self.hitbox[1] - 20, 50, 10))\n draw.rect(win, (0, 128, 0), (self.hitbox[0], self.hitbox[1] - 20, 50 - ((50//10) * (10 - self.health)), 10))\n self.hitbox = (self.x + 17, self.y + 2, 31, 57)\n # draw.rect(win, (250, 0, 0), self.hitbox, 2)\n\n def move(self):\n if self.vel > 0:\n if self.x < self.path[1] + self.vel:\n self.x += self.vel\n else:\n self.vel = self.vel * -1\n self.x += self.vel\n self.walkCount = 0\n else:\n if self.x > self.path[0] - self.vel:\n self.x += self.vel\n else:\n self.vel = self.vel * -1\n self.x += self.vel\n self.walkCount = 0\n\n def hit(self):\n if self.health > 0:\n self.health -= 1\n else:\n self.visible = False\n self.hitCounter += 1\n\n\ndef redrawGameWindow():\n win.blit(bg, (0, 0))\n man.draw(win)\n text = foop.render(\"Score:\" + str(foo.hitCounter), 1, (0, 0, 0))\n win.blit(text, (360, 10))\n for bullet in bullets:\n bullet.draw(win)\n foo.draw(win)\n display.update()\n\n\n# mainloop\nfoop = font.SysFont(\"comicsans\", 30, True)\nman = player(200, 410, 64, 64)\nbullets = []\nshoot_cdr = 0\nfoo = enemy(100, 410, 64, 64, 300)\nrun = True\nwhile run:\n clock.tick(30)\n if foo.health > 0:\n if man.hitbox[1] < foo.hitbox[1] + foo.hitbox[3] and man.hitbox[1] + man.hitbox[3] > foo.hitbox[1]:\n if man.hitbox[0] + man.hitbox[2] > foo.hitbox[0] and man.hitbox[0] < foo.hitbox[0] + foo.hitbox[2]:\n man.hit()\n foo.hitCounter -= 5\n if shoot_cdr > 0:\n shoot_cdr += 1\n if shoot_cdr > 5:\n shoot_cdr = 0\n\n for e in event.get():\n if e.type == QUIT:\n run = False\n\n for bullet in bullets:\n if foo.health > 0:\n if bullet.y - bullet.radius < foo.hitbox[1] + foo.hitbox[3] and bullet.y + bullet.radius > foo.hitbox[1]:\n if bullet.x + bullet.radius > foo.hitbox[0] and bullet.x - bullet.radius < foo.hitbox[0] + foo.hitbox[2]:\n foo.hit()\n bullets.pop(bullets.index(bullet))\n\n if (bullet.x < 500) and (bullet.x > 0):\n bullet.x += bullet.vel\n else:\n bullets.pop(bullets.index(bullet))\n\n keys = key.get_pressed()\n\n if keys[K_SPACE] and shoot_cdr == 0:\n if len(bullets) < 5:\n bullets.append(projectile(round(man.x + man.width // 2), round(man.y + man.height // 2), 6, (0, 0, 0), -1 if man.left else 1))\n bulletSound.play()\n shoot_cdr = 1\n\n if keys[K_LEFT] and man.x > man.vel:\n man.x -= man.vel\n man.left = True\n man.right = False\n man.standing = False\n elif keys[K_RIGHT] and man.x < 500 - man.width - man.vel:\n man.x += man.vel\n man.right = True\n man.left = False\n man.standing = False\n else:\n man.standing = True\n man.walkCount = 0\n\n if not man.isJump:\n if keys[K_UP]:\n man.isJump = True\n man.right = False\n man.left = False\n man.walkCount = 0\n else:\n if man.jumpCount >= -8:\n man.y -= (man.jumpCount * abs(man.jumpCount)) * 0.5\n man.jumpCount -= 1\n else:\n man.isJump = False\n man.jumpCount = 8\n\n redrawGameWindow()\n\n\nquit()\n","sub_path":"Learning module/Animations/Animation_sound_affect.py","file_name":"Animation_sound_affect.py","file_ext":"py","file_size_in_byte":7031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"621429475","text":"import asyncio\nimport io\nimport logging\nimport math\nimport os\nimport pickle\nimport random\n\nimport discord\nfrom discord.ext import commands\n\nFORMAT = '%(levelname)s:%(name)s:(%(asctime)s): %(message)s'\nDATEFMT = '%d-%b-%y %H:%M:%S'\nlogging.basicConfig(format = FORMAT, datefmt = DATEFMT, level = logging.INFO)\n\nbot = commands.Bot('dnd-')\n\nRESERVED_NAMES = {'World', 'all'}\nCONVERSIONS = {'cp': 1, 'sp': 10, 'gp': 100, 'pp': 1000}\n\n################################################################################\n#Internal classes and functions start\n\nclass Campaign:\n def __init__(self, id, gm):\n self.VERSION = '1.1'\n self.names = {}\n self.players = {}\n self.pending = []\n self.archive = []\n self.id = id\n self.gms = [gm]\n\n \n def add_transaction(self, transaction):\n self.pending.append(transaction)\n\n\n def approve(self, indices):\n for index in indices:\n self.pending[index].complete()\n self.archive.append(self.pending[index])\n self.pending = [item for index, item in enumerate(self.pending)\n if index not in indices]\n\n\n def deny(self, indices):\n self.pending = [item for index, item in enumerate(self.pending)\n if index not in indices]\n\n \n def to_csv(self):\n vals = ['Initiator,Giver,Taker,CP,SP,GP,PP,Reason']\n for transaction in self.archive:\n initiator = transaction.initiator.name\n if transaction.mode == 'give':\n giver = transaction.initiator.name\n taker = transaction.participant.name\n elif transaction.mode == 'take':\n giver = transaction.participant.name\n taker = transaction.initiator.name\n else:\n raise ValueError('Invalid transaction mode')\n cp = transaction.amounts['cp']\n sp = transaction.amounts['sp']\n gp = transaction.amounts['gp']\n pp = transaction.amounts['pp']\n reason = transaction.reason\n vals.append(','.join(str(val) for val in (\n initiator, giver, taker,\n cp, sp, gp, pp, reason,\n )))\n return '\\n'.join(vals)\n\n\nclass Player:\n def __init__(self, id, name):\n self.cp = 0\n self.sp = 0\n self.gp = 0\n self.pp = 0\n self.id = id\n self.name = name\n\n\n @property\n def balance(self):\n coins = '[{0.cp} CP | {0.sp} SP | {0.gp} GP | {0.pp} PP]'.format(self)\n egp = ' ({0:.2f} EGP)'.format(convert_to_egp({\n 'cp': self.cp,\n 'sp': self.sp,\n 'gp': self.gp,\n 'pp': self.pp,\n }))\n return coins + egp\n\n\n\nclass Transaction:\n def __init__(self, initiator, mode, amounts, participant, reason):\n self.participant = participant\n self.initiator = initiator\n self.amounts = amounts\n self.reason = reason\n self.mode = mode\n\n if participant is None:\n self.participant = Player(None, 'World')\n\n\n def complete(self):\n if self.mode == 'give':\n mult = -1\n elif self.mode == 'take':\n mult = 1\n\n for coin in self.amounts:\n val = getattr(self.initiator, coin) + self.amounts[coin]*mult\n setattr(self.initiator, coin, val)\n\n if self.participant.name:\n for coin in self.amounts:\n val = getattr(self.participant, coin) - self.amounts[coin]*mult\n setattr(self.participant, coin, val)\n\n\n @property\n def text(self):\n initiator = self.initiator.name\n\n if self.mode == 'give':\n arrow = '->'\n elif self.mode == 'take':\n arrow = '<-'\n else:\n raise ValueError('Mode should be \"give\" or \"take\"')\n\n amount = ''\n for coin in self.amounts:\n if self.amounts[coin]:\n amount += str(self.amounts[coin]) + ' ' + coin.upper() + ', '\n amount = amount[ :-2]\n\n if not self.reason:\n reason = 'No reason given'\n else:\n reason = self.reason\n\n participant = self.participant.name\n\n return f'{initiator} {arrow} {participant}: {amount} ({reason})'\n\n\n\nclass DatabaseManager:\n def __init__(self):\n self.campaigns = [int(id) for id in os.listdir('data')]\n self.locks = {int(id): asyncio.Lock() for id in os.listdir('data')}\n self.cache = {}\n\n\n async def add_campaign(self, campaign):\n if campaign.id in self.campaigns:\n raise FileExistsError('Campaign with this ID already exists')\n\n logging.info('Created {0}'.format(campaign.id))\n\n self.campaigns.append(campaign.id)\n self.locks[campaign.id] = asyncio.Lock()\n\n await self.locks[campaign.id].acquire()\n await self.save_campaign(campaign)\n\n\n async def del_campaign(self, id):\n os.remove('data/{0}'.format(id))\n self.campaigns.remove(id)\n self.locks.pop(id)\n if id in self.cache:\n self.cache.pop(id)\n\n logging.info('Successfully deleted {0}'.format(id))\n\n\n async def load_campaign(self, id, blocking = False):\n await self.locks[id].acquire()\n\n if id not in self.cache:\n logging.info('Reading {0}'.format(id))\n try:\n with open('data/{0}'.format(id), 'rb') as file:\n campaign = pickle.load(file)\n except FileNotFoundError:\n return None\n self.cache[id] = campaign\n while len(self.cache) > 100:\n self.cache.pop(self.cache.keys()[0])\n\n if not blocking:\n self.locks[id].release()\n else:\n logging.info('Acquired lock for {0}'.format(id))\n\n return self.cache[id]\n\n\n async def save_campaign(self, campaign):\n logging.info('Writing {0}'.format(campaign.id))\n with open('data/{0}'.format(campaign.id), 'wb') as file:\n pickle.dump(campaign, file)\n self.cache[campaign.id] = campaign\n while len(self.cache) > 10:\n self.cache.pop(self.cache.keys()[0])\n self.locks[campaign.id].release()\n logging.info('Released lock for {0}'.format(campaign.id))\n\n\n\nasync def parse_indices(ctx, campaign, terms):\n pending = [transaction for transaction in campaign.pending\n if ctx.author.id in (transaction.participant.id, *campaign.gms)]\n terms = [term.strip() for term in terms.split(',')]\n indices = []\n if 'last' in terms:\n indices.append(len(pending) - 1)\n elif 'all' in terms:\n indices = [i for i in range(len(pending))]\n else:\n for term in terms:\n term = term.split('-')\n if len(term) == 1:\n try:\n index = int(term[0]) - 1\n except ValueError:\n await log_syntax_error(ctx)\n return None\n if index < len(pending):\n if index not in indices:\n indices.append(index)\n else:\n logging.info('Encountered invalid index; aborting.')\n await ctx.send('\"' + term[0] + '\" is an invalid ID.')\n return None\n elif len(term) == 2:\n try:\n start_index = int(term[0]) - 1\n end_index = int(term[1]) - 1\n except ValueError:\n await log_syntax_error(ctx)\n return None\n if start_index < end_index:\n if start_index >= 0 and end_index < len(pending):\n for i in range(start_index, end_index + 1):\n if i not in indices:\n indices.append(i)\n else:\n if start_index < 0:\n problem = str(start_index + 1)\n else:\n problem = str(end_index + 1)\n logging.info('Encountered invalid index; aborting.')\n await ctx.send('\"' + problem + '\" is an invalid ID.')\n return None\n else:\n logging.info('Encountered invalid slice; aborting.')\n await ctx.send('Start ID must be lower than end ID.')\n return None\n else:\n await log_syntax_error(ctx)\n return None\n player_index = 0\n corrected_indices = []\n for global_index, transaction in enumerate(campaign.pending):\n if ctx.author.id in (transaction.participant.id, *campaign.gms):\n if player_index in indices:\n corrected_indices.append(global_index)\n player_index += 1\n corrected_indices.sort()\n return corrected_indices\n\n\nasync def log_syntax_error(ctx):\n logging.info('Invalid syntax; aborting.')\n await ctx.send(':x: Invalid syntax. Use `dnd-help [command]` to view info.')\n\n\ndef convert_to_egp(amounts):\n return (0.01*amounts['cp'] + 0.1*amounts['sp']\n + 1*amounts['gp'] + 10*amounts['pp'])\n\n\ndef convert_from_egp(amount, amounts = None):\n if amounts is None:\n amounts = {'cp': 0, 'sp': 0, 'gp': 0, 'pp': 0}\n amounts['gp'] += int(amount)\n amount = round(10*(amount % 1), 1)\n amounts['sp'] += int(amount)\n amount = round(10*(amount % 1))\n amounts['cp'] += int(amount)\n return amounts\n\n#Internal classes and functions end\n################################################################################\n#Commands start\n\nbrief_desc = 'Initialize a new campaign in the current channel'\nfull_desc = ('Usage: dnd-initialize\\n\\n'\n 'Initialize a new campaign in the current channel and prepare it '\n 'for processing transactions. The user invoking this command '\n 'becomes the GM of this campaign and has administrative powers.'\n '\\n\\nAfter using this command, you should register players or get'\n 'them to register using the dnd-register command.')\n\n@bot.command(brief = brief_desc, description = full_desc)\nasync def initialize(ctx):\n logging.info('Initializing new campaign in {0}.'.format(ctx.channel.id))\n\n if os.path.isfile('data/{0}'.format(ctx.channel.id)):\n logging.info('Campaign already exists; aborting.')\n await ctx.send('Campaign already exists in this channel.')\n return\n\n await dbm.add_campaign(Campaign(ctx.channel.id, ctx.author.id))\n\n logging.info('Initialization successful.')\n await ctx.send('New campaign initialized.'\n 'Register players with `dnd-register`.')\n\n################################################################################\n\nbrief_desc = 'Delete the campaign in the current channel'\nfull_desc = ('Usage: dnd-delete\\n\\n'\n 'Permanently delete the campaign the current channel, including '\n 'all registered players and previous transactions. This action is '\n 'irreversible. Only the GM can use this command. Use this command '\n 'without any arguments to view instructions to proceed.')\n\n@bot.command(brief = brief_desc, description = full_desc)\nasync def delete(ctx):\n logging.info('Deleting campaign in {0}.'.format(ctx.channel.id))\n\n if ctx.channel.id not in dbm.campaigns:\n logging.info('No campaign exists in this channel; aborting.')\n await ctx.send('No campaign exists in this channel.')\n return\n\n campaign = await dbm.load_campaign(ctx.channel.id, blocking = False)\n\n if ctx.author.id not in campaign.gms:\n logging.info('Unauthorized use of command; aborting.')\n await ctx.send('Only the GM can delete campaigns.')\n return\n\n try:\n intake = ctx.message.content.split(' ')[1]\n except IndexError:\n logging.info('No channel ID given; aborting')\n await ctx.send(\n 'Warning: campaign deletion is permanent and irreversible. '\n 'All players, balances and transactions will be wiped.\\n\\n'\n 'If you are sure you want to do this, retype this command '\n 'as `dnd-delete {0}` to delete it.'.format(campaign.id)\n )\n return\n\n try:\n id = int(intake)\n except ValueError:\n logging.info('Channel ID is not an integer; aborting')\n await ctx.send('Use your channel id `{0}`'.format(campaign.id))\n return\n\n if id != campaign.id:\n logging.info('Channel ID does not match campaign; aborting')\n await ctx.send('Use your channel id `{0}`'.format(campaign.id))\n return\n\n await dbm.del_campaign(campaign.id)\n\n logging.info('Deletion successful.')\n await ctx.send('Campaign has been deleted.')\n\n################################################################################\n\nbrief_desc = 'Register a user in the campaign under the given name'\nfull_desc = ('Usage: dnd-register ([user ID]) as [name]\\n\\n'\n 'Register the user in the campaign as [name] and initialize their '\n 'account with zero balance.\\n\\nOnly the GM may use the optional '\n '([user ID]) argument. When this argument is not supplied, the '\n 'user calling this command is registered under the given name.'\n '[name] is case sensitive, and may not contain spaces.')\n\n@bot.command(brief = brief_desc, description = full_desc)\nasync def register(ctx):\n logging.info('Registering new player in #{0}.'.format(ctx.channel.name))\n\n if ctx.channel.id not in dbm.campaigns:\n logging.info('No campaign exists in this channel; aborting.')\n await ctx.send('No campaign exists in this channel.')\n return\n\n try:\n arguments = ctx.message.content.split(' ')\n if arguments[1] == 'as':\n id = ctx.author.id\n name = arguments[2]\n elif arguments[2] == 'as':\n id = int(arguments[1])\n name = arguments[3]\n else:\n raise IndexError('Invalid syntax')\n except IndexError:\n await log_syntax_error(ctx)\n return\n\n campaign = await dbm.load_campaign(ctx.channel.id, blocking = False)\n\n if id in campaign.players:\n name = campaign.players[id].name\n logging.info('Name already exists in campaign; aborting.')\n await ctx.send('You are already registered as {0}.'.format(name))\n return\n\n if name in campaign.names:\n logging.info('Name already exists in campaign; aborting.')\n await ctx.send('That name is already taken.')\n return\n\n if name in RESERVED_NAMES:\n logging.info('Name is a reserved keyword; aborting.')\n await ctx.send('That name is a reserved keyword.')\n return\n\n campaign = await dbm.load_campaign(ctx.channel.id, blocking = True)\n\n campaign.players[id] = Player(id, name)\n campaign.names[name] = id\n\n await dbm.save_campaign(campaign)\n\n logging.info('Player \"{0}\" successfully registered.'.format(name))\n await ctx.send('Successfully registered {0}.'.format(name))\n\n################################################################################\n\nbrief_desc = 'Change the name under which a player is registered'\nfull_desc = ('Usage: dnd-reregister ([user ID]) as [name]\\n\\n'\n 'Reregister the user in the campaign as [name] retaining their '\n 'current account balance.\\n\\nOnly the GM may use the optional '\n '([user ID]) argument. When this argument is not supplied, the '\n 'user calling this command is reregistered under the given name.'\n '[name] is case sensitive, and may not contain spaces.')\n\n@bot.command(brief = brief_desc, description = full_desc)\nasync def reregister(ctx):\n logging.info('Reregistering new player in #{0}.'.format(ctx.channel.name))\n\n if ctx.channel.id not in dbm.campaigns:\n logging.info('No campaign exists in this channel; aborting.')\n await ctx.send('No campaign exists in this channel.')\n return\n\n try:\n arguments = ctx.message.content.split(' ')\n if arguments[1] == 'as':\n id = ctx.author.id\n name = arguments[2]\n elif arguments[2] == 'as':\n id = int(arguments[1])\n name = arguments[3]\n else:\n raise IndexError('Invalid syntax')\n except IndexError:\n await log_syntax_error(ctx)\n return\n\n campaign = await dbm.load_campaign(ctx.channel.id, blocking = False)\n\n if id not in campaign.players:\n logging.info('User is not currently registered; aborting.')\n await ctx.send('You are not registered in this campaign.')\n return\n\n if name in campaign.names:\n logging.info('Name already exists in campaign; aborting.')\n await ctx.send('That name is already taken.')\n return\n\n if name in RESERVED_NAMES:\n logging.info('Name is a reserved keyword; aborting.')\n await ctx.send('That name is a reserved keyword.')\n return\n\n campaign = await dbm.load_campaign(ctx.channel.id, blocking = True)\n\n del campaign.names[campaign.players[id].name]\n campaign.players[id].name = name\n campaign.names[name] = id\n \n await dbm.save_campaign(campaign)\n\n logging.info('Player \"{0}\" successfully reregistered.'.format(name))\n await ctx.send('Successfully reregistered as {0}.'.format(name))\n\n################################################################################\n\nbrief_desc = 'Convert a player\\'s money between different currencies'\nfull_desc = ('Usage: dnd-convert (as [initiator name]) [amounts]\\n\\nWithout '\n 'requiring authentication or GM approval, perform the specified '\n 'conversions in the caller\\'s account internally.\\n\\n[amounts] is '\n 'a collection of comma separated values, with each consisting '\n 'of an integer, followed by the unit to convert from, followed by '\n 'the keyword \"to\", followed by the unit to convert to. The units '\n 'may be any of CP, SP, GP, or PP. When converting up, the amount '\n 'to be converted must be an integer in the target unit. Only the '\n 'GM may use the (as [initiator name]) argument to specify the '\n 'conversion to take place in the account of [initiator name]')\n\n@bot.command(brief = brief_desc, description = full_desc)\nasync def convert(ctx):\n logging.info('Performing conversion in #{0}.'.format(ctx.channel.name))\n\n if ctx.channel.id not in dbm.campaigns:\n logging.info('No campaign exists in this channel; aborting.')\n await ctx.send('No campaign exists in this channel.')\n return\n\n try:\n arguments = ctx.message.content.split(' ', maxsplit = 1)[1].split(',')\n except IndexError:\n await log_syntax_error(ctx)\n return\n\n campaign = await dbm.load_campaign(ctx.channel.id, blocking = False)\n\n if arguments[0].strip().split(' ', maxsplit = 1)[0] == 'as':\n if ctx.author.id in campaign.gms:\n _kw, name, arguments[0] = arguments[0].split(' ', maxsplit = 2)\n if name in campaign.names:\n initiator = campaign.players[campaign.names[name]]\n else:\n logging.info('Invalid initiator name; aborting.')\n await ctx.send('No player with name \"{0}\"'.format(name)\n + ' exists in this campaign.')\n return\n else:\n logging.info('Unauthorized use of \"as\"; aborting.')\n await ctx.send('You are not authorized to use \"as\".')\n return\n else:\n if ctx.author.id in campaign.players:\n initiator = campaign.players[ctx.author.id]\n else:\n logging.info('Unregistered user; aborting.')\n await ctx.send('You are not registered in this campaign.')\n return\n\n amounts = {'cp': 0, 'sp': 0, 'gp': 0, 'pp': 0}\n for argument in arguments:\n try:\n starting, target_unit = argument.lower().split(' to ')\n starting_amt, starting_unit = starting.strip().split(' ')\n starting_amt = int(starting_amt)\n conv_factor = CONVERSIONS[starting_unit]/CONVERSIONS[target_unit]\n if not (starting_amt*conv_factor).is_integer():\n logging.info('Invalid up-conversion; aborting.')\n await ctx.send('Cannot convert {0} {1} to {2}.'.format(\n starting_amt, starting_unit.upper(), target_unit.upper()))\n return\n amounts[starting_unit] -= starting_amt\n amounts[target_unit] += int(starting_amt*conv_factor)\n except (IndexError, ValueError):\n await log_syntax_error(ctx)\n return\n\n campaign = await dbm.load_campaign(ctx.channel.id, blocking = True)\n \n transaction = Transaction(initiator, 'take', amounts, None, 'conversion')\n transaction.complete()\n\n await dbm.save_campaign(campaign)\n\n logging.info('Conversion successful.')\n await ctx.send('Successfully converted currency.')\n\n################################################################################\n\nbrief_desc = 'Make a transaction request and add it to the queue'\nfull_desc = ('Usage: dnd-transact (as [initiator name]) give/take [amounts] '\n '(at [+/-][offset]%) (to/from [participant name]) (for [reason])'\n '\\n\\nAdd a transaction request to the queue for adding or '\n 'subtracting the given [amounts] to the involved parties\\' '\n 'accounts.\\n\\nOnly the GM may use the optional (as [initiator '\n 'name]) argument. When this argument is not supplied, the user '\n 'calling this command is made the initiator of the transaction. '\n '\\n\\nThe required argument give/take [amounts] decides whether '\n 'the money is credited to or debited from the initiator\\'s '\n 'account. [amounts] is a collection of comma separated values '\n 'consisting of a number followed by the unit, which may be one of '\n 'CP, SP, GP, PP, or EGP. Capitalisation is not required. For '\n 'example, \"give 400 sp\", \"take 2 CP, 5 SP\", and \"give 24.5 EGP\" '\n 'are all syntactically valid. Note that only EGP values can be '\n 'non-integers, and only up to two decimal points.\\n\\nThe optional '\n 'argument (at [+/-][offset]%) allows for adding a percentage '\n 'offset to the transaction for the purposes of discounts and '\n 'price hikes. [+/-][offset] is a signed integer that determines '\n 'the type and magnitude of the offset. For example, \"+5%\" and '\n '\"-20%\" are both syntactically valid.\\n\\nThe optional argument '\n '(to/from [participant name]) designates the other participant in '\n 'the transaction, if one exists. When this argument is not '\n 'supplied, the other participant is assumed to be an NPC or other '\n 'similar entity, and hence the money is practically created or '\n 'destroyed. Note that the to/from term must be consistent with '\n 'the preceding give/take term in order to be syntactically valid. '\n '\\n\\nThe optional argument (for [reason]) allows for adding a '\n 'note to the transaction for record keeping and ease of '\n 'identification. [reason] can be an arbitrarily long string, '\n 'though it is recommended that it be kept brief for clarity. '\n '\\n\\nA complete use of the command leveraging all the arguments '\n 'may look as follows:\\ndnd-transact as player1 give 45 gp at -20% '\n 'to player2 for buying used scale mail')\n\n@bot.command(brief = brief_desc, description = full_desc)\nasync def transact(ctx):\n logging.info('Attempting transaction in #{0}.'.format(ctx.channel.name))\n\n if ctx.channel.id not in dbm.campaigns:\n logging.info('Campaign is not initialized; aborting.')\n await ctx.send('No campaign exists in this channel.')\n return\n\n keywords = {'as', 'give', 'take', 'at', 'to', 'from', 'for'}\n arguments = ctx.message.content.split(' ')[-1:0:-1]\n active_kw = arguments.pop()\n\n if active_kw not in keywords:\n await log_syntax_error(ctx)\n return\n\n parsed_args = {}\n while arguments:\n argument = arguments.pop()\n if active_kw == 'for':\n parsed_args[active_kw] = argument\n while arguments:\n parsed_args[active_kw] += ' ' + arguments.pop()\n elif argument in keywords:\n active_kw = argument\n elif active_kw in parsed_args:\n parsed_args[active_kw] += ' ' + argument\n else:\n parsed_args[active_kw] = argument\n\n campaign = await dbm.load_campaign(ctx.channel.id, blocking = False)\n\n if 'as' in parsed_args:\n if ctx.author.id in campaign.gms:\n name = parsed_args['as']\n if name in campaign.names:\n initiator = campaign.players[campaign.names[name]]\n else:\n logging.info('Invalid initiator name; aborting.')\n await ctx.send('No player with name \"{0}\"'.format(name)\n + ' exists in this campaign.')\n return\n else:\n logging.info('Unauthorized use of \"as\"; aborting.')\n await ctx.send('You are not authorized to use \"as\".')\n return\n else:\n if ctx.author.id in campaign.players:\n initiator = campaign.players[ctx.author.id]\n else:\n logging.info('Unregistered user; aborting.')\n await ctx.send('You are not registered in this campaign.')\n return\n\n if 'give' in parsed_args:\n mode = 'give'\n elif 'take' in parsed_args:\n mode = 'take'\n else:\n await log_syntax_error(ctx)\n return\n\n amounts = {'cp': 0, 'sp': 0, 'gp': 0, 'pp': 0}\n intake = [term.strip() for term in parsed_args[mode].split(',')]\n for term in intake:\n term = term.split(' ')\n try:\n amount = float(term[0])\n except ValueError:\n await log_syntax_error(ctx)\n return\n if term[1].lower() in amounts:\n amounts[term[1].lower()] += int(amount)\n elif term[1].lower() == 'egp':\n convert_from_egp(amount, amounts)\n else:\n await log_syntax_error(ctx)\n return\n\n if 'at' in parsed_args:\n intake = parsed_args['at']\n try:\n amount = int(intake[1:-1])\n except ValueError:\n await log_syntax_error(ctx)\n return\n if intake[0] == '+':\n mult = 1\n elif intake[0] == '-':\n mult = -1\n else:\n await log_syntax_error(ctx)\n return\n egp_eq = convert_to_egp(amounts)\n egp_eq = egp_eq*(1 + 0.01*amount*mult)\n amounts = convert_from_egp(egp_eq)\n\n if 'to' in parsed_args:\n if mode == 'give':\n intake = parsed_args['to']\n participant = True\n else:\n await log_syntax_error(ctx)\n return\n elif 'from' in parsed_args:\n if mode == 'take':\n intake = parsed_args['from']\n participant = True\n else:\n await log_syntax_error(ctx)\n return\n else:\n participant = False\n\n if participant:\n if intake in campaign.names:\n participant = campaign.players[campaign.names[intake]]\n else:\n logging.info('Invalid participant name; aborting.')\n await ctx.send('No player with name \"{0}\"'.format(initiator)\n + ' exists in this campaign.')\n return\n else:\n participant = None\n\n if 'for' in parsed_args:\n reason = parsed_args['for']\n else:\n reason = None\n\n campaign = await dbm.load_campaign(ctx.channel.id, blocking = True)\n\n transaction = Transaction(initiator, mode, amounts, participant, reason)\n campaign.add_transaction(transaction)\n\n await dbm.save_campaign(campaign)\n\n logging.info('Successfully added transaction to queue.')\n await ctx.send('Transaction recorded; waiting for approval.')\n\n################################################################################\n\nbrief_desc = 'View transactions that are waiting for approval'\nfull_desc = ('Usage: dnd-pending\\n\\n'\n 'Show all transactions that can be approved by the user calling '\n 'this command. Note that only the participant in the transaction '\n '(not the initiator) can approve pending transactions, with only '\n 'the GM being able to view (and approve) all transactions.')\n\n@bot.command(brief = brief_desc, description = full_desc)\nasync def pending(ctx):\n logging.info('Displaying pending in #{0}.'.format(ctx.channel.name))\n\n if ctx.channel.id not in dbm.campaigns:\n logging.info('Campaign is not initialized; aborting.')\n await ctx.send('No campaign exists in this channel.')\n return\n\n campaign = await dbm.load_campaign(ctx.channel.id)\n\n msg = ''\n id = 1\n for transaction in campaign.pending:\n if ctx.author.id in (transaction.participant.id, *campaign.gms):\n msg += str(id) + ': `' + transaction.text + '`\\n'\n id += 1\n msg = msg[ :-1]\n\n if not msg:\n logging.info('No pending transactions.')\n await ctx.send('You have no pending transactions.')\n else:\n logging.info('Transactions successfully displayed.')\n await ctx.send('Pending transactions:\\n' + msg)\n\n################################################################################\n\nbrief_desc = 'Approve a transaction currently in the queue'\nfull_desc = ('Usage: dnd-approve [IDs and slices]\\n\\n'\n 'Approve pending transactions with the given IDs and those '\n 'contained within the ID slices. The IDs can be obtained by using '\n 'the dnd-pending command. The [IDs and slices] argument is a set '\n 'of comma separated values containing either IDs or ID slices. An '\n 'ID slice consists of a lower ID bound followed by a hyphen and a '\n 'upper ID bound, and selects the bounding IDs as well as all IDs '\n 'between them. For example, \"1, 2, 4\", \"2-5, 7\", and \"1-3, 6-7\" '\n 'are all syntactically valid. \"all\" and \"last\" are keywords that'\n 'additionally add the respective transactions to the list.')\n\n@bot.command(brief = brief_desc, description = full_desc)\nasync def approve(ctx):\n logging.info('Approving transactions in #{0}.'.format(ctx.channel.name))\n\n if ctx.channel.id not in dbm.campaigns:\n logging.info('Campaign is not initialized; aborting.')\n await ctx.send('No campaign exists in this channel.')\n return\n\n campaign = await dbm.load_campaign(ctx.channel.id, blocking = False)\n\n try:\n terms = ctx.message.content.split(' ', 1)[1].strip()\n approved_indices = await parse_indices(ctx, campaign, terms)\n except IndexError:\n await log_syntax_error(ctx)\n return\n\n if approved_indices is None:\n return\n elif not approved_indices:\n logging.info('No accessible transactions; aborting.')\n await ctx.send('Invalid indicies or no pending transactions.')\n\n campaign = await dbm.load_campaign(ctx.channel.id, blocking = True)\n\n campaign.approve(approved_indices)\n\n await dbm.save_campaign(campaign)\n\n logging.info('Successfully approved transactions.')\n await ctx.send('Transaction(s) successfully approved.')\n\n################################################################################\n\nbrief_desc = 'Deny a transaction currently in the queue'\nfull_desc = ('Usage: dnd-deny [IDs and slices]\\n\\n'\n 'Deny pending transactions with the given IDs and those contained '\n 'within the ID slices. The IDs can be obtained by using the '\n 'dnd-pending command. The [IDs and slices] argument is a set '\n 'of comma separated values containing either IDs or ID slices. An '\n 'ID slice consists of a lower ID bound followed by a hyphen and a '\n 'upper ID bound, and selects the bounding IDs as well as all IDs '\n 'between them. For example, \"1, 2, 4\", \"2-5, 7\", and \"1-3, 6-7\" '\n 'are all syntactically valid. \"all\" and \"last\" are keywords that'\n 'additionally add the respective transactions to the list.')\n\n@bot.command(brief = brief_desc, description = full_desc)\nasync def deny(ctx):\n logging.info('Denying transactions in #{0}.'.format(ctx.channel.name))\n\n if ctx.channel.id not in dbm.campaigns:\n logging.info('Campaign is not initialized; aborting.')\n await ctx.send('No campaign exists in this channel.')\n return\n\n campaign = await dbm.load_campaign(ctx.channel.id, blocking = False)\n\n terms = ctx.message.content.split(' ', 1)[1].strip()\n denied_indices = await parse_indices(ctx, campaign, terms)\n\n if denied_indices is None:\n return\n elif not denied_indices:\n logging.info('No accessible transactions; aborting.')\n await ctx.send('Invalid indicies or no pending transactions.')\n\n campaign = await dbm.load_campaign(ctx.channel.id, blocking = True)\n\n campaign.deny(denied_indices)\n\n await dbm.save_campaign(campaign)\n\n logging.info('Successfully denied transactions.')\n await ctx.send('Transaction(s) denied.')\n\n################################################################################\n\nbrief_desc = 'View the account balance of a user'\nfull_desc = ('Usage: dnd-balance (of [name])\\n\\n'\n 'Show the balance in the account of a player. Only the GM may use '\n 'the optional (of [name]) argument. When this argument is not '\n 'supplied, the balance of the user calling the command is shown.'\n '\\n\\nIf the keyword \"all\" is supplied instead of a player name,'\n 'the balances of all registered players is displayed.')\n\n@bot.command(brief = brief_desc, description = full_desc)\nasync def balance(ctx):\n logging.info('Displaying balance in #{0}.'.format(ctx.channel.name))\n\n if ctx.channel.id not in dbm.campaigns:\n logging.info('Campaign is not initialized; aborting.')\n await ctx.send('No campaign exists in this channel.')\n return\n\n campaign = await dbm.load_campaign(ctx.channel.id)\n\n arguments = ctx.message.content.split(' ')\n if len(arguments) > 1:\n try:\n if arguments[1] == 'of':\n if ctx.author.id in campaign.gms:\n target = arguments[2]\n else:\n logging.info('Unauthorized use of \"of\"; aborting.')\n await ctx.send('You are not authorized to use \"of\".')\n return\n else:\n raise IndexError('Invalid syntax')\n except IndexError:\n await log_syntax_error(ctx)\n return\n elif ctx.author.id in campaign.players:\n target = campaign.players[ctx.author.id].name\n else:\n logging.info('Unregistered user; aborting.')\n await ctx.send('You are not registered in this campaign.')\n return\n\n if target == 'all':\n msg = ''\n for id in campaign.players:\n msg += '`' + campaign.players[id].name + ': '\n msg += campaign.players[id].balance + '`\\n'\n elif target in campaign.names:\n msg = '`' + campaign.players[campaign.names[target]].balance + '`'\n else:\n logging.info('Invalid participant name; aborting.')\n await ctx.send('No player with name \"{0}\"'.format(target)\n + ' exists in this campaign.')\n return\n\n logging.info('Successfully displayed balance of {0}.'.format(target))\n await ctx.send('Account balance for {0}:\\n'.format(target) + msg)\n\n################################################################################\n\nbrief_desc = 'Roll dice of the given type and quantity'\nfull_desc = ('Usage: dnd-roll ([number])d[sides](+[offset])\\n\\n'\n 'Roll [number] [sides]-sided dice with a [offset] roll modifier. '\n 'Only the [sides] argument is required, but all values must be '\n 'positive integers. For example, \"dnd-roll 4d8+3\" is valid.')\n\n@bot.command(brief = brief_desc, description = full_desc)\nasync def roll(ctx):\n logging.info('Rolling dice in #{0}.'.format(ctx.channel.name))\n\n try:\n intake = ctx.message.content.split(' ')[1]\n except IndexError:\n await log_syntax_error(ctx)\n return\n\n if len(intake.split('d')) != 2:\n await log_syntax_error()\n return\n\n rolls = intake.split('d')[0]\n if rolls:\n try:\n rolls = int(rolls)\n except ValueError:\n logging.info('Invalid roll number; aborting.')\n await ctx.send('\"{0}\" is an invalid number of rolls.'.format(rolls))\n return\n else:\n rolls = 1\n\n sides = intake.split('d')[1].split('+')[0]\n try:\n sides = int(sides)\n except ValueError:\n logging.info('Invalid roll sides; aborting.')\n await ctx.send('\"{0}\" is an invalid number of sides.'.format(rolls))\n return\n\n try:\n offset = int(intake.split('d')[1].split('+')[1])\n except IndexError:\n offset = 0\n except ValueError:\n logging.info('Invalid roll offset; aborting.')\n await ctx.send('\"{0}\" is an invalid offset.'.format(rolls))\n return\n\n if rolls <= 100:\n results = [1 + random.randrange(sides) for _ in range(rolls)]\n else:\n try:\n mu = rolls*(sides + 1)/2\n sigma = math.sqrt(rolls*(sides**2 - 1)/12)\n except OverflowError:\n logging.info('Overflow during calculation; aborting')\n await ctx.send('The number of rolls or sides is too large.')\n return\n result = round(random.gauss(mu, sigma))\n result = min(result, rolls*sides)\n result = max(result, rolls)\n results = [result]\n\n final = sum(results) + offset\n\n breakdown = ' + '.join(str(result) for result in results)\n breakdown = '||({0}) + {1}||'.format(breakdown, offset)\n\n msg = 'Rolled {0}: **{1}**\\n{2}'.format(intake, final, breakdown)\n if len(msg) >= 2000:\n msg = 'Roll result: {0}'.format(final)\n if len(msg) >= 2000:\n msg = 'Roll result too large to display'\n\n await ctx.send(msg)\n\n################################################################################\n\nbrief_desc = 'Export the transaction history of this campaign'\nfull_desc = ('Usage: dnd-history\\n\\n'\n 'Export the campaign transaction history as a .csv file. ')\n\n@bot.command(brief = brief_desc, description = full_desc)\nasync def history(ctx):\n logging.info('Exporting history in #{0}.'.format(ctx.channel.name))\n\n if ctx.channel.id not in dbm.campaigns:\n logging.info('No campaign exists in this channel; aborting.')\n await ctx.send('No campaign exists in this channel.')\n return\n\n campaign = await dbm.load_campaign(ctx.channel.id, blocking = False)\n\n csv = Campaign.to_csv(campaign)\n name = '{0}.csv'.format(ctx.channel.name)\n\n logging.info('Generated history for #{0}.'.format(ctx.channel.name))\n await ctx.send(file=discord.File(io.StringIO(csv), name))\n\n#Commands end\n################################################################################\n#Events start\n\n@bot.event\nasync def on_message(message):\n if message.author == bot.user:\n return\n\n await bot.process_commands(message)\n\n\n@bot.event\nasync def on_command_error(ctx, error):\n logging.error('Error in {0}: {1}\"'.format(ctx.message.content, error))\n await ctx.send('Error processing command. Use `dnd-help` to view help.')\n\n\n@bot.event\nasync def on_ready():\n logging.info('Logged in as {0.name} (ID: {0.id})'.format(bot.user))\n await bot.change_presence(activity = discord.Game(name = status_message))\n\n#Events end\n################################################################################\n#Initialization start\n\nif __name__ == '__main__':\n token = '' #Manually add token here.\n status_message = 'D&D (dnd-help)'\n\n if token == '': #Get token if it's not already in the code.\n try:\n file = open('token.txt')\n token = file.read()\n file.close()\n logging.info(\"Token acquired from file.\")\n except FileNotFoundError:\n logging.warning(\"Token file not found.\")\n try:\n token = os.environ['DND_TOKEN']\n logging.info(\"Token acquired from environment variable.\")\n except KeyError:\n logging.warning(\"Token environment variable not found.\")\n logging.error(\"Token auto detection failed. Aborting.\")\n input(\"Press enter to quit.\")\n quit()\n else:\n logging.info(\"Token acquired from code.\")\n\n dbm = DatabaseManager()\n logging.info('{0} existing campaigns loaded.'.format(len(dbm.campaigns)))\n\n bot.run(token)\n","sub_path":"dnd_bot.py","file_name":"dnd_bot.py","file_ext":"py","file_size_in_byte":41326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"382122587","text":"import os\nfrom PyPDF2 import PdfFileReader, PdfFileWriter\nimport sys\n\n\npath = \"C:/Users/Richa/OneDrive/Desktop/Real_python1/Chapter3/PDF\"\n\ninput_file_name=os.path.join(path, \"GypsyRover.pdf\")\ninput_file = PdfFileReader(input_file_name)\n\nprint(\"Title\", input_file.getDocumentInfo().title)\nprint(\"Author: \", input_file.getDocumentInfo().author)\nprint(\"Number of pages: \", input_file.getNumPages())\n\noutput_file_path = os.path.join(path, \"The Whisteling Gypsy.txt\")\nwith open(output_file_path, \"w\") as output_file:\n for page in range(0, input_file.getNumPages()):\n text = input_file.getPage(page_num).extractText()\n text = text.encode(\"utf-8\")\n output_file.write(text)\n","sub_path":"Chapter3/PDF/WhistelingGypsy.py","file_name":"WhistelingGypsy.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"433755256","text":"#baseball/roster/admin.py\n\nfrom django.contrib import admin\nfrom roster.models import Player\n\n# Register your models here.\n\nclass MembershipInline(admin.TabularInline):\n model = Player\n\nclass PlayerAdmin(admin.ModelAdmin):\n search_fields = ('name',)\n \n\nadmin.site.register(Player, PlayerAdmin)\n\n ","sub_path":"roster/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"542761542","text":"import networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom random import randint,random\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport torch\nimport pickle,os,math\nimport scipy.sparse as sparse\nfrom collections import Counter\nfrom matplotlib.ticker import MaxNLocator\nfrom sklearn.cluster import DBSCAN,SpectralClustering\nimport cupy as cp\nfrom torch.utils.dlpack import from_dlpack, to_dlpack\nfrom cupy.core.dlpack import toDlpack,fromDlpack\nimport link_prediction as lp\nfrom collections import defaultdict\nimport pdb\n\n\ndef get_key (dict, value):\n return [k for k, v in dict.items() if v == value]\n \n \ndef weights_array_to_cluster_quality(weights_array, adj_mat, num_clusters,\n eigen_solver, assign_labels, epsilon,\n is_testing=False):\n # t1 = time.time()\n clustering_labels = cluster_net(num_clusters, adj_mat, eigen_solver, assign_labels)\n # t2 = time.time()\n ncut_val = compute_ncut(adj_mat, clustering_labels, epsilon, verbose=is_testing)\n\n if is_testing:\n ncut_val_previous_method = ncut(weights_array, num_clusters, clustering_labels, epsilon)\n print('NCUT Current', ncut_val)\n print('NCUT Previous', ncut_val_previous_method)\n assert math.isclose(ncut_val, ncut_val_previous_method, abs_tol=1e-5)\n\n return ncut_val, clustering_labels\n\n\ndef WeightsToAdjaency(Weights,startNodeNums):\n M,N=Weights.shape\n GWeight=nx.Graph()\n GWeight.add_nodes_from(range(M+N))\n G1=GWeight\n for i in range(M):\n for j in range(N):\n GWeight.add_weighted_edges_from([(i+startNodeNums,j+M+startNodeNums,Weights[i,j])])\n\n G1.add_edge(i,j+M)\n \n \"\"\"print(\"Diconnected points is {}\".format(list(nx.isolates(G))))\n G.remove_nodes_from(list(nx.isolates(G)))\"\"\"\n GWeight=GWeight.to_undirected()\n G1=G1.to_undirected()\n return GWeight,G1\n\n\ndef GraphPartition(G):\n G.remove_nodes_from(list(nx.isolates(G)))\n #Degree_distribution(G)\n partition=community_louvain.best_partition(G)\n pos=community_layout(G,partition)\n return pos,partition\n\ndef cluster_net(n_clusters, adj_mat, eigen_solver, assign_labels):\n cluster_alg = SpectralClustering(n_clusters=n_clusters,\n eigen_solver=eigen_solver,\n affinity='precomputed',\n assign_labels=assign_labels)\n clustering = cluster_alg.fit(adj_mat)\n return clustering.labels_\n\ndef delete_isolated_ccs(weight_array, adj_mat):\n # find connected components that aren't represented on both the first and\n # the last layer, and delete them from the graph\n\n nc, labels = sparse.csgraph.connected_components(adj_mat, directed=False)\n\n # if there's only one connected component, don't bother\n if nc == 1:\n return weight_array, adj_mat\n \n widths = weights_to_layer_widths(weight_array)\n\n # find cc labels represented in the first layer\n initial_ccs = set()\n for i in range(widths[0]):\n initial_ccs.add(labels[i])\n # find cc labels represented in the final layer\n final_ccs = set()\n final_layer = len(widths) - 1\n for i in range(widths[-1]):\n neuron = mlp_tup_to_int((final_layer, i), widths)\n final_ccs.add(labels[neuron])\n\n # find cc labels that aren't in either of those two sets\n isolated_ccs = set()\n for c in range(nc):\n if not (c in initial_ccs and c in final_ccs):\n isolated_ccs.add(c)\n\n # if there aren't any isolated ccs, don't bother deleting them!\n if not isolated_ccs:\n return weight_array, adj_mat\n\n # go through weight_array\n # for each array, go to the rows and cols\n # figure out which things you have to delete, then delete them\n new_weight_array = []\n for (t, mat) in enumerate(weight_array):\n # print(\"weight array number:\", t)\n n_rows, n_cols = mat.shape\n # print(\"original n_rows, n_cols:\", (n_rows, n_cols))\n rows_layer = t\n cols_layer = t + 1\n\n # delete rows and cols corresponding to neurons in isolated clusters\n rows_to_delete = []\n for i in range(n_rows):\n neuron = mlp_tup_to_int((rows_layer, i), widths)\n if labels[neuron] in isolated_ccs:\n rows_to_delete.append(i)\n\n cols_to_delete = []\n for j in range(n_cols):\n neuron = mlp_tup_to_int((cols_layer, j), widths)\n if labels[neuron] in isolated_ccs:\n cols_to_delete.append(j)\n\n # print(\"rows to delete:\", rows_to_delete)\n # print(\"columns to delete:\", cols_to_delete)\n\n rows_deleted = np.delete(mat, rows_to_delete, 0)\n new_mat = np.delete(rows_deleted, cols_to_delete, 1)\n # print(\"new mat shape:\", new_mat.shape)\n new_weight_array.append(new_mat)\n\n # then return the adj_mat\n new_adj_mat = weights_to_graph(new_weight_array)\n return new_weight_array, new_adj_mat\n\n\n\ndef weights_to_graph(weights_array):\n # take an array of weight matrices, and return the adjacency matrix of the\n # neural network it defines.\n # if the weight matrices are A, B, C, and D, the adjacency matrix should be\n # [[0 A^T 0 0 0 ]\n # [A 0 B^T 0 0 ]\n # [0 B 0 C^T 0 ]\n # [0 0 C 0 D^T]\n # [0 0 0 D 0 ]]\n # however, the weight matrices we get are A^T etc.\n\n block_mat = []\n\n # for everything in the weights array, add a row to block_mat of the form\n # [None, None, ..., sparsify(np.abs(mat)), None, ..., None]\n for (i, mat) in enumerate(weights_array):\n mat=np.maximum(mat,0) \n sp_mat = sparse.coo_matrix(np.abs(mat))\n if i == 0:\n # add a zero matrix of the right size to the start of the first row\n # so that our final matrix is of the right size\n n = mat.shape[0]\n first_zeroes = sparse.coo_matrix((n, n))\n block_row = [first_zeroes] + [None]*len(weights_array)\n else:\n block_row = [None]*(len(weights_array)+1)\n block_row[i+1] = sp_mat\n block_mat.append(block_row)\n\n # add a final row to block_mat that's just a bunch of [None]s followed by a\n # zero matrix of the right size\n m = weights_array[-1].shape[1]\n final_zeroes = sparse.coo_matrix((m, m))\n nones_row = [None]*len(weights_array)\n nones_row.append(final_zeroes)\n block_mat.append(nones_row)\n\n # turn block_mat into a sparse matrix\n up_tri = sparse.bmat(block_mat, 'csr')\n\n # we now have a matrix that looks like\n # [[0 A^T 0 0 ]\n # [0 0 B^T 0 ]\n # [0 0 0 C^T]\n \n # [0 0 0 0 ]]\n # add this to its transpose to get what we want\n adj_mat = up_tri + up_tri.transpose()\n return adj_mat\n\ndef ToBlockMatrix(weights):\n M,N=weights.shape\n A11=np.zeros((M,M))\n A12=weights\n A21=np.transpose(weights)\n A22=np.zeros((N,N))\n BlockMatrix = np.block([[A11, A12], [A21, A22]])\n return BlockMatrix\n\n\ndef Compute_fiedler_vector(G):\n nrom_laplacian_matrics = nx.normalized_laplacian_matrix(G,weight='weight')\n nrom_laplacian_matrics_cupy=cp.asarray(nrom_laplacian_matrics.toarray())\n w,v=cp.linalg.eigh(nrom_laplacian_matrics_cupy)\n #algebraic_connectivity,fiedler_vector=power_iteration(nrom_laplacian_matrics.)\n algebraic_connectivity = w[1] # Neat measure of how tight the graph is\n fiedler_vector = v[:,1].T\n fiedler_vector=torch.Tensor(cp.asarray(cp.real(fiedler_vector)))\n algebraic_connectivity=torch.Tensor(cp.asarray(algebraic_connectivity))\n return algebraic_connectivity, fiedler_vector\n\ndef Fiedler_vector_cluster(G,startClassi):\n algebraic_connectivity, fiedler_vector=Compute_fiedler_vector(G)\n PartOne=[]\n PartTwo=[]\n for node in range(G.number_of_nodes()):\n if fiedler_vector[node].item()<0:\n PartOne.append(node)\n else:\n PartTwo.append(node)\n PartitionResults={startClassi+0:PartOne,startClassi+1:PartTwo}\n G1=nx.Graph()\n G2=nx.Graph()\n G1.add_nodes_from(PartOne)\n G2.add_nodes_from(PartTwo)\n for (i,j) in G.edges():\n if i in G1.nodes() and j in G1.nodes():\n G1.add_edge(i,j)\n \n for (i,j) in G.edges():\n if i in G2.nodes() and j in G2.nodes():\n G2.add_edge(i,j)\n return [G1,G2]\n\n\ndef chooseSemiMatrix(Weight,locx,M):\n semipart=int((M-1)/2)\n if locx=semipart and locx<(M-semipart):\n ChooseWeights=Weight[locx-semipart:locx+semipart+1]\n else:\n ChooseWeights=Weight[-M:]\n return ChooseWeightspp \n\n\ndef WeightedLinkPrediction(G,cluters,LinkPredictionMethod,VectorPairs):\n PartitionClassi=set([*cluters.keys()])\n predLinkWeight=[]\n AddLinkGraph=nx.Graph()\n for OneClassi in PartitionClassi:\n oneClassNodes=cluters[OneClassi]\n SubGraph=nx.Graph()\n SubGraph.add_nodes_from(oneClassNodes)\n #l\n for (i,j) in G.edges:\n if (i in SubGraph.nodes()) and (j in SubGraph.nodes()) and 'weight' in G.get_edge_data(i,j):\n SubGraph.add_weighted_edges_from([(i,j,G.get_edge_data(i,j)['weight'])])\n else:\n continue\n if SubGraph.number_of_edges()>=2:\n diag,vector=Compute_fiedler_vector(SubGraph)\n for iter1 in range(VectorPairs):\n if torch.min(vector)<0:\n locx=torch.argmax(vector).tolist()\n locy=torch.argmin(vector).tolist()\n StartNode=oneClassNodes[locx]\n EndNode=oneClassNodes[locy]\n WrongLink=[tuple(sorted([StartNode,EndNode]))]\n vector=np.delete(vector,locx-1)\n vector=np.delete(vector,locy-1)\n #AddLinkGraph.add_edge(StartNode,EndNode)\n preds=getattr(nx,LinkPredictionMethod)(SubGraph,WrongLink)\n for u,v,p in preds:\n predLinkWeight.append((u,v,p))\n else:\n continue\n\n ## save\n \"\"\"AddedLinkGraphResultsFiles= \"Results/PartitionResults/AddedLindedGraph.pkl\"\n fwG=open(AddedLinkGraphResultsFiles,'wb')\n pickle.dump(G,fwG)\"\"\"\n return predLinkWeight\n\ndef FindDuplicated(a):\n duplicated = set() \n for i in range(0, len(a)):\n if a[i] in a[i+1:]:\n duplicated.add(a[i])\n return duplicated\n\n \n\ndef WeightCorrection(classiResultsFiles,num_classes,GraphResultsFiles,GraphPartitionVisualization,\n OptimizedNet,PredAddEdgeResults,LinkPredictionMethod,VectorPairs,WeightCorrectionCoeffi,UseOld):\n if os.path.exists(PredAddEdgeResults) and UseOld==True:\n predLinkWeight=np.load(PredAddEdgeResults)\n else:\n Graph_array,Gragh_unwighted_array=[],[]\n LayerNodeNum=[]\n startNodeNums=0\n state_dict = OptimizedNet.state_dict()\n if os.path.exists(classiResultsFiles) and os.path.exists(GraphResultsFiles) and UseOld==True:\n frC=open(classiResultsFiles,'rb')\n PartitionResults=pickle.load(frC)\n\n frG=open(GraphResultsFiles,'rb')\n G=pickle.load(frG)\n L=nx.adjacency_matrix(G)\n incidence_matrix=nx.incidence_matrix(G)\n algebraic_connectivity,fiedler_vector=Compute_fiedler_vector(G)\n\n else:\n for layer_name in state_dict:\n if (\"layers\" in layer_name) and (\"weight\" in layer_name):\n Weight=state_dict[layer_name]\n print(Weight.shape)\n if Weight.dim()==3:\n Weight=torch.squeeze(Weight)\n DimCompress=True\n Weight=Weight.cpu().detach().numpy()\n Gone,G_unweighted=WeightsToAdjaency(Weight,startNodeNums)\n startNodeNums+=Gone.number_of_nodes()\n LayerNodeNum.append(Gone.number_of_nodes())\n Graph_array.append(Gone)\n Gragh_unwighted_array.append(G_unweighted)\n G= nx.compose(Graph_array[0],Graph_array[1])\n Gu= nx.compose(Gragh_unwighted_array[0],Gragh_unwighted_array[1])\n L=nx.adjacency_matrix(G)\n incidence_matrix=nx.incidence_matrix(Gu)\n #comps=nx.connected_components(G)\n G_array=[G]\n iter1=0\n while len(G_array) < num_classes and iter10:\n Gsub=Fiedler_vector_cluster(G_array[iter2],0+2*iter2)\n for i in range(len(Gsub)):\n print(iter2,i,Gsub[i].number_of_edges(),Gsub[i].number_of_nodes(),\n Gsub[i].number_of_nodes()/G.number_of_nodes())\n #pdb.set_trace()\n\n G_array_tmp.append(Gsub[i])\n tmp1+=len(list(Gsub[i].nodes))\n PartitionResults.update({lab:list(Gsub[i].nodes)})\n \n \n for node in Gsub[i].nodes:\n if node in partition:\n \"New dict is {}, old dict is {}\".format({node:lab},{node,partition[node]})\n partition.update({node:lab})\n print(\"partition num is:\",len(PartitionResults))\n lab+=1\n \n else:\n tmp1+=len(list(G_array[iter2].nodes))\n PartitionResults.update({k:list(G_array[iter2].nodes)})\n for node in G_array[iter2].nodes:\n if node in partition:\n \"New dict is {}, old dict is {}\".format({node:lab},{node,partition[node]})\n partition.update({node:lab})\n lab+=1\n print(\"The graph is no edge\")\n print(\"is equal 1\",tmp1==G.number_of_nodes())\n if (tmp1==G.number_of_nodes())==False:\n pdb.set_trace()\n print(\"here\")\n if (len(partition)==G.number_of_nodes())==False:\n print(G.number_of_nodes()-len(partition))\n pdb.set_trace()\n\n\n iter1+=1\n G_array=G_array_tmp \n \n \n \"\"\"partitionNew={}\n tmp2=0\n elements=[]\n for key in PartitionResults:\n elements=elements+PartitionResults[key]\n duplicated=FindDuplicated(elements)\n if len(duplicated)>0:\n print(\"{} becomes duplicated num is {}:\".format(key,len(duplicated),duplicated))\n for value in PartitionResults[key]:\n partitionNew.update({value: key})\n tmp2+=len(PartitionResults[key])\n print(\"is equal 2\",tmp2==len(partitionNew))\n if (tmp2==len(partitionNew))==False:\n print(tmp2-len(partitionNew))\n pdb.set_trace()\"\"\"\n\n\n ### saving\n fwC=open(classiResultsFiles,'wb')\n pickle.dump(PartitionResults,fwC)\n\n fwG=open(GraphResultsFiles,'wb')\n pickle.dump(G,fwG)\n predLinkWeight=WeightedLinkPrediction(G,PartitionResults,LinkPredictionMethod,VectorPairs)\n np.save(PredAddEdgeResults,predLinkWeight)\n \n if len(predLinkWeight)==0:\n pass\n else:\n print(predLinkWeight)\n state_dict = OptimizedNet.state_dict()\n NeededAddEdges=[]\n for layer_name in state_dict:\n if (\"layers\" in layer_name) and (\"weight\" in layer_name):\n Weight=state_dict[layer_name]\n if Weight.dim()==3:\n Weight=torch.squeeze(Weight)\n DimCompress=True\n else:\n DimCompress=False\n M,N=Weight.shape\n BaseNode=0\n for iter1 in range(len(predLinkWeight)):\n if BaseNode<=predLinkWeight[iter1][0]<=(BaseNode+M) and (BaseNode+M)<=predLinkWeight[iter1][1]<=(BaseNode+M+N):\n Weight[int(predLinkWeight[iter1][0]-BaseNode),int(predLinkWeight[iter1][1]-M-BaseNode)]+=WeightCorrectionCoeffi*predLinkWeight[iter1][2]\n tmp=Weight[int(predLinkWeight[iter1][0]-BaseNode),int(predLinkWeight[iter1][1]-M-BaseNode)]\n print(\"Weight change from {} to {} at connection between node {} to {} weight errors.\".format(round(tmp.item(),4),round(predLinkWeight[iter1][2],4),int(predLinkWeight[iter1][0]-BaseNode),int(predLinkWeight[iter1][1]-M-BaseNode)))\n \n elif ((BaseNode<=predLinkWeight[iter1][0] int community\n graph partitions\n\n\n Returns:\n --------\n pos -- dict mapping int node -> (float x, float y)\n node positions\n\n \"\"\"\n\n pos_communities = _position_communities(g, partition, scale=3.)\n\n pos_nodes = _position_nodes(g, partition, scale=1.)\n\n # combine positions\n pos = dict()\n for node in g.nodes():\n pos[node] = pos_communities[node] + pos_nodes[node]\n\n return pos\n\ndef _position_communities(g, partition, **kwargs):\n\n # create a weighted graph, in which each node corresponds to a community,\n # and each edge weight to the number of edges between communities\n between_community_edges = _find_between_community_edges(g, partition)\n\n communities = set(partition.values())\n hypergraph = nx.DiGraph()\n hypergraph.add_nodes_from(communities)\n for (ci, cj), edges in between_community_edges.items():\n hypergraph.add_edge(ci, cj, weight=len(edges))\n\n # find layout for communities\n pos_communities = nx.spring_layout(hypergraph, **kwargs)\n\n # set node positions to position of community\n pos = dict()\n for node, community in partition.items():\n pos[node] = pos_communities[community]\n\n return pos\n\ndef _find_between_community_edges(g, partition):\n\n edges = dict()\n\n for (ni, nj) in g.edges():\n ci = partition[ni]\n cj = partition[nj]\n\n if ci != cj:\n try:\n edges[(ci, cj)] += [(ni, nj)]\n except KeyError:\n edges[(ci, cj)] = [(ni, nj)]\n\n return edges\n\ndef _position_nodes(g, partition, **kwargs):\n \"\"\"\n Positions nodes within communities.\n \"\"\"\n\n communities = dict()\n for node, community in partition.items():\n try:\n communities[community] += [node]\n except KeyError:\n communities[community] = [node]\n\n pos = dict()\n for ci, nodes in communities.items():\n subgraph = g.subgraph(nodes)\n pos_subgraph = nx.spring_layout(subgraph, **kwargs)\n pos.update(pos_subgraph)\n\n return pos\n\ndef test():\n # to install networkx 2.0 compatible version of python-louvain use:\n # pip install -U git+https://github.com/taynaud/python-louvain.git@networkx2\n from community import community_louvain\n\n g = nx.karate_club_graph()\n partition = community_louvain.best_partition(g)\n pos = community_layout(g, partition)\n\n nx.draw(g, pos, node_color=list(partition.values())); plt.show()\n return\n","sub_path":"SpectralAnalysisFull.py","file_name":"SpectralAnalysisFull.py","file_ext":"py","file_size_in_byte":22568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"113716755","text":"# Five imports\nfrom Products.Five.browser import BrowserView\n\n# CMFPlone imports\nfrom Products.CMFPlone import utils\nfrom Products.CMFPlone.PloneBatch import Batch\n\n# CMFCore imports\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.CMFDefault.utils import decode\n\n# This Module imports\nfrom TT.FischereiverbandNews.config import *\nfrom TT.FischereiverbandNews.utils import *\n\nclass NachrichtenContentView(BrowserView):\n \"\"\"\n \"\"\"\n def getParentLink(self, REQUEST=None):\n return self.context.aq_parent.absolute_url()\n\n def getImages(self,nachrichten):\n objItems = nachrichten.objectItems()\n return [item[1] for item in objItems] \n \n def redirectToParent(self):\n destination = self.getParentLink()\n return self.context.REQUEST.RESPONSE.redirect(destination)\n \n def queryCatalog(self,nachrichten_id, REQUEST=None,review_state=None):\n \"\"\"\n \"\"\"\n if REQUEST is None:\n REQUEST = getattr(self.context, 'REQUEST', {})\n\n q = {'portal_type' : 'NachrichtenItem', \n 'sort_on' : 'effective',\n 'sort_order' : 'reverse'}\n \n if review_state: q['review_state'] = review_state\n # Quering\n pcatalog = getToolByName(self, 'portal_catalog')\n results = pcatalog.searchResults(REQUEST, **q)\n nachricten = ''\n for result in results:\n item = result.getObject()\n item_id = item.getId()\n if item_id == nachrichten_id:\n nachricten = item\n return nachricten\n","sub_path":"src/TT.FischereiverbandNews/TT/FischereiverbandNews/browser/nachrichten_content_view.py","file_name":"nachrichten_content_view.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"201906421","text":"from collections import deque\nfrom collections.abc import Callable\nfrom typing import Optional\nfrom errors import KeyExistsRegistrationException, KeyNotFound\nimport threading\n\nclass PyTaskManager:\n def __init__(self, concurrent_tasks: int = 1):\n self.__threads = dict()\n self.__actions = dict()\n self.__concurrent_tasks = concurrent_tasks\n self.__task_queue = deque([])\n self.__task_queue_cv = threading.Condition()\n\n self.__mount_threads()\n self.__start_threads()\n\n @staticmethod\n def __thread_fn(manager, index: int):\n try:\n manager.__listen()\n except:\n manager.__recreate_thread(index)\n\n def __listen(self):\n while(True):\n self.__task_queue_cv.acquire()\n scheduled = self.dequeue()\n\n if scheduled is None:\n self.__task_queue_cv.wait()\n scheduled = self.dequeue()\n\n if scheduled is not None:\n self.__task_queue_cv.release()\n \n if scheduled[0] in self.__actions:\n self.__actions[scheduled[0]](*scheduled[1])\n else:\n self.__task_queue_cv.release()\n \n if scheduled[0] in self.__actions:\n self.__actions[scheduled[0]](*scheduled[1])\n\n def __recreate_thread(self, index: int):\n if index in self.__threads:\n self.__threads.pop(index)\n \n thread = threading.Thread(target=self.__thread_fn, args=(self,index,))\n self.__threads.setdefault(index, thread)\n self.__threads[index].start()\n\n def __mount_threads(self):\n for index in range(self.__concurrent_tasks):\n thread = threading.Thread(target=self.__thread_fn, args=(self,index,))\n self.__threads.setdefault(index, thread)\n\n def __start_threads(self):\n for index in range(self.__concurrent_tasks):\n if index in self.__threads:\n self.__threads[index].start()\n\n def register(self, key: str, fn: Callable[[...], str]) -> None:\n if key in self.__actions:\n raise KeyExistsRegistrationException(key)\n else:\n self.__actions.setdefault(key, fn)\n\n def enqueue(self, key: str, *args) -> None:\n if key not in self.__actions:\n raise KeyNotFound(key)\n\n with self.__task_queue_cv:\n self.__task_queue.append([key, args])\n self.__task_queue_cv.notify()\n\n def dequeue(self):\n try:\n return self.__task_queue.popleft()\n except:\n return None\n\n\ndef fn(x, y):\n print(x,y)\n raise Exception(\"sssssss\")\n\nmanager = PyTaskManager(3)\nmanager.register(\"test\", fn)\nmanager.enqueue(\"test\", 2,3)\n","sub_path":"task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"379833269","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dataportal3', '0021_usergroup_usergroupsurveycollection'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='usergroupsurveycollection',\n name='survey_visibility_metadata',\n ),\n migrations.AddField(\n model_name='surveyvisibilitymetadata',\n name='user_group_survey_collection',\n field=models.ForeignKey(to='dataportal3.UserGroupSurveyCollection', null=True),\n ),\n ]\n","sub_path":"dataportal3/migrations/0022_auto_20160105_1649.py","file_name":"0022_auto_20160105_1649.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"456582827","text":"# from core.context import running_context\nfrom core.case import database\n\n\nclass GlobalSubscriptions(object):\n \"\"\"\n Specifies the events which are subscribed to by all types of a execution level\n\n Attributes:\n controller (list[str]): Events subscribed to by all controllers\n workflow (list[str]): Events subscribed to by all workflows\n step (list[str]): Events subscribed to by all steps\n next_step (list[str]): Events subscribed to by all next\n flag (list[str]): Events subscribed to by all flags\n filter (list[str]): Events subscribed to by all filters\n \"\"\"\n\n def __init__(self, controller=None, workflow=None, step=None, next_step=None, flag=None, filter=None):\n self.controller = controller if controller is not None else []\n self.workflow = workflow if workflow is not None else []\n self.step = step if step is not None else []\n self.next_step = next_step if next_step is not None else []\n self.flag = flag if flag is not None else []\n self.filter = filter if filter is not None else []\n\n def __iter__(self):\n yield self.controller\n yield self.workflow\n yield self.step\n yield self.next_step\n yield self.flag\n yield self.filter\n\n def as_json(self):\n return {\"controller\": self.controller,\n \"workflow\": self.workflow,\n \"step\": self.step,\n \"next_step\": self.next_step,\n \"flag\": self.flag,\n \"filter\": self.filter}\n\n @staticmethod\n def from_json(json):\n if set(json.keys()) == set(list(['controller', 'workflow', 'step', 'next_step', 'flag', 'filter'])):\n return GlobalSubscriptions(controller=json['controller'],\n workflow=json['workflow'],\n step=json['step'],\n next_step=json['next_step'],\n flag=json['flag'],\n filter=json['filter'])\n\n def __repr__(self):\n return str({'controller': self.controller,\n 'workflow': self.workflow,\n 'step': self.step,\n 'next_step': self.next_step,\n 'flag': self.flag,\n 'filter': self.filter})\n\n\nclass Subscription(object):\n \"\"\"\n Encapsulates the events which are subscribed to for one level of execution. Forms a tree.w\n\n Attributes:\n events (_SubscriptionEventList): A list of events this level is subscribed to\n subscriptions (dict{str: Subscription}): A list of subscriptions to execution events one level lower\n \"\"\"\n\n def __init__(self, events=None, subscriptions=None):\n self.events = events if events is not None else []\n self.subscriptions = subscriptions if subscriptions is not None else {} # in form of {'name' => Subscription()}\n\n def is_subscribed(self, message_name):\n \"\"\"\n Is the given message subscribed to in this level of execution?\n :param message_name: The given message\n :return (bool): Is the message subscribed to?\n \"\"\"\n return message_name in self.events\n\n def as_json(self):\n return {\"events\": self.events,\n \"subscriptions\": {str(name): subscription.as_json()\n for name, subscription in self.subscriptions.items()}}\n\n @staticmethod\n def from_json(json_in):\n events = json_in['events'] if 'events' in json_in else None\n _subscriptions = json_in['subscriptions'] if 'subscriptions' in json_in else None\n if _subscriptions is not None:\n _subscriptions = {sub_name: Subscription.from_json(sub) for sub_name, sub in _subscriptions.items()}\n return Subscription(events=events, subscriptions=_subscriptions)\n\n def __repr__(self):\n return str({'events': self.events,\n 'subscriptions': self.subscriptions})\n\n\nclass CaseSubscriptions(object):\n def __init__(self, subscriptions=None, global_subscriptions=None):\n self.subscriptions = subscriptions if subscriptions is not None else {}\n self.global_subscriptions = global_subscriptions if global_subscriptions is not None else GlobalSubscriptions()\n\n def is_subscribed(self, ancestry, message_name):\n current_subscriptions = self.subscriptions\n ancestry = list(ancestry[::-1])\n ancestry_level_name = ancestry.pop()\n while ancestry_level_name and ancestry_level_name in current_subscriptions:\n if not ancestry:\n return current_subscriptions[ancestry_level_name].is_subscribed(message_name)\n else:\n current_subscriptions = current_subscriptions[ancestry_level_name].subscriptions\n ancestry_level_name = ancestry.pop()\n return False\n\n def as_json(self):\n return {\"subscriptions\": {str(name): subscription.as_json()\n for name, subscription in self.subscriptions.items()},\n \"global_subscriptions\": self.global_subscriptions.as_json()}\n\n @staticmethod\n def from_json(json_in):\n _subscriptions = json_in['subscriptions'] if 'subscriptions' in json_in else None\n if _subscriptions is not None:\n _subscriptions = {subscription_name: Subscription.from_json(subscription)\n for subscription_name, subscription in _subscriptions.items()}\n\n global_subscriptions = json_in['global_subscriptions'] if 'global_subscriptions' in json_in else None\n if global_subscriptions is not None:\n global_subscriptions = GlobalSubscriptions.from_json(global_subscriptions)\n return CaseSubscriptions(subscriptions=_subscriptions, global_subscriptions=global_subscriptions)\n\n def __repr__(self):\n return str({'subscriptions': self.subscriptions,\n 'global_subscriptions': self.global_subscriptions})\n\n\nsubscriptions = {}\n\n\ndef set_subscriptions(new_subscriptions):\n global subscriptions\n subscriptions = new_subscriptions\n database.case_db.register_events(new_subscriptions.keys())\n\n\ndef add_cases(cases):\n valid_cases = []\n for case_name, case in cases.items():\n if case_name not in subscriptions:\n subscriptions[case_name] = case\n valid_cases.append(case_name)\n database.case_db.register_events(valid_cases)\n\n\ndef delete_cases(cases):\n valid_cases = []\n for case_name in cases:\n if case_name in subscriptions:\n del subscriptions[case_name]\n valid_cases.append(case_name)\n database.case_db.delete_cases(valid_cases)\n\n\ndef rename_case(old_case_name, new_case_name):\n if old_case_name in subscriptions:\n subscriptions[new_case_name] = subscriptions.pop(old_case_name)\n database.case_db.rename_case(old_case_name, new_case_name)\n\n\ndef get_subscriptions():\n return subscriptions\n\n\ndef clear_subscriptions():\n global subscriptions\n subscriptions = {}\n\n\ndef is_case_subscribed(case, ancestry, message_name):\n return subscriptions[case].is_subscribed(ancestry, message_name)\n\n\ndef subscriptions_as_json():\n return {str(name): subscription.as_json() for name, subscription in subscriptions.items()}\n\n\ndef edit_global_subscription(case_name, global_subscriptions):\n if case_name in subscriptions:\n subscriptions[case_name].global_subscriptions = global_subscriptions\n return True\n return False\n\n\ndef edit_subscription(case, ancestry, events):\n if case in subscriptions:\n a = list(ancestry[::-1])\n current_subscriptions = subscriptions[case].subscriptions\n ancestry = list(ancestry[::-1])\n if ancestry:\n ancestry_level_name = ancestry.pop()\n if ancestry_level_name not in current_subscriptions:\n subscriptions[case].subscriptions = __construct_subscription_from_ancestry(a, events)\n return True\n else:\n while ancestry_level_name and ancestry_level_name in current_subscriptions:\n if not ancestry:\n current_subscriptions[ancestry_level_name].events = events\n return True\n else:\n current_subscriptions = current_subscriptions[ancestry_level_name].subscriptions\n ancestry_level_name = ancestry.pop()\n return False\n else:\n return False\n\n\ndef __construct_subscription_from_ancestry(ancestry, events):\n ancestry = list(ancestry[::-1])\n name = ancestry.pop()\n sub = {name: Subscription(events=events)}\n while ancestry:\n name = ancestry.pop()\n sub = {name: Subscription(subscriptions=sub)}\n return sub\n\n\ndef add_subscription(case, ancestry, events):\n if case in subscriptions:\n ancestry = list(ancestry[::-1])\n current_subscriptions = subscriptions[case].subscriptions\n if ancestry:\n ancestry_level_name = ancestry.pop()\n while ancestry_level_name:\n if not current_subscriptions:\n ancestry.append(ancestry_level_name)\n current_subscriptions = __construct_subscription_from_ancestry(ancestry, events)\n break\n elif ancestry_level_name not in current_subscriptions:\n ancestry.append(ancestry_level_name)\n current_subscriptions[ancestry_level_name] = __construct_subscription_from_ancestry(ancestry, events)[\n ancestry_level_name]\n break\n else:\n current_subscriptions = current_subscriptions[ancestry_level_name].subscriptions\n ancestry_level_name = ancestry.pop()\n else:\n # You failed to add anything if you get here\n pass\n\n\ndef remove_subscription_node(case, ancestry):\n if case in subscriptions:\n ancestry = list(ancestry[::-1])\n current_subscriptions = subscriptions[case].subscriptions\n ancestry_level_name = ancestry.pop()\n while ancestry_level_name and ancestry_level_name in current_subscriptions:\n if not ancestry:\n del current_subscriptions[ancestry_level_name]\n break\n elif not current_subscriptions:\n break\n else:\n current_subscriptions = current_subscriptions[ancestry_level_name].subscriptions\n ancestry_level_name = ancestry.pop()\n","sub_path":"core/case/subscription.py","file_name":"subscription.py","file_ext":"py","file_size_in_byte":10642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"484640554","text":"## 设置为true会打印一些调试信息\nDEBUG = False\n\nConf = {\n \"CORP_ID\" : \"\",\n \"APP_ID\" : 1000002,\n \"APP_SECRET\" : \"\"\n}\n\nJXY_Conf = {\n \"ACCOUNTS\" : (\n {\n \"user\":\"\",\n \"pwd\":\"\"\n },{\n \"user\":\"\",\n \"pwd\":\"\"\n }\n ),\n \"TIMER\":1200, #1200秒启动一次\n}\n\nWW91_Conf = {\n \"ACCOUNTS\" : (\n {\n \"user\":\"xx\",\n \"pwd\":\"xx\"\n },\n ),\n}\n\nP2PEYE_Conf = {\n \"ACCOUNTS\" : (\n {\n \"user\":\"xx\",\n \"pwd\":\"xx\"\n },\n ),\n}\n\nFlask_Conf = {\n \"sToken\":\"\",\n \"sEncodingAESKey\":\"\",\n \"sCorpID\":\"\",\n \"ServerHost\":\"127.0.0.1\",\n \"ServerPort\":7001,\n \"FarmGameLog\":\"\"\n}\n\nEMAIL_OPTIONS = {\n \"HOST\":\"pop.qq.com\",\n \"PORT\":995,\n \"USER\":\"xxx@qq.com\",\n \"PASS\":\"xxx\"\n}","sub_path":"conf_sample.py","file_name":"conf_sample.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"102485117","text":"from django.db import models\nfrom django.db.models.signals import pre_save\nfrom django.dispatch import receiver\nfrom django.core.exceptions import ValidationError\nimport re\n\nprepend_zeros = lambda reqd, available: ''.join('0' for c in range(\n reqd - available)\n)\n\n\nclass Branch(models.Model):\n code = models.CharField(\"Branch Code\", max_length=3, unique=True)\n name = models.CharField(\"Branch Name\", max_length=50)\n\n def save(self, *args, **kwargs):\n if not self.code.isdigit():\n raise ValidationError(\"Only numbers allowed for branch code\")\n self.name = self.name.upper()\n\n len_code = len(self.code)\n if len_code < 3:\n self.code = '%s%s' % (prepend_zeros(3, len_code), self.code)\n\n super(Branch, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return '%s: %s' % (self.name, self.code,)\n\n class Meta:\n db_table = 'branch'\n app_label = 'adhocmodels'\n ordering = ('name', 'code',)\n verbose_name_plural = \"Branches\"\n\n\nclass Currency(models.Model):\n code = models.CharField(\"Currency Code\", max_length=3, unique=True)\n name = models.CharField(\"Currency Name\", max_length=50)\n\n def save(self, *args, **kwargs):\n if not self.code.isalpha():\n raise ValueError('Only letters allowed for currency code.')\n self.code = self.code.upper()\n self.name = self.name.upper()\n super(Currency, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return self.code\n\n class Meta:\n db_table = 'currency'\n verbose_name_plural = \"Currencies\"\n\n\nclass OverseasBank(models.Model):\n name = models.CharField(\"Bank Name\", max_length=50)\n swift_bic = models.CharField(\"Swift Bic\", max_length=11, unique=True)\n\n def save(self, *args, **kwargs):\n self.name = self.name.upper()\n self.swift_bic = self.swift_bic.upper()\n super(OverseasBank, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return u'%s: %s..' % (self.swift_bic, self.name[:20],)\n\n class Meta:\n db_table = 'overseas_bank'\n ordering = (\"swift_bic\", \"name\",)\n app_label = 'adhocmodels'\n verbose_name_plural = \"Overseas Banks\"\n\n\nclass RelationshipManager(models.Model):\n name = models.CharField(\"Name\", max_length=50)\n rmcode = models.CharField(\"RM Code\", max_length=15, unique=True)\n branch = models.ForeignKey(Branch, related_name='rel_managers')\n\n def save(self, *args, **kwargs):\n self.name = self.name.upper()\n self.rmcode = self.rmcode.upper()\n super(RelationshipManager, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return '%s: %s' % (self.name, self.rmcode)\n\n class Meta:\n db_table = 'rel_manager'\n ordering = ('name', 'rmcode',)\n app_label = 'adhocmodels'\n verbose_name = 'Relationship Manager'\n verbose_name_plural = \"Relationship Managers\"\n\n\nclass AccountNumber(models.Model):\n nuban = models.CharField(\"Nuban\", max_length=10, unique=True)\n old_numb = models.CharField(\n 'Old Acct. Number', max_length=13, null=True, blank=True)\n owner = models.ForeignKey(\n 'Customer', related_name='acct_numbs', verbose_name='Customer Name')\n branch = models.ForeignKey(Branch, related_name='accts')\n acct_id = models.CharField(\n 'Customer ID For Acct.', max_length=10, unique=True,)\n\n def save(self, *args, **kwargs):\n if not self.nuban.isdigit:\n raise ValidationError(\"Account Numbers can only contain numbers\")\n\n REQD_DIGITS_NUBAN = 10\n REQD_DIGITS_OLD_NUMB = 13\n\n len_nuban = len(self.nuban)\n\n if len_nuban < REQD_DIGITS_NUBAN:\n self.nuban = '%s%s' % (\n prepend_zeros(REQD_DIGITS_NUBAN, len_nuban), self.nuban)\n\n if self.old_numb:\n if not self.old_numb.isdigit():\n raise ValidationError(\n \"Account Numbers can only contain numbers\")\n\n len_old_numb = len(self.old_numb)\n\n if len_old_numb < REQD_DIGITS_OLD_NUMB:\n self.old_numb = '%s%s' % (\n prepend_zeros(REQD_DIGITS_OLD_NUMB, len_old_numb),\n self.old_numb,\n )\n\n super(AccountNumber, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return '%s: owner=%s | branch=%s' % (\n self.nuban, self.owner, self.branch\n )\n\n class Meta:\n db_table = 'acct_numb'\n app_label = 'adhocmodels'\n ordering = ('owner', 'nuban',)\n\n\nclass Customer(models.Model):\n name = models.CharField('Name', max_length=200)\n rel_manager = models.ForeignKey(\n RelationshipManager, related_name='clients', null=True, blank=True,\n db_column='rel_manager')\n branch_for_itf = models.ForeignKey(\n Branch, null=True, blank=True, db_column='brn_itf')\n parent = models.ForeignKey(\n \"self\", null=True, blank=True, related_name='subsidiaries',\n db_column='parent')\n\n class Meta:\n db_table = 'customer'\n app_label = 'adhocmodels'\n ordering = ('name',)\n\n def save(self, *args, **kwargs):\n self.name = self.name.upper()\n\n if self.parent and not self.parent.acct_numbers:\n raise ValidationError(\n 'Parent Company must have at least one account number')\n\n super(Customer, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return self.name\n\n @property\n def isparent(self):\n return not self.parent and self.subsidiaries.all()\n\n @property\n def issubsidiary(self):\n return self.parent and not self.isparent\n\n @property\n def acct_numbers(self):\n if self.acct_numbs.all():\n return self.acct_numbs.all()\n\n elif self.issubsidiary:\n return self.parent.acct_numbers\n\n else:\n return self.acct_numbs.all()\n\n def subsidiary_status(self):\n if self.isparent:\n return 'PARENT COY'\n elif self.issubsidiary:\n return 'SUBSIDIARY'\n else:\n return 'NONE'\n subsidiary_status.short_description = 'STATUS'\n\n @property\n def rm(self):\n if self.issubsidiary:\n return self.parent.rel_manager\n else:\n return self.rel_manager\n\n def rman(self):\n \"\"\"for the admin cos admin wouldnt allow methods decorated\n with @ property.\n \"\"\"\n return self.rm\n rman.short_description = 'Relationship Manager'\n\n def brn_name(self):\n return self.acct_numbers[0].branch.name\n\n def brn_code(self):\n return self.acct_numbers[0].branch.code\n\n def acct_id(self):\n return self.acct_numbers[0].acct_id\n\n def acct_numb(self):\n return self.acct_numbers[0].nuban\n\n\nclass NostroAccount(models.Model):\n bank = models.ForeignKey(\n OverseasBank, related_name='my_nostros',\n verbose_name='Overseas Bank Name', db_column='bank')\n ccy = models.ForeignKey(\n Currency, related_name='ccy_nostros',\n verbose_name='Currency', db_column='ccy')\n number = models.CharField('Account Number', max_length=60, unique=True)\n name = models.CharField(\n 'Account Name', max_length=1000, blank=True, null=True)\n\n class Meta:\n db_table = 'nostro_acct'\n unique_together = ('bank', 'ccy', 'number',)\n\n def save(self, *args, **kwargs):\n self.number = self.number.strip()\n if self.name:\n self.name = self.name.strip(' \\n\\r\\t')\n return super(NostroAccount, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return u'%s | %s | %s | %s' % (\n self.bank.swift_bic,\n self.number,\n self.ccy.code,\n self.name or '')\n\n @classmethod\n def get_instance_from_repr(cls, bic, acct, ccy):\n \"\"\"Get an instance from the instance's __unicode__ string.\"\"\"\n return cls.objects.get(bank__swift_bic=bic, number=acct, ccy__code=ccy)\n\n\nclass LedgerAccountType(models.Model):\n code = models.CharField(\"Account Code\", max_length=4, unique=True)\n description = models.CharField(\n \"Accout Type Description\",\n max_length=100)\n\n def save(self, *args, **kwargs):\n CODE_RE = re.compile('[a-zA-Z0-9]{4}')\n if not CODE_RE.match(self.code):\n raise ValidationError(\n 'Wrong format for ledger account code: %s' % self.code)\n\n self.code = self.code.upper()\n self.description = self.description.upper()\n super(LedgerAccountType, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return '%s: %s' % (self.code, self.description,)\n\n class Meta:\n db_table = 'ledger_acct_type'\n app_label = 'adhocmodels'\n ordering = ('code',)\n verbose_name = 'Ledger Account Type'\n verbose_name_plural = 'Ledger Account Types'\n\n\nclass LedgerAccount(models.Model):\n number = models.CharField(\"Account Number\", max_length=60, unique=True)\n acct_type = models.ForeignKey(\n LedgerAccountType, db_column='acct_type',\n related_name='ledger_acct_types', verbose_name='Account Type')\n ccy = models.ForeignKey(Currency, db_column='ccy')\n external_number = models.ForeignKey(\n NostroAccount,\n null=True,\n blank=True,\n verbose_name='External Acct. Number',\n db_column='external_number',\n related_name='ledger_acct')\n is_default_memo = models.BooleanField(\n 'Default For Memo Cash Account?', default=False)\n name = models.CharField('Account Name', max_length=255, null=True, blank=True)\n\n class Meta:\n db_table = 'ledger_acct'\n verbose_name = 'Ledger Account'\n verbose_name_plural = 'Ledger Accounts'\n\n def __unicode__(self):\n return self.number\n\n def currency(self):\n return self.ccy.code\n\n def acct_type_display(self):\n return self.acct_type.code\n acct_type_display.short_description = 'Account Type'\n\n\n@receiver(pre_save, sender=LedgerAccount, dispatch_uid='1403736920.856/-9-45298328huEb')\ndef ledger_acct_pre_save(sender, **kwargs):\n self = kwargs['instance']\n self.number = self.number.upper().strip(' \\t\\n\\r')\n\n if self.acct_type.code == 'CASH' and 'CASH' not in self.number:\n raise ValidationError(\n 'Incorrect Number for a cash security account.')\n\n if self.acct_type.code == 'MCSH' and 'MCSH' not in self.number:\n raise ValidationError(\n 'Incorrect number for a memo cash account.')\n\n if self.acct_type.code == 'OTHN' and 'OTHN' not in self.number:\n raise ValidationError(\n 'Incorrect number for a nostro other account')\n\n if self.external_number and self.external_number.ccy != self.ccy:\n raise ValidationError(\n \"This ledger's currency must be %s\" %\n \"the same as external account's currency\")\n\n ccy_re = re.compile('(%s)' % '|'.join(\n Currency.objects.values_list('code', flat=True)))\n\n ccy_found = ccy_re.search(self.number)\n\n if ccy_found and ccy_found.group(0) != self.ccy.code:\n raise ValidationError(\n \"Wrong currency for this account type\")\n\n if self.is_default_memo and 'MCSH' not in self.number:\n raise ValidationError(\n 'Only memo cash account can be set as a default memo')\n\n\ndef get_default_memos():\n memos = {}\n for memo in LedgerAccount.objects.filter(is_default_memo=True):\n memos[memo.ccy.code] = {\n 'number': memo.number,\n 'name': memo.name,\n 'id': memo.id,\n }\n return memos\n\n\nclass ValidTransactionRef(models.Model):\n valid_ref_start = models.CharField(\n 'First four digits of reference', max_length=16)\n\n def save(self, *args, **kwargs):\n self.valid_ref_start = self.valid_ref_start[:4].upper()\n super(ValidTransactionRef, self).save(*args, **kwargs)\n\n @classmethod\n def is_valid_trxn_ref(cls, inref):\n return any(\n [inref[:4].upper() == ref.valid_ref_start\n for ref in cls.objects.all()])\n\n class Meta:\n db_table = 'valid_refs'\n verbose_name = 'Valid Transaction Reference'\n verbose_name_plural = 'Valid Transaction References'\n app_label = 'adhocmodels'\n","sub_path":"recons/adhocmodels/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":12375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"284604786","text":"import sys\nsys.stdin = open(\"input.txt\", \"r\")\n\n\ndef find(N, H):\n H.insert(-1, 0)\n res = 0\n for i in range(2, N - 2):\n i_max = 255\n nth = -2\n while nth != 3 and H[i] - H[i + nth] >= 0:\n if H[i] - H[i + nth] <= i_max and H[i] - H[i + nth] != 0:\n i_max = H[i] - H[i + nth]\n nth += 1\n if H[i] - H[i + nth] < 0:\n pass\n\n elif i_max != 255:\n res += i_max\n\n print(i, i_max)\n # i_max = 255\n # elif i_max != 255:\n # if H[i] - H[i + nth] < 0:\n # pass\n # elif i_max != 255:\n # res += i_max\n # # i_max = 255\n # # res += i_max\n # # i_max = 255\n\n return res\n\n\nT = 1\nfor tc in range(1, T+1):\n N = int(input())\n H = list(map(int, input().split()))\n\n res = find(N, H)\n print(\"#%d %d\" % (tc, res) )","sub_path":"05_알고리즘/190812/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"233971246","text":"'''\n1. Packed padded sequences: Packed padded sequences allow us to only process the\n non-padded elements of our input sentence with our RNN;\n\n2. Masking: Masking is used to force the model to ignore certain elements we do\n not want it to look at, such as attention over padded elements;\n(1 & 2 are somewhat similar function on controling the padded elements;)\n\n3. Inference: view attention values over the source sequence;\n\n4. calculate the BLEU metric from our translations.\n\nPacked Padded Sequence and Masking are two techniques, they are different:\nPacked padded sequences are used to tell our RNN to skip over padding tokens in our encoder;\nMasking explicitly forces the model to ignore certain values, such as attention over padded elements.\nBoth common in NLP;\n'''\n\nfrom typing import Text\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom torchtext.legacy.datasets import Multi30k\nfrom torchtext.legacy.data import Field, BucketIterator\n\nfrom PPSM_Models import Encoder,Attention,Decoder,Seq2Seq\nfrom PPSM_Models import train, evaluate\nfrom PPSM_Models import translate_sentence, display_attention\nfrom metric import calculate_bleu\n\nimport spacy\nimport numpy as np\n\nimport random\nimport math\nimport time\n\nimport pdb\n\nSEED = 1234\n\nrandom.seed(SEED)\nnp.random.seed(SEED)\ntorch.manual_seed(SEED)\ntorch.cuda.manual_seed(SEED)\ntorch.backends.cudnn.deterministic = True\n\nspacy_de = spacy.load('de_core_news_sm')\nspacy_en = spacy.load('en_core_web_sm')\n\ndef tokenize_de(text):\n \"\"\"\n Tokenizes German text from a string into a list of strings\n \"\"\"\n return [tok.text for tok in spacy_de.tokenizer(text)]\n\ndef tokenize_en(text):\n \"\"\"\n Tokenizes English text from a string into a list of strings\n \"\"\"\n return [tok.text for tok in spacy_en.tokenizer(text)]\n\n# TRICK (torchtext related): When using packed padded sequences, we need to tell\n# PyTorch how long the actual (non-padded) sequences are. Luckily for us,\n# TorchText's Field objects allow us to use the \"include_lengths\" argument, this\n# will cause our \"batch.src\" to be a tuple.\n# The first element of the tuple is the same as before, a batch of numericalized\n# source sentence as a tensor, and the second element is the non-padded lengths\n# of each source sentence within the batch.\nSRC = Field(tokenize = tokenize_de, \n init_token = '', \n eos_token = '', \n lower = True, \n include_lengths = True)\n\nTRG = Field(tokenize = tokenize_en, \n init_token = '', \n eos_token = '', \n lower = True)\n\ntrain_data, valid_data, test_data = Multi30k.splits(exts = ('.de', '.en'), \n fields = (SRC, TRG))\n\nSRC.build_vocab(train_data, min_freq = 2)\nTRG.build_vocab(train_data, min_freq = 2)\n\n# BATCH_SIZE = 128\nBATCH_SIZE = 32\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n# Trick: One quirk about packed padded sequences is that all elements in the\n# batch need to be sorted by their non-padded lengths in descending order, i.e.\n# the first sentence in the batch needs to be the longest. \n#\n# We use two arguments of the iterator to handle this:\n# 'sort_within_batch' which tells the iterator that the contents of the batch need to be sorted;\n# 'sort_key' is a function which tells the iterator how to sort the elements in the batch. Here, we sort by the length of the src sentence.\ntrain_iterator, valid_iterator, test_iterator = BucketIterator.splits(\n (train_data, valid_data, test_data), \n batch_size = BATCH_SIZE,\n sort_within_batch = True,\n sort_key = lambda x : len(x.src),\n device = device)\n\nINPUT_DIM = len(SRC.vocab)\nOUTPUT_DIM = len(TRG.vocab)\nENC_EMB_DIM = 256\nDEC_EMB_DIM = 256\nENC_HID_DIM = 512\nDEC_HID_DIM = 512\nENC_DROPOUT = 0.5\nDEC_DROPOUT = 0.5\nSRC_PAD_IDX = SRC.vocab.stoi[SRC.pad_token]\n\nattn = Attention(ENC_HID_DIM, DEC_HID_DIM)\nenc = Encoder(INPUT_DIM, ENC_EMB_DIM, ENC_HID_DIM, DEC_HID_DIM, ENC_DROPOUT)\ndec = Decoder(OUTPUT_DIM, DEC_EMB_DIM, ENC_HID_DIM, DEC_HID_DIM, DEC_DROPOUT, attn)\n\nmodel = Seq2Seq(enc, dec, SRC_PAD_IDX, device).to(device)\n\ndef init_weights(m):\n for name, param in m.named_parameters():\n if 'weight' in name:\n nn.init.normal_(param.data, mean=0, std=0.01)\n else:\n nn.init.constant_(param.data, 0)\n \nmodel.apply(init_weights)\n\ndef count_parameters(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\nprint(f'The model has {count_parameters(model):,} trainable parameters')\n\noptimizer = optim.Adam(model.parameters())\n\nTRG_PAD_IDX = TRG.vocab.stoi[TRG.pad_token]\n\n# Trick: cross-entropy loss by ignoring the padded token.\ncriterion = nn.CrossEntropyLoss(ignore_index = TRG_PAD_IDX)\n\ndef epoch_time(start_time, end_time):\n elapsed_time = end_time - start_time\n elapsed_mins = int(elapsed_time / 60)\n elapsed_secs = int(elapsed_time - (elapsed_mins * 60))\n return elapsed_mins, elapsed_secs\n\n# N_EPOCHS = 10\nN_EPOCHS = 3\nCLIP = 1\n\nbest_valid_loss = float('inf')\n\nfor epoch in range(N_EPOCHS):\n \n start_time = time.time()\n \n train_loss = train(model, train_iterator, optimizer, criterion, CLIP)\n valid_loss = evaluate(model, valid_iterator, criterion)\n \n end_time = time.time()\n \n epoch_mins, epoch_secs = epoch_time(start_time, end_time)\n \n if valid_loss < best_valid_loss:\n best_valid_loss = valid_loss\n torch.save(model.state_dict(), 'models/tut4-model.pt')\n \n print(f'Epoch: {epoch+1:02} | Time: {epoch_mins}m {epoch_secs}s')\n print(f'\\tTrain Loss: {train_loss:.3f} | Train PPL: {math.exp(train_loss):7.3f}')\n print(f'\\t Val. Loss: {valid_loss:.3f} | Val. PPL: {math.exp(valid_loss):7.3f}')\n\n\nmodel.load_state_dict(torch.load('models/tut4-model.pt'))\ntest_loss = evaluate(model, test_iterator, criterion)\nprint(f'| Test Loss: {test_loss:.3f} | Test PPL: {math.exp(test_loss):7.3f} |')\n\n# Inference and display attention.\ndef infer_disp(example_idx):\n src = vars(train_data.examples[example_idx])['src']\n trg = vars(train_data.examples[example_idx])['trg']\n\n print(f'src = {src}')\n print(f'trg = {trg}')\n\n # inference\n translation, attention = translate_sentence(src, SRC, TRG, model, device)\n print(f'predicted trg = {translation}')\n\n display_attention(src, translation, attention)\n\nexample_idx = 12\ninfer_disp(example_idx)\n\nexample_idx = 14\ninfer_disp(example_idx)\n\nexample_idx = 18\ninfer_disp(example_idx)\n\nbleu_score = calculate_bleu(test_data, SRC, TRG, model, device)\n\nprint(f'BLEU score = {bleu_score*100:.2f}')","sub_path":"four.py","file_name":"four.py","file_ext":"py","file_size_in_byte":6618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"457853849","text":"from django.conf import settings\nfrom django.http import HttpResponse, Http404\nfrom django.template.response import TemplateResponse\nfrom django.views.decorators.cache import never_cache, cache_page, cache_control\nfrom django.views.decorators.csrf import csrf_protect\n\nfrom .models import *\nfrom main.views import set_common_info\nfrom website.common import lang_field\nfrom website.decorators import check_maintenance, check_switch\n\nimport datetime\n\n@check_maintenance\n@check_switch()\n@never_cache\ndef tool(request, template_name='tool/tool.html', extra_context=None):\n context = {\n 'all_in_one': {'tumour_type': [], 'gene': [],}, \n 'tumour_type': [], \n }\n ngb_id_tmp = []\n entries = Panel.objects.values(\n 'tumour_type__ngb_id', lang_field('remark_zh', 'remark_en'), 'gene_list', \n lang_field('tumour_type__name_zh', 'tumour_type__name_en'), 'pk').order_by(\n lang_field('tumour_type__name_zh', 'tumour_type__name_en'))\n for i in entries:\n gene_list = i['gene_list'].strip().split(',')\n gene_list.sort()\n for j in gene_list:\n if j not in context['all_in_one']['gene']:\n context['all_in_one']['gene'].append(j)\n if i['tumour_type__ngb_id'] not in ngb_id_tmp:\n ngb_id_tmp.append(i['tumour_type__ngb_id'])\n context['all_in_one']['tumour_type'].append({\n 'ngb_id': i['tumour_type__ngb_id'],\n 'name': i[lang_field('tumour_type__name_zh', 'tumour_type__name_en')], \n })\n context['tumour_type'].append({\n 'ngb_id': i['tumour_type__ngb_id'], \n 'name': i[lang_field('tumour_type__name_zh', 'tumour_type__name_en')], \n 'gene': gene_list, \n 'remark': i[lang_field('remark_zh', 'remark_en')], \n 'pk': i['pk'], \n })\n context['all_in_one']['gene'].sort()\n common_info = set_common_info('tool', 'Tool')\n context.update(common_info)\n if extra_context:\n context.update(extra_context)\n return TemplateResponse(request, template_name, context)\n\n@cache_control(max_age=1)\n@check_maintenance\n@check_switch()\n@cache_page(31449600)\ndef download_panel(request, pk):\n if pk == '0':\n entries = Panel.objects.all().values_list('gene_list', flat=True)\n gene_list = []\n for i in entries:\n gene_list_tmp = i.strip().split(',')\n for j in gene_list_tmp:\n if j not in gene_list:\n gene_list.append(j)\n else:\n entries = Panel.objects.filter(pk=pk)\n if entries.exists():\n entry = entries[0]\n gene_list = entry.gene_list.strip().split(',')\n else:\n raise Http404('Url argument error 0.')\n gene_list.sort()\n text = '\\n'.join(gene_list)\n response = HttpResponse(text, content_type='application/plain-text')\n response['Content-Disposition'] = ('attachment; filename=\"gene_set_%s.txt\"' \n % datetime.datetime.now().strftime('%Y%m%d%H%M%S'))\n return response","sub_path":"website/tool/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"416346497","text":"import subprocess\nimport sys\nimport os \n\ndef install(package):\n subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package])\n\nif __name__ == '__main__':\n install('dill')\n install('pillow')\n install('PySide2')\n install('numpy')\n install('pyglet')\n install(\"sti-LabJackPython\")\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"371055300","text":"################################################################################\r\n######################### 1. LIBRARIES AND DATA LOADING ########################\r\n################################################################################\r\n\r\n#### 1.1) Import the libraries used ###\r\n\r\nimport numpy as np\r\nimport pandas as pd \r\nimport matplotlib.pyplot as plt\r\n\r\nfrom nltk.corpus import stopwords \r\nfrom nltk.metrics import jaccard_distance\r\nfrom collections import Counter \r\nfrom fuzzywuzzy import fuzz\r\n\r\nfrom sklearn.cross_validation import train_test_split \r\nimport xgboost as xgb \r\n\r\n\r\n#### 1.2) Read the data ###\r\n\r\n# For reading in the spell corrected df_train file\r\n# df_train = pd.read_csv('df_train_corrected.csv', encoding = \"ISO-8859-1\")\r\ndf_train = pd.read_csv('train.csv')\r\ndf_test = pd.read_csv('test.csv')\r\n\r\n################################################################################\r\n############################## 2. DEFINE FUNCTIONS #############################\r\n################################################################################\r\n\r\n### 2.1) Function 1: Shared words (5 features) ###\r\n\r\nstops = set(stopwords.words(\"english\"))\r\n \r\ndef shared_words(row):\r\n \r\n\r\n q1words = {}\r\n q2words = {}\r\n q1 = str(row['question1']).lower().split()\r\n q2 = str(row['question2']).lower().split()\r\n \r\n for word in str(row['question1']).lower().split(): \r\n if word not in stops: \r\n q1words[word] = 1 \r\n\r\n for word in str(row['question2']).lower().split(): \r\n if word not in stops:\r\n q2words[word] = 1\r\n \r\n if len(q1words) == 0 or len(q2words) == 0 :\r\n return '0:0:0:0:0'\r\n \r\n # Common non stop words between question pairs. Both variableS are equivalent \r\n shared_words_q1 = [word for word in q1words.keys() if word in q2words.keys()]\r\n shared_words_q2 = [word for word in q2words.keys() if word in q1words.keys()] \r\n \r\n \r\n \r\n R = (len(shared_words_q1) + len(shared_words_q2))/(len(q1words) + len(q2words))\r\n R1 = len(q1words) / len(q1) # q1 non stop words ratio\r\n R2 = len(q2words) / len(q2)\r\n R3 = R1-R2\r\n R4 = len(shared_words_q1)\r\n \r\n return '{}:{}:{}:{}:{}'.format(R,R1,R2,R3,R4)\r\n \r\n\r\n### 2.2) Function 2: TDIDF (1 feature) ###\r\n\r\ndef get_weight(count, eps=10000, min_count=2):\r\n if count < min_count:\r\n return 0\r\n else:\r\n return 1 / (count + eps)\r\n\r\ntrain_qs = pd.Series(df_train['question1'].tolist() + df_train['question2'].tolist()).astype(str)\r\nwords = (\" \".join(train_qs)).lower().split() \r\ncounts = Counter(words)\r\nweights = {word: get_weight(count) for word, count in counts.items()} \r\n\r\n\r\ndef tfidf_word_match_share(row):\r\n q1words = {}\r\n q2words = {}\r\n for word in str(row['question1']).lower().split():\r\n if word not in stops:\r\n q1words[word] = 1\r\n for word in str(row['question2']).lower().split():\r\n if word not in stops:\r\n q2words[word] = 1\r\n if len(q1words) == 0 or len(q2words) == 0:\r\n return 0\r\n \r\n\r\n shared_weights = [weights.get(word,0) for word in q1words if word in q2words] + [weights.get(word,0) for word in q2words if word in q1words] \r\n total_weights = [weights.get(word,0) for word in q1words] + [weights.get(word,0) for word in q2words]\r\n R = np.sum(shared_weights) / np.sum(total_weights)\r\n return R\r\n\r\n### 2.3) Function 3: Jaccard Distance (1 feature) ###\r\n\r\ndef jaccard_dist(row):\r\n return jaccard_distance(set(str(row['question1'])), set(str(row['question2'])))\r\n \r\n### 2.4) Function 4: Cosine Distance (1 feature) ###\r\n\r\ndef cosine_dist(row):\r\n a = set(str(row['question1']))\r\n b = set(str(row['question2']))\r\n d = len(a)*len(b)\r\n if (d == 0):\r\n return 0\r\n else: \r\n return len(a.intersection(b))/d\r\n \r\n \r\n################################################################################\r\n############################ 3. FEATURES ENGINEERING ###########################\r\n################################################################################\r\n\r\n\r\n# Currently 19 features\r\n # Set 1 (5 features)\r\n # 1.1 = Proportion of shared words\r\n # 1.2 = Ratio of q1's non stopwords\r\n # 1.3 = Ratio of q2's non stopwords\r\n # 1.4 = Ratio difference (1.3 - 1.4)\r\n # 1.5 = Length (number) of shared words\r\n \r\n #Set 2 (1 feature)\r\n # 2.1 = TFIDF \r\n \r\n # Set 3 (6 features)\r\n # 3.1 = Word count in q1\r\n # 3.2 = Word count in q2\r\n # 3.3 = Word count difference \r\n # 3.4 = Character count in q1 (including spaces)\r\n # 3.5 = Character count in q2 (including spaces)\r\n # 3.6 = Character count difference (including spaces)\r\n \r\n # Set 4 (7 features - FuzzyWuzzy)\r\n # 4.1 = QRatio\r\n # 4.2 = WRatio\r\n # 4.3 = Partial ratio\r\n # 4.4 = Partial token set ratio\r\n # 4.5 = Partial token sort ratio\r\n # 4.6 = Token set ratio\r\n # 4.7 = Token sort ratio\r\n \r\n # Set 5 (2 features) (Potential to add more under this set!)\r\n # 5.1 = Jaccard distance\r\n # 5.2 = Cosine distance\r\n\r\n### 3.1) Creation of dataframes for training and testing ###\r\n\r\nx_train = pd.DataFrame() # hold the training set \r\nx_test = pd.DataFrame() # hold the testing set \r\ntemp_df = pd.DataFrame() # to be removed later\r\ntemp_df_test = pd.DataFrame()\r\n\r\n### 3.2) Generating and loading the features ###\r\n \r\n################################## TRAINING SET ################################\r\n\r\n# create temp df for set 1 function \r\ntemp_df['allR'] = df_train.apply(shared_words, axis = 1, raw = True)\r\n\r\n# Set 1\r\nx_train['shared_words'] = temp_df['allR'].apply(lambda x: float(x.split(':')[0]))\r\nx_train['q1_ns_ratio'] = temp_df['allR'].apply(lambda x: float(x.split(':')[1]))\r\nx_train['q2_ns_ratio'] = temp_df['allR'].apply(lambda x: float(x.split(':')[2]))\r\nx_train['ratio_diff'] = temp_df['allR'].apply(lambda x: float(x.split(':')[3]))\r\nx_train['shared_words_length'] = temp_df['allR'].apply(lambda x: float(x.split(':')[4]))\r\n\r\n# Set 2\r\nx_train['tfidf'] = df_train.apply(tfidf_word_match_share, axis = 1, raw = True)\r\n\r\n# Set 3\r\nx_train['q1_word_count'] = df_train['question1'].apply(lambda x: len(str(x).lower().split()))\r\nx_train['q2_word_count'] = df_train['question2'].apply(lambda x: len(str(x).lower().split()))\r\nx_train['diff_word_count'] = x_train['q1_word_count'] - x_train['q2_word_count']\r\n\r\nx_train['q1_char_count_withspace'] = df_train['question1'].apply(lambda x: len(str(x)))\r\nx_train['q2_char_count_withspace'] = df_train['question2'].apply(lambda x: len(str(x)))\r\nx_train['diff_char_count_withspace'] = x_train['q1_char_count_withspace'] - x_train['q2_char_count_withspace']\r\n\r\n# Set 4\r\nx_train['fuzz_qratio'] = df_train.apply(lambda x: fuzz.QRatio(str(x['question1']), str(x['question2'])), axis=1)\r\nx_train['fuzz_WRatio'] = df_train.apply(lambda x: fuzz.WRatio(str(x['question1']), str(x['question2'])), axis=1)\r\nx_train['fuzz_partial_ratio'] = df_train.apply(lambda x: fuzz.partial_ratio(str(x['question1']), str(x['question2'])), axis=1)\r\nx_train['fuzz_partial_token_set_ratio'] = df_train.apply(lambda x: fuzz.partial_token_set_ratio(str(x['question1']), str(x['question2'])), axis=1)\r\nx_train['fuzz_partial_token_sort_ratio'] = df_train.apply(lambda x: fuzz.partial_token_sort_ratio(str(x['question1']), str(x['question2'])), axis=1)\r\nx_train['fuzz_token_set_ratio'] = df_train.apply(lambda x: fuzz.token_set_ratio(str(x['question1']), str(x['question2'])), axis=1)\r\nx_train['fuzz_token_sort_ratio'] = df_train.apply(lambda x: fuzz.token_sort_ratio(str(x['question1']), str(x['question2'])), axis=1)\r\n\r\n# Set 5\r\nx_train['jaccard_dist'] = df_train.apply(jaccard_dist, axis = 1)\r\nx_train['cosine_dist'] = df_train.apply(cosine_dist, axis = 1)\r\n\r\ndel temp_df\r\n\r\n################################################################################\r\n################################################################################\r\n\r\n################################## TESTING SET ################################\r\n\r\n# create temp df for set 1 function\r\ntemp_df_test['allR'] = df_test.apply(shared_words, axis = 1, raw = True)\r\n\r\n# Set 1 \r\nx_test['shared_words'] = temp_df_test['allR'].apply(lambda x: float(x.split(':')[0]))\r\nx_test['q1_ns_ratio'] = temp_df_test['allR'].apply(lambda x: float(x.split(':')[1]))\r\nx_test['q2_ns_ratio'] = temp_df_test['allR'].apply(lambda x: float(x.split(':')[2]))\r\nx_test['ratio_diff'] = temp_df_test['allR'].apply(lambda x: float(x.split(':')[3]))\r\nx_test['shared_words_length'] = temp_df_test['allR'].apply(lambda x: float(x.split(':')[4]))\r\n\r\n# Set 2\r\nx_test['tfidf'] = df_test.apply(tfidf_word_match_share, axis = 1, raw = True)\r\n\r\n# Set 3\r\nx_test['q1_word_count'] = df_test['question1'].apply(lambda x: len(str(x).lower().split()))\r\nx_test['q2_word_count'] = df_test['question2'].apply(lambda x: len(str(x).lower().split()))\r\nx_test['diff_word_count'] = x_test['q1_word_count'] - x_test['q2_word_count']\r\n\r\nx_test['q1_char_count_withspace'] = df_test['question1'].apply(lambda x: len(str(x)))\r\nx_test['q2_char_count_withspace'] = df_test['question2'].apply(lambda x: len(str(x)))\r\nx_test['diff_char_count_withspace'] = x_test['q1_char_count_withspace'] - x_test['q2_char_count_withspace']\r\n\r\n# Set 4\r\nx_test['fuzz_qratio'] = df_test.apply(lambda x: fuzz.QRatio(str(x['question1']), str(x['question2'])), axis=1)\r\nx_test['fuzz_WRatio'] = df_test.apply(lambda x: fuzz.WRatio(str(x['question1']), str(x['question2'])), axis=1)\r\nx_test['fuzz_partial_ratio'] = df_test.apply(lambda x: fuzz.partial_ratio(str(x['question1']), str(x['question2'])), axis=1)\r\nx_test['fuzz_partial_token_set_ratio'] = df_test.apply(lambda x: fuzz.partial_token_set_ratio(str(x['question1']), str(x['question2'])), axis=1)\r\nx_test['fuzz_partial_token_sort_ratio'] = df_test.apply(lambda x: fuzz.partial_token_sort_ratio(str(x['question1']), str(x['question2'])), axis=1)\r\nx_test['fuzz_token_set_ratio'] = df_test.apply(lambda x: fuzz.token_set_ratio(str(x['question1']), str(x['question2'])), axis=1)\r\nx_test['fuzz_token_sort_ratio'] = df_test.apply(lambda x: fuzz.token_sort_ratio(str(x['question1']), str(x['question2'])), axis=1)\r\n\r\n# Set 5\r\nx_test['jaccard_dist'] = df_test.apply(jaccard_dist, axis = 1)\r\nx_test['cosine_dist'] = df_test.apply(cosine_dist, axis = 1)\r\n\r\n\r\n# remove temp \r\ndel temp_df_test \r\n\r\n################################################################################\r\n################################ 4. TRAINING SAMPLES ###########################\r\n################################################################################\r\n\r\n\r\ny_train = df_train['is_duplicate']\r\n\r\npos_train = x_train[y_train == 1]\r\nneg_train = x_train[y_train == 0]\r\n\r\n# now we over sample the negative class (need more reference on this methodology)\r\np = 0.165\r\nscale = ((len(pos_train) / (len(pos_train) + len(neg_train))) / p) - 1\r\nwhile scale > 1:\r\n neg_train = pd.concat([neg_train, neg_train])\r\n scale -=1\r\nneg_train = pd.concat([neg_train, neg_train[:int(scale * len(neg_train))]])\r\nprint(len(pos_train) / (len(pos_train) + len(neg_train)))\r\n\r\n# rebild the x_train and y_train \r\nx_train = pd.concat([pos_train, neg_train])\r\ny_train = (np.zeros(len(pos_train)) + 1).tolist() + np.zeros(len(neg_train)).tolist()\r\ndel pos_train, neg_train\r\n\r\nrandom = 12357\r\nnp.random.seed(random)\r\nx_train, x_valid, y_train, y_valid = train_test_split(x_train, y_train, test_size = 0.2, random_state = random)\r\n\r\n\r\n################################################################################\r\n################################# 5. XGBOOST MODEL #############################\r\n################################################################################\r\n\r\n### 5.1) Setting the model parameters ###\r\nparams = {} # dict \r\nparams['eta'] = 0.15\r\nparams['max_depth'] = 5 \r\nparams['objective'] = 'binary:logistic'\r\nparams['eval_metric'] = 'logloss'\r\nparams['seed'] = 123\r\n\r\n\r\n### 5.2) Concatenates the information into DMatrix for training ###\r\nxg_train = xgb.DMatrix(x_train, label = y_train) # train set input into xgb\r\nxg_valid = xgb.DMatrix(x_valid, label = y_valid) # valid (test) set input. \r\n\r\nwatchlist = [(xg_train, 'train'), (xg_valid, 'valid')]\r\n\r\n\r\n### 5.3) Runs the model ###\r\n# start modelling and training on the train and valid df (split from x_train and y_train)\r\n# \r\n# [500] train-logloss: 0.339 valid-logloss:0.34481 (6 features)\r\n# [500] train-logloss:0.330407 valid-logloss:0.338668 (12 features)\r\n# [499] train-logloss:0.316258 valid-logloss:0.32599 (12 + 7 fuzzywuzzy features)\r\n# [499] train-logloss:0.309309 valid-logloss:0.322939 (eta increased to 0.15)\r\nbst = xgb.train(params, xg_train, 500, watchlist)\r\n\r\n\r\n### 5.4) Test the model ###\r\n# time to input our test dataset into our model \r\nxg_test = xgb.DMatrix(x_test)\r\noutput_result = bst.predict(xg_test)\r\n\r\n### 5.5) Write out submission into csv file ###\r\n# Woof woof\r\nnextsub = pd.DataFrame({'test_id':df_test['test_id'],'is_duplicate':output_result})\r\nnextsub.to_csv('nextsub_descriptionhere.csv',index = False)\r\n\r\n\r\n################################################################################\r\n################################ 6. FEATURES CHART #############################\r\n################################################################################\r\n\r\n\r\nvariables_important = bst.get_fscore() # dict\r\nscore_df = pd.DataFrame()\r\nscore_df['variables'] = variables_important.keys()\r\nscore_df['f_score'] = variables_important.values()\r\nscore_df.plot(kind= 'barh', x='variables',y='f_score', legend = False)\r\n\r\n## Alternatively, run this for better visualization\r\n\r\nplt.rcParams['figure.figsize'] = (7.0, 7.0)\r\nxgb.plot_importance(bst); plt.show()","sub_path":"code-analysis/xgboost1.py","file_name":"xgboost1.py","file_ext":"py","file_size_in_byte":13632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"591190536","text":"from django.contrib.auth.mixins import (LoginRequiredMixin,\n PermissionRequiredMixin)\nfrom django.contrib.auth.models import User\nfrom django.db.models import Q\nfrom django.shortcuts import render, redirect\nfrom django.views import View\nfrom django.views.generic.edit import CreateView\n\nfrom .models import Tweet, Message\nfrom .forms import MessageForm, TweetForm\n\n\nclass MainView(LoginRequiredMixin, View):\n\n def get(self, request):\n form = TweetForm()\n tweets = Tweet.objects.order_by('-creation_date')\n users = User.objects.all()\n return render(request, 'main.html', {'tweets': tweets,\n 'users': users,\n 'form': form})\n\n def post(self, request):\n form = TweetForm(request.POST)\n if form.is_valid():\n content = form.cleaned_data['content']\n current_user = request.user\n Tweet.objects.create(content=content, author=current_user)\n return redirect('main')\n\n\nclass UserView(LoginRequiredMixin, View):\n\n def get(self, request, user_id):\n user = User.objects.get(pk=int(user_id))\n user_tweets = Tweet.objects.filter(author=user)\n return render(request, 'user_front.html', {'user': user,\n 'tweets': user_tweets})\n\n\nclass TweetView(LoginRequiredMixin, View):\n\n def get(self, request, tweet_id):\n tweet = Tweet.objects.get(pk=int(tweet_id))\n user = User.objects.get(pk=tweet.author_id)\n return render(request, 'tweet_view.html', {'user': user,\n 'tweet': tweet})\n\n\nclass MessagesView(LoginRequiredMixin, View):\n\n def get(self, request, user_id, tweet_id):\n user = User.objects.get(pk=int(user_id))\n messages = Message.objects.filter(Q(author=user) | Q(recipient=user))\n return render(request, 'tweet_view.html', {'user': user,\n 'messages': messages})\n\n\nclass CreateUserView(CreateView):\n model = User\n fields = ['username', 'password', 'first_name', 'last_name', 'email']\n\n\n\n","sub_path":"twitter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"513485061","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^list/(?P[0-9]+)$', views.trip, name='trip'),\n url(r'^settle/(?P[0-9]+)$', views.settle, name='settle'),\n url(r'^add_person_to_list/(?P[0-9]+)$', views.add_person_to_list, name='add_person'),\n url(r'^delete_person/(?P[0-9]+)$', views.delete_person, name='delete_person'),\n url(r'^add_transaction/(?P[0-9]+)$', views.add_transaction, name='add_transaction'),\n url(r'^add_payment$', views.add_payment, name='add_payment'),\n url(r'^delete_transaction/(?P[0-9]+)$', views.delete_transaction, name='delete_transaction'),\n url(r'^add_list$', views.add_list, name='add_list'),\n]\n","sub_path":"owings/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"319659891","text":"import re\nfrom templite import Templite, TempliteSyntaxError\nimport unittest\n\nclass AnyOldObject(object):\n def __init__(self, **attrs):\n for n, v in attrs.items():\n setattr(self, n, v)\n\nclass TempliteTest(unittest.TestCase):\n def test_passthrough(self):\n # Strings without variables are passed through unchanged.\n templite_one = Templite('Hello, 20% fun time!')\n print(templite_one.code_builder)\n self.assertEqual(Templite(\"Hello\").render(), \"Hello\")\n self.assertEqual(\n Templite(\"Hello, 20% fun time!\").render(),\n \"Hello, 20% fun time!\"\n )\n\n def test_variables(self):\n test_templite = Templite(\"Hello, {{name}}!\", {'name': 'Ned'})\n print(test_templite.code_builder)\n self.assertEqual(test_templite.render(), \"Hello, Ned!\")\n\n def test_undefined_variables(self):\n # Using undefined names is an error.\n with self.assertRaises(Exception):\n test_templite = Templite(\"Hi, {{name}}!\")\n print(test_templite.code_builder)\n test_templite.render(context=None)\n\n def test_pipes(self):\n data = {\n 'name': 'Ned',\n 'upper': lambda x: x.upper(),\n 'second': lambda x: x[1],\n }\n templite_one = Templite(\"Hello, {{name|upper}}!\", data)\n self.assertEqual(templite_one.render(), \"Hello, NED!\")\n templite_two = Templite(\"Hello, {{name|upper|second}}!\", data)\n print(templite_two.code_builder)\n self.assertEqual(templite_two.render(), \"Hello, E!\")\n\n def test_reusability(self):\n # A single Templite can be used more than once with different data.\n globs = {\n 'upper': lambda x: x.upper(),\n 'punct': '!',\n }\n template = Templite(\"This is {{name|upper}}{{punct}}\", globs)\n print(template.code_builder)\n render_one = template.render({'name': 'Ned'})\n self.assertEqual(render_one, \"This is NED!\")\n self.assertEqual(template.render({'name': 'Ben'}), \"This is BEN!\")\n\n def test_attribute(self):\n # Variables' attributes can be accessed with dots.\n obj = AnyOldObject(a=\"Ay\")\n template_1 = Templite(\"{{obj.a}}\")\n print(template_1.code_builder)\n self.assertEqual(template_1.render({'obj': obj}), \"Ay\")\n\n obj2 = AnyOldObject(obj=obj, b=\"Bee\")\n template_2 = Templite(\"{{obj2.obj.a}} {{obj2.b}}\")\n print(template_2.code_builder)\n self.assertEqual(template_2.render({'obj': obj, 'obj2': obj2}), \"Ay Bee\")\n\n def test_member_function(self):\n # Variables' member functions can be used, as long as they are nullary.\n class WithMemberFns(AnyOldObject):\n def ditto(self):\n return self.txt + self.txt\n\n obj = WithMemberFns(txt=\"Once\")\n template = Templite(\"{{obj.ditto}}\")\n print(template.code_builder)\n self.assertEqual(template.render({'obj': obj}), \"OnceOnce\")\n\n def test_item_access(self):\n d = {'a': 17, 'b': 23}\n template = Templite(\"{{d.a}} < {{d.b}}\")\n print(template.code_builder)\n self.assertEqual(template.render({'d': d}), \"17 < 23\")\n\n def test_loops(self):\n nums = [1, 2, 3, 4]\n template = Templite(\"Look: {% for n in nums %}{{n}}, {% endfor %}done.\")\n print(template.code_builder)\n self.assertEqual(template.render({'nums': nums}), \"Look: 1, 2, 3, 4, done.\")\n def test_filtered_loop(self):\n # Loop iterables can be filtered.\n nums = [1, 2, 3, 4]\n def rev(l):\n \"\"\"Return the reverse of `l`.\"\"\"\n l = l[:]\n l.reverse()\n return l\n template_two = Templite(\n \"Look: {% for n in nums|rev %}{{n}}, {% endfor %}done.\",\n {'rev': rev})\n print(template_two.code_builder)\n self.assertEqual(template_two.render({'nums': nums}), \"Look: 4, 3, 2, 1, done.\")\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"template_engine/test_templite.py","file_name":"test_templite.py","file_ext":"py","file_size_in_byte":4004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"563313082","text":"# encoding: utf-8\n\nimport logging\n\nfrom ckanext.jsonpatch.model.jsonpatch import *\n\nlog = logging.getLogger(__name__)\n\n\ndef init_tables():\n tables = (\n jsonpatch_table,\n jsonpatch_revision_table,\n )\n for table in tables:\n if not table.exists():\n log.debug(\"Creating table %s\", table.name)\n table.create()\n else:\n log.debug(\"Table %s already exists\", table.name)\n","sub_path":"ckanext/jsonpatch/model/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"281817143","text":"from flask import Flask, render_template, request, redirect\r\nimport datetime\r\nimport os\r\n\r\nappl = Flask(\"Note Creation Center\")\r\nnotes=[]\r\n\r\n@appl.route(\"/\")\r\ndef home():\r\n return render_template(\"main.html\", notes = notes, dir = dir)\r\n \r\n@appl.route(\"/submit\", method =[\"POST\"])\r\ndef submit():\r\n time = datetime.datetime.now()\r\n print(time)\r\n ntname = request.form[\"name\"]\r\n print(ntname)\r\n notes.append({\"name\":ntname, \"date\":time})\r\n \r\n ntname +=\".html\"\r\n dir = ntname\r\n print(dir)\r\n \r\n ## Creating a file for the note ##\r\n file = open(ntname, \"w\")\r\n file.write(request.formp[\"data\"])\r\n file.close()\r\n return redirect(\"/\")\r\n\r\n@appl.route(\"/note/\", methods =[\"GET\",\"POST\"])\r\ndef view(name):\r\n ## opening the file created to be read and viewed by the user ##\r\n file = open(name, \"r\")\r\n print(file.read())\r\n return redirect(\"/\", name = name)\r\n \r\nif __name__ == \"__main__\":\r\n appl.run(host = \"0.0.0.0\", port = 5001)\r\n \r\n \r\n","sub_path":"appl.py","file_name":"appl.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"354386755","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport pygame\nimport sys\nimport datetime\nimport time\n\n\nclass TextPicture(pygame.sprite.Sprite):\n\n def __init__(self, speed, location):\n pygame.sprite.Sprite.__init__(self)\n now = datetime.datetime.now()\n text = now.strftime(\"%H:%M:%S\")\n font = pygame.font.Font(None, 40)\n time_text = font.render(text, 1, [0, 0, 0]) # show now time\n self.image = time_text\n self.speed = speed\n self.rect = self.image.get_rect()\n self.rect.left, self.rect.top = location\n\n def move(self):\n self.rect = self.rect.move(self.speed)\n if self.rect.left < 0 or self.rect.left > screen.get_width() - self.image.get_width():\n self.speed[0] = -self.speed[0]\n if self.rect.top < 0 or self.rect.top > screen.get_height() - self.image.get_height():\n self.speed[1] = -self.speed[1]\n\n\npygame.init()\nscreen = pygame.display.set_mode([640, 480])\nmy_time_picture = TextPicture([1, 1], [50, 50])\n\n\nwhile 1:\n screen.fill([255, 255, 255])\n my_time_picture.move()\n screen.blit(my_time_picture.image, my_time_picture.rect)\n pygame.display.flip()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"631715015","text":"#! /usr/bin/python\nimport wx\nimport gettext\nfrom mainframe.menu_utama import* \nimport mainframe\n \n\nclass MyApp(wx.App):\n def OnInit(self):\n self.frame = FUtama(None)\n self.SetTopWindow(self.frame)\n self.frame.Show()\n return True\n\nif __name__ == \"__main__\":\n gettext.install(\"app\") # replace with the appropriate catalog name\n\n app = MyApp(0)\n app.MainLoop()\n","sub_path":"GUIExamps/MyGUI/mainframe/bukamuka.py","file_name":"bukamuka.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"247380853","text":"from telethon import utils\nfrom telethon.tl.types import (\n MessageMediaGame, Game, PhotoEmpty\n)\n\n\ndef test_game_input_media_memory_error():\n large_long = 2**62\n media = MessageMediaGame(Game(\n id=large_long, # <- key to trigger `MemoryError`\n access_hash=large_long,\n short_name='short_name',\n title='title',\n description='description',\n photo=PhotoEmpty(large_long),\n ))\n input_media = utils.get_input_media(media)\n bytes(input_media) # <- shouldn't raise `MemoryError`\n","sub_path":"tests/telethon/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"565096272","text":"# -*- coding: utf-8 -*-\nimport sys\nimport socket\nimport aiml\nimport logging\nimport os\nimport Log\nfrom Log import Logger\nfrom Speak import OutputVoice, MyTTS\n\nlog = Logger('./log/mand.log', level='debug')\n\n# 判断是否形成大脑文件--指令\nmybotMand = aiml.Kernel()\n# 自定义对话指令库\nif os.path.isfile(\"./AIML/base.brn\"):\n mybotMand.bootstrap(brainFile=\"./AIML/base.brn\")\nelse:\n mybotMand.bootstrap(learnFiles=\"./AIML/base.xml\", commands=\"load aiml b\")\n mybotMand.saveBrain(\"./AIML/base.brn\")\n\n# 信息配置\nhost = ''\njling_port = 9987\nagora_port = 9988\ncommand_port = 9989\nrun = '192.168.43.237'\nrun_port = 9990\nbufSize = 1024\n\njlingHost = (host, jling_port)\nagoraHost = (host, agora_port)\ncommandHost = (host, command_port)\nrunHost = (run, run_port)\n\n\n# 数据的写入\ndef writeTxT(path, msg):\n # 单引号转为双引号\n msg = msg.replace(\"\\'\", '\\\"')\n file = open(\"%s.txt\" % path, \"w\")\n file.write(msg)\n\n\n# 数据的读取\ndef readTxT(path):\n file = open(\"%s.txt\" % path, \"r\")\n msg = file.read()\n return msg\n\n\n# 打开视频监控\ndef openMonitor():\n os.system(\"\")\n\n\ndef JLing_command():\n client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n client.bind(commandHost)\n while True:\n data, addr = client.recvfrom(bufSize)\n message = str(data, encoding='utf-8')\n log.logger.info(\"MSG:\" + str(message) + \"Addr:\" + str(addr))\n # 播放指令\n if message.find('01') >= 0:\n msg = \"小精灵已经把话说完了\"\n MyTTS(message[4:])\n OutputVoice()\n client.sendto(msg.encode(encoding=\"utf-8\"), agoraHost)\n log.logger.info(\"Mand send to agora :\" + msg)\n # 打开视频监控\n if message.find('02') >= 0:\n msg = \"已经打开了JLing的视频监控\"\n os.system(\"./OpenVideoCall/run.sh\")\n client.sendto(msg.encode(encoding=\"utf-8\"), agoraHost)\n log.logger.info(\"Mand send to agora :\" + msg)\n # 消息的反馈\n if message.find('03') >= 0:\n msg = readTxT(\"JLing_date\")\n client.sendto(msg.encode(encoding=\"utf-8\"), agoraHost)\n log.logger.info(\"Mand send to agora :\" + msg)\n # 消息的更改\n if message.find('04') >= 0:\n msg = readTxT(\"JLing_date\")\n dict = eval(msg)\n try:\n dict[message[4:6]] = message[7:]\n writeTxT(\"JLing_date\", str(dict))\n msg = \"数据输入成功\"\n client.sendto(msg.encode(encoding=\"utf-8\"), agoraHost)\n log.logger.info(\"Mand send to agora :\" + msg)\n except:\n msg = \"数据输入失败,请按以下格式输入:0004D1:关闭\"\n client.sendto(msg.encode(encoding=\"utf-8\"), agoraHost)\n log.logger.info(\"Mand send to agora :\" + msg)\n # 消息的反馈\n msg = readTxT(\"JLing_date\")\n client.sendto(msg.encode(encoding=\"utf-8\"), agoraHost)\n log.logger.info(\"Mand send to agora :\" + msg)\n if message.find('05') >= 0:\n msg = message[4:]\n log.logger.info(\"Mand send to RUN :\" + msg)\n client.sendto(msg.encode(encoding=\"utf-8\"), runHost)\n\n\nJLing_command()\n","sub_path":"ChallengeProject/JLing/JLingRobot/Mand.py","file_name":"Mand.py","file_ext":"py","file_size_in_byte":3287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"447811451","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponse\nfrom blog.models import Post, Category, Tag\nimport markdown\nfrom comments.forms import CommentForm\n# 导入ListView为了将视图函数修改为类视图\nfrom django.views.generic import ListView, DetailView\nfrom django.utils.text import slugify\nfrom markdown.extensions.toc import TocExtension\nfrom django.db.models import Q\n\n'''\n# 博客首页索引页面视图\ndef index(request):\n #return render(request, 'blog/index.html', context = {'title': '我的博客首页', 'welcome': '欢迎访问我的博客首页'})\n post_list = Post.objects.all()\n #post_list = Post.objects.all().order_by('-created_time')\n return render(request, 'blog/index.html', context = {'post_list': post_list})\n'''\nclass IndexView(ListView):\n model = Post\n template_name = 'blog/index.html'\n context_object_name = 'post_list'\n # 指定 paginate_by 属性后开启分页功能,其值代表每一页包含多少篇文章\n paginate_by = 4\n\n def get_context_data(self, **kwargs):\n \"\"\"\n 在视图函数中将模板变量传递给模板是通过给 render 函数的 context 参数传递一个字典实现的,\n 例如 render(request, 'blog/index.html', context={'post_list': post_list}),\n 这里传递了一个 {'post_list': post_list} 字典给模板。\n 在类视图中,这个需要传递的模板变量字典是通过 get_context_data 获得的,\n 所以我们复写该方法,以便我们能够自己再插入一些我们自定义的模板变量进去。\n \"\"\"\n\n # 首先获得父类生成的传递给模板的字典。\n context = super().get_context_data(**kwargs)\n # 父类生成的字典中已有 paginator and page_obj and is_paginated 这三个模板变量,\n # paginator 是 Paginator 的一个实例,\n # page_obj 是 Page 的一个实例,\n # is_paginated 是一个布尔变量,用于指示是否已分页。\n # 例如如果规定每页10个数据, 而本身只有5个数据,其实就用不着分页, 此时is_paginated=False.\n # 关于什么是Paginator, Page类在 Django Pagination 简单分页:http://zmrenwu.com/post/34/ 中已有详细说明\n # 由于 context 是一个字典,所以调用 get 方法从中取出某个键对应的值。\n paginator = context.get('paginator')\n page = context.get('page_obj')\n is_paginated = context.get('is_paginated')\n\n # 调用自己写的方法获得显示分页导航条需要的数据, 见下方.\n pagination_data = self.pagination_data(paginator, page, is_paginated)\n\n # 将分页导航条的模板变量更新到context中, 注意pagination_data方法返回的也是一个字典.\n context.update(pagination_data)\n\n # 将更新后的context返回, 以便ListView使用这个字典中的模板变量去渲染模板\n # 注意此时context字典中已有了显示分页导航条所需的数据.\n return context\n\n def pagination_data(self, paginator, page, is_paginated):\n # 如果没有分页, 则无需显示分页导航条, 不用任何分页导航条的数据, 因此返回一个空的字典\n if not is_paginated:\n return {}\n\n # 当前页左边连续的页码号,初始值为空\n left = []\n\n # 当前页右边连续的页码号,初始值为空\n right = []\n\n # 标示第1页页码后是否需要显示省略号\n left_has_more = False\n\n # 标示最后一页页码前是否需要显示省略号\n right_has_more = False\n\n # 标示是否需要显示第1页的页码号.\n # 因为如果当前页左边的连续页码号中已经含有第1页的页码号, 此时就无需再显示第1页的页码号\n # 其它情况下第一页的页码是始终需要显示的\n # 初始值为 False\n first = False\n\n # 标示是否需要显示最后一页的页码号.\n # 需要此指示变量的理由和上面相同.\n last = False\n\n # 获得用户当前请求的页码号\n page_number = page.number\n\n # 获得分页后的总页数\n total_pages = paginator.num_pages\n\n # 获得整个分页页码列表, 比如分了四页, 那么就是 [1, 2, 3, 4]\n page_range = paginator.page_range\n\n if page_number == 1:\n # 如果用户请求的是第一页的数据, 那么当前页左边的不需要数据, 因此 left=[](已默认为空).\n # 此时只要获取当前页右边的连续页码号,\n # 比如分页页码列表是 [1, 2, 3, 4], 那么获取的就是 right = [2, 3].\n # 注意这里只获取了当前页码后连续两个页码, 你可以更改这个数字以获取更多页码.\n right = page_range[page_number:page_number + 2]\n\n # 如果最右边的页码号比最后一页的页码号减去 1 还要小,\n # 说明最右边的页码号和最后一页的页码号之间还有其它页码,因此需要显示省略号,通过 right_has_more 来指示。\n if right[-1] < total_pages - 1:\n right_has_more = True\n\n # 如果最右边的页码号比最后一页的页码号小,说明当前页右边的连续页码号中不包含最后一页的页码\n # ��以需要显示最后一页的页码号,通过 last 来指示\n if right[-1] < total_pages:\n last = True\n elif page_number == total_pages:\n # 如果用户请求的是最后一页的数据,那么当前页右边就不需要数据,因此 right=[](已默认为空),\n # 此时只要获取当前页左边的连续页码号。\n # 比如分页页码列表是 [1, 2, 3, 4],那么获取的就是 left = [2, 3]\n # 这里只获取了当前页码后连续两个页码,你可以更改这个数字以获取更多页码。\n left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1]\n\n # 如果最左边的页码号比第 2 页页码号还大,\n # 说明最左边的页码号和第 1 页的页码号之间还有其它页码,因此需要显示省略号,通过 left_has_more 来指示。\n if left[0] > 2:\n left_has_more = True\n\n # 如果最左边的页码号比第 1 页的页码号大,说明当前页左边的连续页码号中不包含第一页的页码,\n # 所以需要显示第一页的页码号,通过 first 来指示\n if left[0] > 1:\n first = True\n\n else:\n # 用户请求的既不是最后一页,也不是第 1 页,则需要获取当前页左右两边的连续页码号,\n # 这里只获取了当前页码前后连续两个页码,你可以更改这个数字以获取更多页码。\n left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1]\n right = page_range[page_number:page_number + 2]\n\n # 是否需要显示最后一页和最后一页前的省略号\n if right[-1] < total_pages - 1:\n right_has_more = True\n if right[-1] < total_pages:\n last = True\n\n # 是否需要显示第 1 页和第 1 页后的省略号\n if left[0] > 2:\n left_has_more = True\n if left[0] > 1:\n first = True\n\n data = {\n 'left': left,\n 'right': right,\n 'left_has_more': left_has_more,\n 'right_has_more': right_has_more,\n 'first': first,\n 'last': last,\n }\n return data\n'''\n# 博客文章详情页\ndef detail(request, pk):\n post = get_object_or_404(Post, pk=pk)\n \n # 访问量+1\n post.increase_views()\n\n # 将markdown格式文章内容转换为html格式\n post.body = markdown.markdown(post.body, extensions = [\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ])\n # ----- 评论代码开始 ----\n # 1.评论输入表单(输入框)\n form = CommentForm()\n\n # 2.获取这篇Post下的全部评论列表\n comment_list = post.comment_set.all()\n\n # 将文章、表单、以及文章下的评论列表作为模板变量传给detail.html模板,以便渲染相应数据。\n context = {'post': post,\n 'form': form,\n 'comment_list': comment_list\n }\n # ---- 评论代码结束 ----\n return render(request, 'blog/detail.html', context = context)\n'''\n\n\nclass PostDetailView(DetailView):\n # 这些属性的含义和 ListView 是一样的\n model = Post\n template_name = 'blog/detail.html'\n context_object_name = 'post'\n\n def get(self, request, *args, **kwargs):\n # 覆写 get 方法的目的是因为每当文章被访问一次,就得将文章阅读量 +1\n # get 方法返回的是一个 HttpResponse 实例\n # 之所以需要先调用父类的 get 方法,是因为只有当 get 方法被调用后,\n # 才有 self.object 属性,其值为 Post 模型实例,即被访问的文章 post\n response = super(PostDetailView, self).get(request, *args, **kwargs)\n\n # 将文章阅读量 +1\n # 注意 self.object 的值就是被访问的文章 post\n self.object.increase_views()\n\n # 视图必须返回一个 HttpResponse 对象\n return response\n\n def get_object(self, queryset=None):\n # 覆写 get_object 方法的目的是因为需要对 post 的 body 值进行渲染\n post = super(PostDetailView, self).get_object(queryset=None)\n '''\n # 这种方式是没有添加标题目录之前的渲染body的方式\n post.body = markdown.markdown(post.body,\n extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ])\n '''\n # 更改渲染body的方式(实现标题的目录)\n md = markdown.Markdown(extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n # 'markdown.extensions.toc',\n # 记得在顶部引用TocExtension 和 slugify\n TocExtension(slugify = slugify),\n ])\n post.body = md.convert(post.body)\n post.toc = md.toc\n\n return post\n\n def get_context_data(self, **kwargs):\n # 覆写 get_context_data 的目的是因为除了将 post 传递给模板外(DetailView 已经帮我们完成),\n # 还要把评论表单、post 下的评论列表传递给模板。\n context = super(PostDetailView, self).get_context_data(**kwargs)\n form = CommentForm()\n comment_list = self.object.comment_set.all()\n context.update({\n 'form': form,\n 'comment_list': comment_list\n })\n return context\n\n\n'''\n# 文章归档视图函数(侧边栏以月份的归档\"2017年05月\")\ndef archives(request, year, month):\n post_list = Post.objects.filter(created_time__year=year,\n created_time__month=month\n )\n #).order_by('-created_time')\n return render(request, 'blog/index.html', context={'post_list': post_list})\n'''\n\nclass ArchivesView(IndexView):\n def get_queryset(self):\n return super(ArchivesView, self).get_queryset().filter(\n created_time__year = self.kwargs.get('year'),\n created_time__month=self.kwargs.get('month')\n )\n\n\n'''\n# 文章以目录分类的视图函数\ndef category(request, pk):\n cate = get_object_or_404(Category, pk=pk)\n post_list = Post.objects.filter(category=cate)\n #post_list = Post.objects.filter(category=cate).order_by('-created_time')\n return render(request, 'blog/index.html', context={'post_list': post_list})\n'''\nclass CategoryView(IndexView):\n def get_queryset(self):\n cate = get_object_or_404(Category, pk=self.kwargs.get('pk'))\n return super(CategoryView, self).get_queryset().filter(category=cate)\n\n# 标签对应下的博客文章, 非常类似分类视图\nclass TagView(ListView):\n model = Post\n template_name = 'blog/index.html'\n context_object_name = 'post_list'\n\n def get_queryset(self):\n tag = get_object_or_404(Tag, pk=self.kwargs.get('pk'))\n return super(TagView, self).get_queryset().filter(tags=tag)\n\n# 关键词搜索视图函数\ndef search(request):\n q = request.GET.get('q')\n error_msg = ''\n if not q:\n error_msg = \"请输入关键词\"\n return render(request, 'blog/index.html', {'error_msg': error_msg})\n post_list = Post.objects.filter(Q(title__icontains = q) | Q(body__icontains = q))\n return render(request, 'blog/index.html', {'error_msg':error_msg, 'post_list': post_list})\n\n# 首页中\"关于\"的页面视图函数\ndef about(request):\n return render(request, 'blog/about.html')\n\n# 首页中\"联系\"的页面视图函数\ndef contact(request):\n return render(request, 'blog/contact.html')\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"212441023","text":"\nimport os\nimport random\n\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.contrib.staticfiles.testing import StaticLiveServerTestCase\nfrom django.test import override_settings\nfrom django.core.urlresolvers import reverse\nfrom django.utils import translation\n\nfrom selenium.webdriver.firefox.webdriver import WebDriver\n\nfrom apps.app_files.models import Photo, Video\n\n\n@override_settings(ROOT_URLCONF='project_brat.urls')\nclass TestLive(StaticLiveServerTestCase):\n\n fixtures = []\n\n @classmethod\n def setUpClass(cls):\n super(TestLive, cls).setUpClass()\n translation.activate('en')\n cls.selenium = WebDriver()\n # find media for tests\n abs_path_to_parent_folder = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n path_to_media_for_tests = '/tests/media_for_tests/'\n folder_for_test_photos = 'photos_for_tests/'\n folder_for_test_videos = 'videos_for_tests/'\n folder_for_test_musics = 'musics_for_tests/'\n cls.abs_path_to_folder_with_test_photo = abs_path_to_parent_folder + path_to_media_for_tests + folder_for_test_photos\n cls.abs_path_to_folder_with_test_videos = abs_path_to_parent_folder + path_to_media_for_tests + folder_for_test_videos\n cls.abs_path_to_folder_with_test_musics = abs_path_to_parent_folder + path_to_media_for_tests + folder_for_test_musics\n\n @classmethod\n def tearDownClass(cls):\n super(TestLive, cls).tearDownClass()\n cls.selenium.quit()\n\n def test_state_btn_search(self):\n self.selenium.get(\"{0}{1}\".format(self.live_server_url, reverse('app_files:musics')))\n btn_for_search = self.selenium.find_element_by_id('button_for_search_music')\n self.assertFalse(btn_for_search.is_enabled())\n self.selenium.find_element_by_id('input_for_search_music').send_keys('test-test')\n self.selenium.find_element_by_tag_name('body').click()\n self.assertTrue(btn_for_search.is_enabled())\n btn_for_search.click()\n\n def test_displaying_photo(self):\n try:\n photo_filename = random.choice(os.listdir(self.abs_path_to_folder_with_test_photo))\n path_to_file = self.abs_path_to_folder_with_test_photo + photo_filename\n full_filename = os.path.split(path_to_file)[1]\n only_filename, file_extension = full_filename.rsplit('.', 1)\n with open(path_to_file, 'rb') as photo_file:\n uploaded_file = SimpleUploadedFile(name=full_filename, content=photo_file.read(), content_type='image/'+file_extension)\n Photo.objects.create(title=only_filename, path=uploaded_file)\n self.selenium.get(\"{0}{1}\".format(self.live_server_url, reverse('app_files:photos')))\n self.selenium.find_element_by_class_name('fancybox').click()\n finally:\n os.remove(Photo.objects.first().path.path)\n\n def test_displaing_videos_and_video_review(self):\n try:\n only_mp4_file = tuple(i for i in os.listdir(self.abs_path_to_folder_with_test_videos) if i.endswith('.mp4'))\n video_filename = random.choice(only_mp4_file)\n path_to_file_mp4 = self.abs_path_to_folder_with_test_videos + video_filename\n path_to_file_ogg = path_to_file_mp4[:-3] + 'ogv'\n full_filename_mp4 = os.path.split(path_to_file_mp4)[1]\n full_filename_ogg = os.path.split(path_to_file_ogg)[1]\n only_filename = full_filename_mp4.rsplit('.', 1)[0]\n with open(path_to_file_mp4, 'rb') as file_video_mp4:\n with open(path_to_file_ogg, 'rb') as file_video_ogg:\n uploaded_file_mp4 = SimpleUploadedFile(name=full_filename_mp4, content=file_video_mp4.read(), content_type='audio/mp4')\n uploaded_file_ogg = SimpleUploadedFile(name=full_filename_ogg, content=file_video_ogg.read(), content_type='audio/ogg')\n Video.objects.create(title=only_filename, path_to_mp4=uploaded_file_mp4, path_to_ogg=uploaded_file_ogg)\n self.selenium.get(\"{0}{1}\".format(self.live_server_url, reverse('app_files:videos')))\n self.selenium.find_element_by_partial_link_text(Video.objects.first().title).click()\n finally:\n os.remove(Video.objects.first().path_to_ogg.path)\n os.remove(Video.objects.first().path_to_mp4.path)\n\n def test_css_view_page(self):\n self.selenium.get(\"{0}{1}\".format(self.live_server_url, reverse('app_files:musics')))\n self.assertIn('/img/pattern_table_musics.png', self.selenium.find_element_by_id('table_of_music').value_of_css_property('background-image'))\n self.assertEqual(self.selenium.find_element_by_id('table_of_music').value_of_css_property('box-shadow'), 'rgb(0, 0, 0) 3px 3px 3px 0px')\n self.assertEqual(self.selenium.find_element_by_id('table_of_music').value_of_css_property('color'), 'rgba(34, 34, 34, 1)')\n","sub_path":"project/apps/files/tests/tests_live.py","file_name":"tests_live.py","file_ext":"py","file_size_in_byte":4916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"8357424","text":"from components import app\n\nfrom flask import Flask, render_template, flash, redirect, url_for, request\nfrom typing import List, Dict\n\n\n@app.route('/setupdb')\ndef setupdb() -> str:\n db.create_all()\n admin = User(username='admin', email='admin@example.com')\n guest = User(username='guest', email='guest@example.com')\n db.session.add(admin)\n db.session.add(guest)\n db.session.commit()\n return \"db setup\"\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n if form.validate_on_submit():\n flash('Login requested for user {}, remember_me={}'.format(\n form.username.data, form.remember_me.data))\n return redirect('/index')\n return render_template('login.html', title='Sign In', form=form)\n\n\n@app.route('/')\n@app.route('/index')\n@login_required\ndef index():\n user = {'username': 'Miguel'}\n posts = [\n {\n 'author': {'username': 'John'},\n 'body': 'Beautiful day in Portland!'\n },\n {\n 'author': {'username': 'Susan'},\n 'body': 'The Avengers movie was so cool!'\n }\n ]\n return render_template('index.html', title='Home', user=user, posts=posts)\n","sub_path":"app/backend/components/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"637783589","text":"class Restaurant:\n def __init__(self, name, type):\n f = open('고객서빙현황로그.txt', 'r', encoding = 'UTF-8')\n self.number_served = int(f.readline())\n f.close()\n self.order_list = []\n self.restaurant_name = name\n self.cuisine_type = type\n self.todays_customer = 0\n self.f = open('고객서빙현황로그.txt', 'w', encoding='UTF-8')\n\n def describe_restaurant(self):\n print(\"저희 레스토랑 명칭은 %s 이고 %s 전문점입니다.\"%(self.restaurant_name, self.cuisine_type))\n\n def open_restaurant(self):\n print(\"저희 %s 레스토랑 오픈했습니다. 어서오세요.\" % self.restaurant_name)\n\n def reset_number_served(self, number):\n self.todays_customer = number\n\n def increment_number_served(self, number):\n self.todays_customer += number\n\n def check_customer_number(self):\n print(\"지금까지 총 %d명 손님께서 오셨습니다.\\n\"%self.todays_customer)\n\n def order_menu(self):\n menu = '음식'\n print(\"%s을 주문하셨습니다.\\n\"%menu)\n\n def __del__(self):\n print(\"\\n%s 레스토랑 문닫습니다.\\n\\n이용해 주셔서 감사합니다.\"%self.restaurant_name)\n self.f.write(\"%d\\n\" %(self.number_served + self.todays_customer))\n self.f.close()\n\n\nclass Korean_Rest(Restaurant):\n def describe_restaurant(self):\n print(\"저희 레스토랑 명칭은 %s 이고 한식 전문점입니다.\"%self.restaurant_name)\n\n def order_menu(self, order):\n if order == 0:\n print(self.order_list)\n print(\"주문완료하셨습니다.\")\n return\n elif order == 1:\n self.menu = '김치찌개'\n elif order == 2:\n self.menu = '된장찌개'\n elif order == 3:\n self.menu = '순두부찌개'\n elif order == 4:\n self.menu = '동태찌개'\n elif order == 5:\n self.menu = '공기밥'\n print(\"%s 주문하셨습니다.\" % self.menu)\n self.order_list.append(self.menu)\n\n\nclass Japanese_Rest(Restaurant):\n def describe_restaurant(self):\n print(\"저희 레스토랑 명칭은 %s 이고 일일식 전문점입니.\"%self.restaurant_name)\n\n def order_menu(self, order):\n if order == 0:\n print(restaurant.order_list)\n print(\"주문완료하셨습니다.\")\n return\n elif order == 1:\n self.menu = '스시'\n elif order == 2:\n self.menu = '돈가스'\n elif order == 3:\n self.menu = '우동'\n elif order == 4:\n self.menu = '라멘'\n elif order == 5:\n self.menu = '규동'\n print(\"%s 주문하셨습니다.\" % self.menu)\n self.order_list.append(self.menu)\n\nname, type = input(\"레스토랑 이름과 요리 종류를 선택하세요.(공백으로 구분) : \").split()\nif type == 'k':\n restaurant = Korean_Rest(name, type)\nelif type == 'j':\n restaurant = Japanese_Rest(name, type)\nelse:\n restaurant = Restaurant(name, type)\n\nrestaurant.describe_restaurant()\nopen = input(\"레스토랑을 오픈하시겠습니까? (y/n) : \")\nif open == 'y':\n restaurant.open_restaurant()\n while True:\n option = str(input(\"어서오세요. 몇명이십니까?(초기화:0입력, 종료:-1, 누적고객 확인:p) : \"))\n if option == '0':\n restaurant.reset_number_served(0)\n print(\"손님 카운팅을 0으로 초기화 하였습니다.\\n\")\n elif option == '-1':\n print(\"\\n주문받겠습니다.\\n\")\n break\n elif option == 'p':\n restaurant.check_customer_number()\n else:\n print(\"손님 %d명 들어오셨습니다. 자리를 안내해드리겠습니다.\\n\" % int(option))\n restaurant.increment_number_served(int(option))\n\n while True:\n if isinstance(restaurant, Korean_Rest):\n order = int(input(\"메뉴를 선택하십시오.\\n1.김치찌개\\n2.된장찌개\\n3.순두부찌개\\n4.동태찌개\\n5.공기밥\\n메뉴번호 입력(0=주문종료) : \"))\n elif isinstance(restaurant, Japanese_Rest):\n order = int(input(\"메뉴를 선택하십시오.\\n1.스시\\n2.돈가스\\n3.우동\\n4.라멘\\n5.규동\\n메뉴번호 입력(0=주문종료) : \"))\n print()\n restaurant.order_menu(order)\n\n if order == 0:\n break\n\n","sub_path":"01_Jump_to_Python/Chap05/Restaurant_v5.py","file_name":"Restaurant_v5.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"569057360","text":"# coding:utf-8\n'''\nGradien Boosting\n'''\nimport sklearn,pandas, pickle, os, summary, util\nimport numpy as np\n\nfrom sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, GradientBoostingClassifier\nfrom sklearn.metrics import f1_score\nfrom sklearn.grid_search import GridSearchCV\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.linear_model import LogisticRegression\n\nimport model16\n\n__fname__ = os.path.basename(__file__)\n__fname__ = __fname__[:__fname__.rindex('.')]\n\t\ndef GetData():\n\t\n\tdata = pandas.read_csv('data.train.csv')\n\t\n\tY=data['buy']\n\t\n\tX=GetFeature(data)\n\t\n\t\n\treturn X, Y\n\t\n_feature_names = model16._feature_names\ndef GetFeature(data):\n\n\t\n\t\n\t\n\treturn model16.GetFeature(data)\n\t\t\ndef GetModel():\n\t\n\tf = open('%s.model' % __fname__,'rb')\n\tclf = pickle.load(f)\n\tf.close()\n\treturn clf\n\ndef TestModel():\n\treturn summary.TestModel(__fname__)\n\t\nif __name__ == '__main__':\n\t\n\tX, Y = GetData()\n\tsamples = (np.random.rand(len(Y))<0.25) | (Y==1)\n\tX = X[samples]\n\tY = Y[samples]\n\t\n\tfeature_names = X.columns\n\tparms = {\n\t\t'n_estimators' : [200],\n\t\t'max_leaf_nodes' : [3],\n\t\t'learning_rate' : [.05],\n\t\t'min_samples_leaf' : [6],\n\t\t\n\t}\n\t#tr = ExtraTreesClassifier(n_jobs=10)\n\tgb = GradientBoostingClassifier(init=LogisticRegression())\n\tpipe = Pipeline([('gb',gb)])\n\tclf = GridSearchCV(gb, parms, scoring='f1', n_jobs=10)\n\n\tclf.fit(X,Y)\n\t\n\timport pickle\n\tf = open('%s.model' % __fname__,'wb')\n\tpickle.dump(clf, f)\n\tf.close()\n\t\n\t\n\t\n\tpred = clf.predict(X)\n\t\n\tsummary.clf_summary(clf, feature_names)\n\tsummary.summary(Y, pred)\n\t\n\t\n\tF1, P, R = TestModel()\n\t\n\tutil.notify_me('%s.F1:%.2f,P:%.2f,R:%.2f' % (__fname__, F1*100, P*100, R*100))\n\n\n","sub_path":"model25.py","file_name":"model25.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"556552156","text":"\"\"\"\n输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。\n序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。\n\n示例 1:\n输入:target = 9\n输出:[[2,3,4],[4,5]]\n\n示例 2:\n输入:target = 15\n输出:[[1,2,3,4,5],[4,5,6],[7,8]]\n\"\"\"\n\n\n# 数学\n# target = 求和 x, x+1, x+2, x+3, .....\n# 即 target = k * x + b\n# 当 上式 成立 即 可 [x, x+1, x+2, ...x+k-1] 成为答案\nclass Solution:\n # def findContinuousSequence(self, target: int) -> List[List[int]]:\n def findContinuousSequence(self, target):\n # target = k * x + b\n ans = []\n k = 2\n b = 1\n while b < target:\n if (target - b) % k == 0:\n temp = []\n # 构造答案\n x = (target - b) // k\n for i in range(k):\n temp.append(x+i)\n ans.append(temp)\n b = b + k\n k = k + 1\n ans.reverse()\n # 其实可以优化一下 就先找到 最大的上限 b 然后 倒着来 就不需要 ans.reverse() 了\n return ans\n\n def findContinuousSequence_MoveWindow(self, target):\n i = 1 # 滑动窗口的左边界\n j = 1 # 滑动窗口的右边界\n sum = 0 # 滑动窗口中数字的和\n res = []\n while i <= target // 2:\n if sum < target:\n # 右边界向右移动\n sum += j\n j += 1\n elif sum > target:\n # 左边界向右移动\n sum -= i\n i += 1\n else:\n # 记录结果\n arr = list(range(i, j))\n res.append(arr)\n # 左边界向右移动\n sum -= i\n i += 1\n return res\n\n\nif __name__ == '__main__':\n target = 15\n print(Solution().findContinuousSequence(target))\n\n # print(9 / 2) # 小数除法\n # print(9 // 2) # 取商\n # print(9 % 2) # 取余\n","sub_path":"SwordOffer-3/O57-II.py","file_name":"O57-II.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"286091554","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nfrom optparse import OptionParser\n\nimport numpy as np\nimport scipy as ci \nimport matplotlib\nmatplotlib.use('agg') # no 'plt.show()' any more; able to save to file, not render a window! \nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\n\nimport tables \n\nfrom I3Tray import I3Tray\nfrom icecube import icetray, dataclasses, dataio, hdfwriter, tableio, phys_services, simclasses, recclasses # simclass: MMCTrackList\nfrom icecube import linefit, spline_reco, cscd_llh, portia # spline_reco: Fitparam\nfrom icecube.weighting import weighting\nfrom icecube.icetray import I3Units\nfrom icecube.phys_services import I3Calculator\n\n### nugen weighting: atm{conventional, prompt} + astro, each has 3 flavors\n# atm_conv: Weight_honda2006_gaisserH4a_elbert # use this one\n# atm_conv_KaonCont0_Pioncont1: Weight_honda2006_gaisserH4a_elbert_KaonCont0_PionCont1\n# atm_conv_KaonCont1_Pioncont0: Weight_honda2006_gaisserH4a_elbert_KaonCont1_PionCont0\n# atm_prompt_central: Weight_BERSS_H3p_central # use this one\n# atm_prompt_lower: Weight_BERSS_H3p_lower\n# atm_prompt_upper: Weight_BERSS_H3p_upper\n\n### n_file for weighting: (Jul 29, 2019). Accounted goodrunlist. \n# 11374: 18989\n# 11477: 19956\n# 11981: 19956\n# 11057: 72701\n# Livetime of processed 2012 data = 2813559.84254\n# Livetime of processed 2013 data = 2955469.73138\n# Livetime of processed 2014 data = 3052686.52963\n# Livetime of processed 2015 data = 3240653.63454\n# Livetime of processed 2016 data = 2919677.64478\n\n# NOTE: This file checks the weighted statistics of the current mc (astro numu and corsika) samples after converting i3 to h5. \n# NOTE: Now (May 22, 2019), all the files are AFTER preselection on Downgoing (reco), truncated muon E > 300 TeV, Qtot > 4000 PE, len(dE/dx) > 4\n\n\n\" ----- corsika/nugen ----- \"\n\nfile_list = ['/data/user/yanglyu/my_proj/analysis_1_downgoing_neutrino/data/corsika_h5/corsika_11057.h5',\n '/data/user/yanglyu/my_proj/analysis_1_downgoing_neutrino/data/nugen_h5/nugen_11374.h5']\n\nfig_dir = '/data/user/yanglyu/my_proj/analysis_1_downgoing_neutrino/1_distribution_plots/plots/0-1_' # save fig to dir\n\nfor my_file in file_list:\n print('loading mc...')\n\n with tables.open_file(my_file,'r') as f:\n lifetime = 365*86400 \n\n chi2 = f.root.Collection.cols.chi2[:]\n ndf = f.root.Collection.cols.NDF[:]\n chi2_red = chi2/ndf\n PeakOverMedian = f.root.Collection.cols.PeakOverMedian[:]\n zenith_truth = f.root.MCPrimary.cols.zenith[:]\n energy = f.root.MCPrimary.cols.energy[:]\n bundle_size = f.root.Bundle_Size.cols.value[:]\n muon_e = f.root.Bundle_truth_muon_energy_prod_in_atm.cols.value[:]\n muon_ec = f.root.Bundle_truth_muon_energy_center.cols.value[:]\n Q_tot = f.root.QTot.cols.value[:]\n truncated_muon_e = f.root.SPEFit4TruncatedEnergy_SPICEMie_DOMS_Muon.cols.energy[:]\n\n if 'nugen' in my_file:\n mc_generator = 'astro_numu'\n zenith_reco = f.root.SPEFit4TruncatedEnergy_SPICEMie_DOMS_Muon.cols.zenith[:]\n\n ### astrophysical ###\n n_file = 18989\n energy = f.root.MCPrimary.cols.energy[:]\n ptype = f.root.MCPrimary.cols.type[:]\n zenith = f.root.MCPrimary.cols.zenith[:]\n p_int = f.root.I3MCWeightDict.cols.TotalInteractionProbabilityWeight[:]\n generator = weighting.from_simprod(11374)\n gen = generator(energy,ptype,np.cos(zenith))\n unit = I3Units.cm2/I3Units.m2\n\n my_weight = (6.7 * 10**(-18))/6 * (energy/10**5)**(-2) * p_int / gen / unit * lifetime/n_file\n\n\n elif 'corsika' in my_file:\n mc_generator = 'corsika'\n zenith_reco = f.root.SPEFit4TruncatedEnergy_SPICEMie_DOMS_Muon.cols.zenith[:]\n\n n_file = 72701 # modified\n my_weight = f.root.Weight_GaisserH4a.cols.value[:] * lifetime/n_file\n\n\n\n\n \" ----- check chi2 for single and bundle ----- \"\n\n plt.figure()\n plt.subplot(121)\n plt.hist(chi2[bundle_size==1],bins=30, log=True, histtype='step', lw=2, label='Single Muon',weights=my_weight[bundle_size==1])\n plt.hist(chi2[bundle_size>1],bins=30, log=True, histtype='step', lw=2, label='Muon Bundle',weights=my_weight[bundle_size>1])\n plt.xlabel(r'$\\chi^2$')\n plt.ylabel('# of events/year')\n plt.legend()\n plt.subplot(122)\n plt.hist(chi2_red[bundle_size==1],bins=30, log=True, histtype='step', lw=2, label='Single Muon, red',weights=my_weight[bundle_size==1])\n plt.hist(chi2_red[bundle_size>1],bins=30, log=True, histtype='step', lw=2, label='Muon Bundle, red',weights=my_weight[bundle_size>1])\n plt.xlabel(r'$\\chi^2_{red}$')\n plt.ylabel('# of events/year')\n plt.legend()\n plt.suptitle(mc_generator+' chi2 distribution')\n plt.savefig(fig_dir+'hist1d_single_bundle_chi2_comparison_'+mc_generator+'.png',dpi=600)\n\n plt.figure()\n plt.hist(np.log10(PeakOverMedian[bundle_size==1]),bins=30, log=True, histtype='step', lw=2, label='Single Muon',weights=my_weight[bundle_size==1])\n plt.hist(np.log10(PeakOverMedian[bundle_size>1]),bins=30, log=True, histtype='step', lw=2, label='Muon Bundle',weights=my_weight[bundle_size>1])\n\n plt.xlabel(r'$log_{10}$(Peak over Median)')\n plt.ylabel('# of events/year')\n plt.legend()\n plt.title(mc_generator+' Peak_over_Median distribution')\n plt.savefig(fig_dir+'hist1d_single_bundle_PeakOverMedian_comparison_'+mc_generator+'.png',dpi=600)\n\n\n \" ----- physical quantity distribution ----- \"\n\n plt.figure(figsize=(15,10))\n\n plt.subplot(241)\n plt.hist(chi2,bins=40,log=True,histtype='step',lw=3,weights=my_weight)\n plt.xlabel('chi2')\n\n plt.subplot(242)\n plt.hist(chi2_red,bins=40,log=True,histtype='step',lw=3,weights=my_weight)\n plt.xlabel('reduced chi2')\n\n plt.subplot(243)\n plt.hist(np.cos(zenith_truth),bins=20,log=True,histtype='step',lw=3,weights=my_weight)\n plt.xlabel('cos(zenith_truth)')\n\n plt.subplot(244)\n plt.hist(np.cos(zenith_reco),bins=20,log=True,histtype='step',lw=3,weights=my_weight)\n plt.xlabel('cos(zenith_reco)')\n\n plt.subplot(245)\n plt.hist(np.log10(PeakOverMedian),bins=20,log=True,histtype='step',lw=3,weights=my_weight)\n plt.xlabel(r'$log_{10}$(peak/median)')\n\n plt.subplot(246)\n plt.hist(ndf,log=True,histtype='step',lw=3,weights=my_weight) # NDF = len(bin) - 2 #ndf is number of data points - number of fit parameters\n plt.xlabel('NDF')\n\n plt.subplot(247)\n plt.hist(np.log10(Q_tot),bins=20,log=True,histtype='step',lw=3,weights=my_weight)\n plt.axvline(np.log10(4000),label='4000 PE',color='orange')\n plt.legend()\n plt.xlabel(r'$log_{10}$(Q_tot) (PE)')\n\n plt.subplot(248)\n plt.hist(np.log10(truncated_muon_e[truncated_muon_e>0]),bins=20,log=True,histtype='step',lw=3,weights=my_weight)\n plt.axvline(np.log10(300000),label='300 TeV',color='orange')\n plt.legend()\n plt.xlabel(r'$log_{10}$(truncated muon energy) [GeV]')\n\n plt.suptitle('Various quantities - '+mc_generator)\n plt.savefig(fig_dir+'statistics_'+mc_generator+'.png',dpi=600)\n\n\n \" ----- stochasticity vs zenith_reco angle 2d ----- \"\n\n plt.figure()\n plt.hist2d(np.cos(zenith_reco),chi2_red,bins=40,cmap='rainbow',weights=my_weight)\n # plt.xlim(0,1)\n plt.xlabel('cos(zenith_reco)')\n plt.ylabel('chi2_red')\n plt.title('reduced chi2 vs zenith_reco - '+mc_generator)\n plt.colorbar()\n plt.savefig(fig_dir+'hist2d_stoch_vs_zenith_'+mc_generator+'.png',dpi=600)\n\n\n \" ----- stochasticity vs zenith_reco angle 1-d sliced ----- \"\n\n plt.figure(figsize=(15,20))\n for i in range(0,10):\n plt.subplot(4,3,i+1)\n plt.hist(chi2_red[(zenith_reco > i*0.1) & (zenith_reco <= 0.1+i*0.1)],log=True,histtype='step',bins=20,lw=3,weights=my_weight[(zenith_reco > i*0.1) & (zenith_reco <= 0.1+i*0.1)])\n plt.xlabel('chi2_red')\n plt.ylabel('# of events/year')\n plt.title(str(i*0.1)+' 0\n\ngithub_df = create_github_stars(row_count)\n\nperson_df = pd.DataFrame(\n {\n 'person_id': id_list, 'age': age, 'income': income,\n 'height': height, 'is_client': is_client\n }\n)\nperson_github_df = create_person_github()\n\ntry:\n print(\"Adding data to mariadb...\")\n with mariadb_engine.connect() as mdb_conn, mdb_conn.begin():\n person_df.to_sql('person', mdb_conn, if_exists='replace')\n github_df.to_sql('github', mdb_conn, if_exists='replace')\n person_github_df.to_sql('person_github', mdb_conn, if_exists='replace')\n print(\"Added data to mariadb\")\nexcept Error as e:\n print(e)\n","sub_path":"docker-environment/init_mariadb.py","file_name":"init_mariadb.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"11486622","text":"import os\nimport time\nimport argparse\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nfrom sklearn.preprocessing import StandardScaler\n\nfrom models.linear_regression import LinearRegression\n\nplt.style.use('seaborn')\n\n\ndef getArguments():\n parser = argparse.ArgumentParser(description='Parameters to tweak Linear Regression.')\n\n parser.add_argument('--lr', type=float, default=3e-2,\n help='Learning rate. Defaults to 0.03')\n parser.add_argument('--max_epochs', type=int, default=10,\n help='Maximum epochs for gradient descent to run. Defaults to 10')\n parser.add_argument('-e', '--epsilon', type=float, default=1e-3,\n help='Epsilon for checking convergence. Defaults to 0.001')\n parser.add_argument('-s', '--save', action='store_true',\n help=\"Flag to save visualizations and animations\")\n parser.add_argument('-l', '--length', type=int, default=5,\n help=\"Length of the animation in seconds. Defaults to 5\")\n parser.add_argument('-b', '--batch_size', type=int, default=10,\n help=\"Batch size to be taken for mini-batch gradient descent. Defaults to 10\")\n parser.add_argument('-m', '--n_samples', type=int, default=200,\n help=\"Number of training examples. Defaults to 200\")\n parser.add_argument('--noise', type=float, default=0.7,\n help=\"Noise of the dataset. Defaults to 0.7\")\n\n return parser.parse_args()\n\n\ndef getCircularDataset(n_samples=200, noise=1):\n center = np.random.uniform(low=-10, high=10)\n\n x = np.random.normal(size=(n_samples, 1))\n y = center**2 - x**2\n\n if noise:\n noiseData = np.random.normal(scale=noise, size=(n_samples, 1))\n y += noiseData\n\n return x, y\n\n\ndef animate(i, dataset, costDataset, line, c_line):\n x = dataset[0]\n preds = dataset[1][i]\n line.set_data(x, preds)\n c_line.set_data(costDataset[:, :i])\n return line, c_line\n\n\ndef plotAndSaveGraphs(lr, args, scaler):\n\n # destructure history object\n history = lr.getHistory()\n thetaHistory = np.array(history['theta'])\n costHistory = history['cost']\n totalIterations = len(costHistory) - 1\n costDataset = np.array([np.arange(1, totalIterations + 2), costHistory])\n\n # make directories\n if args.save:\n pathToDirectory = os.path.join('visualizations', 'linear_regression')\n if not os.path.exists(pathToDirectory):\n os.makedirs(pathToDirectory)\n\n fullData = np.linspace(lr.x[:, 1].min(), lr.x[:, 1].max(), 100).reshape(-1, 1)\n squared = np.concatenate((fullData, (fullData[:, 0]**2).reshape(-1, 1)), axis=1)\n squared = scaler.transform(squared)\n\n fullDataWithOnes = np.concatenate((np.ones((squared.shape[0], 1)), squared), axis=1)\n\n fig = plt.figure(figsize=(16, 9))\n ax1 = fig.add_subplot(121)\n\n sns.scatterplot(x=lr.x[:, 1].reshape(-1,), y=lr.y.reshape(-1,),\n ax=ax1, label='Datapoint')\n\n hypotheses = []\n for theta in thetaHistory:\n theta = np.array(theta).reshape(-1, 1)\n fullDataPrediction = lr.getPrediction(fullDataWithOnes, theta)\n hypotheses.append(fullDataPrediction)\n\n dataset = np.array([fullData, hypotheses], dtype=object)\n\n line = ax1.plot(dataset[0], dataset[1][-1], c='r', label='Hypothesis',\n alpha=0.6)[0]\n\n ax1.set_xlabel('X')\n ax1.set_ylabel('Y')\n ax1.set_title('Training Dataset')\n ax1.legend()\n\n ax2 = fig.add_subplot(122)\n\n # plot training cost history\n c_line = ax2.plot(costDataset[0], costDataset[1], label='Cost')[0]\n ax2.set_xlabel('Number of iterations')\n ax2.set_ylabel('Cost')\n ax2.set_title(f'Iterations: {totalIterations} lr: {args.lr} batch_size: {args.batch_size}')\n ax2.legend()\n\n lengthOfVideo = args.length\n nFrames = totalIterations + 1\n interval = lengthOfVideo * 1000 / nFrames\n fps = (1 / (interval / 1000))\n\n print('=' * 80)\n print('[INFO]\\t\\tParameters for Animation')\n print('=' * 80)\n print(f'[INFO] Duration of video: {lengthOfVideo} seconds')\n print(f'[DEBUG] Total number of frames: {nFrames}')\n print(f'[DEBUG] Interval for each frame: {interval}')\n print(f'[DEBUG] FPS of video: {fps}')\n print('=' * 80)\n\n ani = animation.FuncAnimation(fig, animate, fargs=(dataset, costDataset, line, c_line),\n frames=nFrames, blit=False,\n interval=interval, repeat=True)\n\n if args.save:\n fileName = os.path.join(pathToDirectory, 'NonLinearLinearRegression.mp4')\n print('[INFO] Saving animation...')\n startTime = time.time()\n ani.save(fileName, fps=fps)\n timeDifference = time.time() - startTime\n print(f'[INFO] Animation saved to {fileName}. Took {timeDifference:.2f} seconds.')\n plt.close()\n else:\n plt.show()\n\n # plot distribution of theta\n fig = plt.figure(figsize=(16, 9))\n ax1 = fig.add_subplot(131)\n\n sns.kdeplot(x=thetaHistory[:, 0].reshape(-1,), fill=True, ax=ax1, label='Theta1 Values')\n ax1.set_xlabel('Theta1 values')\n ax1.set_title('Distribution of theta1')\n ax1.legend()\n\n ax2 = fig.add_subplot(132)\n\n sns.kdeplot(x=thetaHistory[:, 1].reshape(-1,), fill=True, ax=ax2, label='Theta2 Values')\n ax2.set_xlabel('Theta2 values')\n ax2.set_title('Distribution of theta2')\n ax2.legend()\n\n ax3 = fig.add_subplot(133)\n\n sns.kdeplot(x=thetaHistory[:, 2].reshape(-1,), fill=True, ax=ax3, label='Theta3 Values')\n ax3.set_xlabel('Theta3 values')\n ax3.set_title('Distribution of theta3')\n ax3.legend()\n\n if args.save:\n fileName = os.path.join(pathToDirectory, 'NonLinearDistributionOfGradients.png')\n plt.savefig(fileName)\n print(f'[INFO] Distribution of gradients saved to {fileName}')\n plt.close()\n else:\n plt.show()\n\n\ndef main():\n args = getArguments()\n print('[DEBUG]', args)\n\n x, y = getCircularDataset(n_samples=args.n_samples,\n noise=args.noise)\n\n nf = x[:, 0]**2\n x = np.concatenate((x, nf.reshape(-1, 1)), axis=1)\n\n scaler = StandardScaler()\n x = scaler.fit_transform(x)\n\n lr = LinearRegression(x,\n y.reshape(-1, 1),\n alpha=args.lr,\n max_epochs=args.max_epochs,\n epsilon=args.epsilon,\n batch_size=args.batch_size)\n\n bestTheta = lr.getThetaByNormalEquations()\n bestPredictions = lr.getPrediction(lr.x, bestTheta)\n bestCost = lr.getCost(bestPredictions, lr.y)\n\n print(f'[DEBUG] Best Theta: {bestTheta.tolist()}')\n print(f'[DEBUG] Best Cost: {bestCost}')\n\n lr.runGradientDescent()\n optimizedTheta = lr.theta\n optimizedPredictions = lr.getPrediction(lr.x, optimizedTheta)\n optimizedCost = lr.getCost(optimizedPredictions, lr.y)\n\n print(f'[DEBUG] Optimized Theta: {optimizedTheta.tolist()}')\n print(f'[DEBUG] Optimized Cost: {optimizedCost}')\n\n plotAndSaveGraphs(lr, args, scaler)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Code/Visualization/Machine-Learning-Gautam-J/run_linear_regression_non_linear.py","file_name":"run_linear_regression_non_linear.py","file_ext":"py","file_size_in_byte":7193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"281747232","text":"import tensorflow as tf\nfrom openrec.recommenders import BPR\nfrom openrec.modules.interactions import PairwiseEuDist\n\nclass CML(BPR):\n\n def _build_post_training_ops(self):\n unique_user_id, _ = tf.unique(self._user_id_input)\n unique_item_id, _ = tf.unique(tf.concat([self._p_item_id_input, self._n_item_id_input], axis=0))\n return [self._user_vec.censor_l2_norm_op(censor_id_list=unique_user_id),\n self._p_item_vec.censor_l2_norm_op(censor_id_list=unique_item_id)]\n\n def _build_interactions(self, train=True):\n\n if train:\n self._interaction_train = PairwiseEuDist(user=self._user_vec.get_outputs()[0], \n p_item=self._p_item_vec.get_outputs()[0],\n n_item=self._n_item_vec.get_outputs()[0], \n p_item_bias=self._p_item_bias.get_outputs()[0],\n n_item_bias=self._n_item_bias.get_outputs()[0], \n train=True, scope='pairwise_eu_dist', reuse=False)\n self._loss_nodes.append(self._interaction_train)\n else:\n self._interaction_serve = PairwiseEuDist(user=self._user_vec_serving.get_outputs()[0], \n item=self._item_vec_serving.get_outputs()[0],\n item_bias=self._item_bias_serving.get_outputs()[0], \n train=False, scope='CML', reuse=False)\n","sub_path":"openrec/recommenders/cml.py","file_name":"cml.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"373889994","text":"import pylab\nfrom matplotlib import pyplot\nfrom PlotInfo import PlotInfo\nfrom Marker import Marker\n\nclass Label(PlotInfo):\n def __init__(self, x, y, text=None, bbox=None):\n PlotInfo.__init__(self, \"label\")\n\n self.x = x\n self.y = y\n self.text = text\n self.textX = x\n self.textY = y\n self.arrow = None\n self._marker = Marker()\n self.rotation = None\n\n if bbox: self.bbox = dict(bbox)\n else: self.bbox = None\n\n @property\n def marker(self):\n return self._marker.marker\n\n @marker.setter\n def marker(self, value):\n self._marker.marker = value\n\n @marker.getter\n def marker(self):\n return self._marker.marker\n\n def setTextOffset(self, x, y):\n self.textX = self.x + x\n self.textY = self.y + y\n\n def setTextPosition(self, x, y):\n self.textX = x\n self.textY = y\n\n def hasArrow(self, style=\"->\", color=\"black\"):\n self.arrow = dict(facecolor=color, arrowstyle=style)\n\n def draw(self, fig, axis):\n kwdict = {}\n kwdict[\"xytext\"] = (self.textX, self.textY)\n kwdict[\"xycoords\"] = \"data\"\n kwdict[\"textcoords\"] = \"data\"\n kwdict[\"arrowprops\"] = self.arrow\n kwdict[\"horizontalalignment\"] = \"center\"\n kwdict[\"rotation\"] = self.rotation\n\n # For props, see\n # http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.patches.Rectangle\n if self.bbox: kwdict[\"bbox\"] = self.bbox\n\n handles = []\n labels = []\n\n handles.append(axis.annotate(self.text, (self.x, self.y), **kwdict))\n labels.append(None)\n\n if self.marker is not None:\n handles.append(axis.scatter([self.x],[self.y],marker=self.marker,\n color=\"black\"))\n labels.append(None)\n\n return [handles, labels]\n","sub_path":"Label.py","file_name":"Label.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"428288143","text":"# encoding: utf-8\n\n\"\"\"WebCore-specific utilities.\"\"\"\n\nfrom marrow.util.url import URL\n\n\n__all__ = ['URLGenerator']\n\n\nclass URLGenerator(object):\n @property\n def _base(self):\n \"\"\"Return a 3-tuple of the application base path, current processed\n script_path, and the script_path\"\"\"\n import web.core\n r = web.core.request\n return r.environ['web.base'], r.path_url, r.environ['web.controller']\n \n def __call__(self, path=None, params=None, anchor=None, protocol=None, host=None, port=None):\n \"\"\"The default syntax for the creation of paths.\n \n Path must be a string. Params must be a dictionary and represents the\n query string arguments. Anchor must be a string representing the text\n after the hash symbol. Host must be a string. Port must be an integer.\n \n If protocol, host, or port are defined then a full URL will be\n generated, otherwise an absolute path will be generated.\n \n If the path begins with a forward slash it is absolute from the root\n of the web application mount point, otherwise it is relative to the\n current controller (not method).\n \n Query string arguments may be strings, or lists of strings. A list\n indicates an argument that appears multiple times.\n \n For example, url('/foo') will result in a url of '/app/foo' if the\n application is mounted on /app. If you are within a controller named\n 'users' attached to your appliation root, you can use url('create') to\n generate the URL needed to call the 'create' method;\n \"/app/users/create\" in this case.\n \n To switch to a secure connection without changing the URL you can call\n url(protocol='https').\n \"\"\"\n if protocol or host or port:\n return self._full(path, params, anchor, protocol, host, port)\n \n return self._partial(path, params, anchor)\n \n def complete(self, path=None, params=None, anchor=None, protocol=None, host=None, port=None):\n \"\"\"As per the default syntax, but always returns a complete URL.\"\"\"\n \n return self._full(path, params, anchor, protocol, host, port)\n \n def compose(self, *args, **kw):\n \"\"\"An alternate syntax for simpler URL generation.\n \n This accepts an unlimited number of positional arguments which will be\n composed into the path and keyword arguments will be used as query\n string arguments. If the first path element starts with a forward\n slash then the path is absolute from the root of the application mount\n point, otherwise it is relative to the current controller (not method).\n \n Query string arguments may be strings, or lists of strings. A list\n indicates an argument that appears multiple times.\n \n This syntax does not allow overriding of other URL elements (such as\n protocol and host) and thus never generates full URLs, nor does it\n allow the definition of an anchor.\n \n This is most useful if you are using a CRUD controller style. For\n example, if the user is viewing a listing generated on /app/users/\n you can use the following to good effect:\n \n * url.compose('create') - \"/app/users/create\"\n * url.compose(user.id) - \"/app/users/27\"\n * url.compose(user.id, 'modify') - \"/app/users/27/modify\"\n \"\"\"\n \n return self('/'.join(str(i) for i in args), kw)\n \n def _full(self, path, params, anchor, protocol, host, port):\n \"\"\"Prepare a complete URL.\"\"\"\n \n base, current, controller = self._base\n url = URL(current)\n \n url.path = self._partial(path, None, None)\n \n if protocol:\n url.scheme = protocol\n \n if host:\n url.host = host\n \n if port:\n url.port = port\n \n url.query = params\n url.fragment = anchor\n \n return unicode(url)\n \n def _partial(self, path, params, anchor):\n \"\"\"Prepare a resource path.\"\"\"\n \n base, current, controller = self._base\n url = URL()\n \n if not path:\n url.path = str(URL(current).path)\n else:\n url.path = base if path.startswith('/') else controller\n url.path.append(path[1:] if path.startswith('/') else path)\n \n url.query = params\n url.fragment = anchor\n \n return unicode(url)\n","sub_path":"web/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"315453547","text":"\"\"\"This is a quantum leap from the previous version. Note that the long\nlist of arguments in the definition of the initializer disappears, and\nso does the equally long block of the if statements.\n\nIt is amazing that no matter how many attributes the class uses, the\nsize of its initializer remains a constant.\n\"\"\"\n\nclass Href:\n\n target=None\n onClick=None\n onMouseOver=None\n onMouseOut=None\n\n def __init__(self,\n url,\n text,\n **kw):\n\n self.url = url\n self.text = text\n\n for key in kw:\n setattr(self, key, kw[key])\n\n def __str__(self):\n s = ['%s' % self.text)\n return ''.join(s)\n\nucsd = Href('UCSD', 'http://ucsd.edu', target='_blank')\nharvard = Href('Harvard University', 'http://harvard.edu')\nprint(ucsd); print(harvard)\nprint(vars(ucsd)); print(vars(harvard)) ","sub_path":"assignment2/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"651590614","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 24 10:58:07 2017\n\n@author: srikant\n\"\"\"\nimport json\nimport sys\nimport os\n\nimport pandas as pd\n\nimport get_github_details as ghd\nimport get_stackoverflow_details as sod\n\n\nMASTER_DIR = \"master_data\"\nMASTER_FILE = \"Applicant Master Data 2017.xlsx\"\nOUTPUT_FILE = MASTER_FILE.replace('Master', 'Github and Stackoverflow')\n\ndef read_master_data(filepath):\n '''Read Applicant Master Data,\n drop rows where either emailid or name is missing,\n return dataframe of master data.\n '''\n # read master appliant information\n try:\n master_df_raw = pd.read_excel(filepath, sheetname='Sheet1')\n except FileNotFoundError as err:\n print(\"\\nCouldnt find '{}' \\n\".format(filepath))\n sys.exit(0)\n master_df_raw.columns = master_df_raw.columns.str.lower()\n # offset for consistency in row numbers\n offset = 2\n master_df_raw.index = master_df_raw.index + offset\n # drop rows where both names or emails are available\n name_and_email_available = master_df_raw['name'].notnull() & master_df_raw['email'].notnull()\n master_df = master_df_raw[name_and_email_available]\n return master_df\n\n\ndef write_df_to_excel(df, filepath):\n '''write df to excelfile in a proper order\n '''\n # order of columns for excel output\n cols_order = [\n 'master_details',\n 'github_id_details',\n 'stackoverflow_id_details',\n 'github_overall_rating',\n 'stackoverflow_overall_rating',\n 'github_expertise_ratings',\n 'stackoverflow_expertise_ratings'\n ]\n # keep columns that are in df\n ordered_df_list = []\n for col_name in cols_order:\n try:\n ordered_df_list.append(df[[col_name]].sortlevel(axis=1))\n except (KeyError,IndexError):\n continue\n ordered_df = pd.concat(ordered_df_list, axis=1)\n # write dataframe to excel file\n ordered_df.to_excel(filepath, index_label='index')\n\n\n\ndef get_master_details(row):\n '''get a few id details from master data\n '''\n user_name = row['name']\n user_email = row['email'].split('|')[0]\n # applicant master details\n master_details_dict = {\n ('master_details','name'): user_name,\n ('master_details','email'): user_email\n }\n return master_details_dict\n\n \ndef get_github_details(g, user_name, user_email):\n '''get github details\n '''\n # search in Github for user matching the email_id\n search_string = user_email\n github_matches = ghd.find_matching_users(g, search_string)\n try:\n # get github data for the matching user\n github_details = ghd.get_github_profiles(github_matches, search_string)\n except SystemExit:\n github_details = {}\n # get the github ratings df\n github_ratings_df = github_details.get(search_string,{}).get('overall_rating', pd.DataFrame())\n # convert df to dict\n github_ratings_dict = github_ratings_df.to_dict().get('value',{})\n return github_ratings_dict\n\n\ndef get_stackoverflow_details(so, user_name, user_email):\n '''get stackoverflow details\n '''\n # use fullname as search string\n search_string = user_name\n search_kw = {'inname':search_string}\n # find matching stackoverflow users, use the first match\n stackovf_matches = sod.find_matching_users(so, search_kw)[0:1]\n try:\n # get stackoverflow details for the first user\n stackovf_details = sod.get_stackoverflow_profiles(stackovf_matches, search_kw)\n except SystemExit:\n stackovf_details = {}\n # get statckoverflow ratings df\n stackovf_ratings_df = stackovf_details.get(search_string,{}).get('ratings_df', pd.DataFrame())\n # convert df to dict\n stackovf_ratings_dict = stackovf_ratings_df.to_dict().get('value',{})\n return stackovf_ratings_dict\n\n\ndef get_github_stackorf_details(g, so, master_data_df):\n '''get github and stackoverflow details for each of the applicant in the master_data_df\n '''\n all_details_dict = {}\n master_details_dict = {}\n github_ratings_dict = {}\n stackovf_ratings_dict = {}\n ratings_dict = {}\n # for each applicant get Github, Stackoverflow and Master Data, do this for all applicants\n for i,row in master_data_df.iterrows():\n print('\\nSl.No {:3d}: [{}], [{}]'.format(i, row['name'], row['email']) )\n # applicant master details\n master_details_dict[i] = get_master_details(row)\n user_name = master_details_dict[i].get(('master_details','name'),'')\n user_email = master_details_dict[i].get(('master_details','email'),'')\n # search in Github for user matching the email_id\n github_ratings_dict[i] = get_github_details(g, user_name, user_email)\n # search in Stackoverflow for user matching the user_name\n stackovf_ratings_dict[i] = get_stackoverflow_details(so, user_name, user_email)\n # append all ratings df to applicant master details\n ratings_dict[i] = {\n **master_details_dict[i],\n **github_ratings_dict[i],\n **stackovf_ratings_dict[i]\n }\n # dictionary of combined as well as individual ratings\n all_details_dict = {\n 'ratings_dict': ratings_dict,\n 'master_details_dict': master_details_dict,\n 'github_ratings_dict': github_ratings_dict,\n 'stackovf_ratings_dict': stackovf_ratings_dict\n }\n return all_details_dict\n\n\nif __name__ == '__main__':\n # read master data from excel file\n master_data_df = read_master_data(filepath = os.path.join(MASTER_DIR, MASTER_FILE))\n # initialize github object\n g = ghd.init_github_object()\n # initialize stackoverflow object\n so = sod.init_stackoverflow_object()\n # get applicant github stackoverflow data\n sample = True\n if sample:\n data_df = master_data_df.sample(10)\n suffix = \"Sample \"\n else:\n data_df = master_data_df\n suffix = \"\"\n all_details_dict = get_github_stackorf_details(g, so, data_df)\n ratings_details = all_details_dict['ratings_dict']\n # convert dict of all applicant details to a dataframe\n applicants_df = pd.DataFrame.from_dict(ratings_details, orient='index')\n # write to excel file\n output_file = os.path.join(MASTER_DIR, suffix + OUTPUT_FILE)\n write_df_to_excel(applicants_df, output_file)\n","sub_path":"parse_applicant_masterdata.py","file_name":"parse_applicant_masterdata.py","file_ext":"py","file_size_in_byte":6359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"547793910","text":"import os.path\n\nimport tensorflow as tf\n\nfrom src.components.networks import Networks\nfrom src.components.placeholders import Placeholders\n\nfrom src.utils.utils import get_logger\n\nlogger = get_logger(\"savers\")\n\n\nclass Saver:\n def __init__(self, variable_list, save_path, init_path=None, name=\"Unnamed Graph\"):\n try:\n self.save_path = save_path\n if not os.path.isdir(self.save_path):\n os.makedirs(self.save_path)\n self.init_path = init_path\n self.name = name\n self.saver = tf.train.Saver(variable_list)\n except Exception as e:\n logger.warning(f\"Could not create Saver for {name}!\")\n\n def load(self, session):\n try:\n self.saver.restore(session, tf.train.latest_checkpoint(self.save_path))\n logger.info(f\"Successfully restored {self.name} from {tf.train.latest_checkpoint(self.save_path)}!\")\n except Exception as e:\n logger.warning(f\"Could not restore {self.name} from {self.save_path}. Maybe it doesn't exist!\")\n self.attempt_restoring_from_initialization_checkpoint(session)\n\n def attempt_restoring_from_initialization_checkpoint(self, session):\n if self.init_path:\n logger.info(f\"Trying to initialize {self.name} from {self.init_path}.\")\n try:\n self.saver.restore(session, tf.train.latest_checkpoint(self.init_path))\n logger.info(f\"Successfully initialized {self.name} from {tf.train.latest_checkpoint(self.init_path)}!\")\n except:\n logger.warning(f\"Could not initialize {self.name} from {self.init_path}. Maybe it doesn't exist!\")\n\n def save(self, session, global_step):\n try:\n self.saver.save(session, os.path.join(self.save_path, \"model.ckpt\"), global_step=global_step,\n write_meta_graph=False)\n except:\n pass\n\n\nclass Savers:\n def __init__(self, networks: Networks, placeholders: Placeholders, save_dir, init_dir=None):\n self.save_dir = save_dir\n self.init_dir = init_dir\n\n self.init_generator_savers(networks)\n self.init_discriminator_savers(networks)\n self.init_fnet_saver()\n self.init_vgg_saver()\n self.init_global_step_saver(placeholders)\n\n def init_fnet_saver(self):\n fnet_variable_list = tf.get_collection(tf.GraphKeys.MODEL_VARIABLES, scope='fnet')\n self.fnet_saver = Saver(fnet_variable_list, save_path=self.get_save_path(\"fnet\"), init_path='./fnet',\n name=\"FNet\")\n\n def init_vgg_saver(self):\n vgg_variable_list = tf.get_collection(tf.GraphKeys.MODEL_VARIABLES, scope=\"vgg_19\")\n self.vgg_saver = Saver(vgg_variable_list, save_path=self.get_save_path(\"vgg19\"), init_path=\"./vgg19\")\n\n def init_discriminator_savers(self, networks):\n self.discriminator_spatial_a_saver = Saver(networks.discriminator_spatial_a.var_list,\n save_path=self.get_save_path(networks.discriminator_spatial_a.name),\n init_path=self.get_init_path(networks.discriminator_spatial_a.name),\n name=\"Spacial Discriminator A\")\n self.discriminator_spatial_b_saver = Saver(networks.discriminator_spatial_b.var_list,\n save_path=self.get_save_path(networks.discriminator_spatial_b.name),\n init_path=self.get_init_path(networks.discriminator_spatial_b.name),\n name=\"Spacial Discriminator B\")\n self.discriminator_temporal_saver = Saver(networks.discriminator_temporal.var_list,\n save_path=self.get_save_path(networks.discriminator_temporal.name),\n init_path=self.get_init_path(networks.discriminator_temporal.name),\n name=\"Temporal Discriminator\")\n\n def init_generator_savers(self, networks):\n self.generator_ab_saver = Saver(networks.generator_ab.var_list,\n save_path=self.get_save_path(networks.generator_ab.name),\n init_path=self.get_init_path(networks.generator_ab.name), name=\"Generator AB\")\n self.generator_ba_saver = Saver(networks.generator_ba.var_list,\n save_path=self.get_save_path(networks.generator_ba.name),\n init_path=self.get_init_path(networks.generator_ba.name), name=\"Generator BA\")\n\n def init_global_step_saver(self, placeholders):\n self.global_step_saver = Saver([placeholders.global_step], save_path=self.get_save_path(\"global_step\"),\n name=\"Global Step\")\n\n def save_all(self, session, global_step=None):\n for saver in self.get_all_savers():\n saver.save(session, global_step)\n\n def load_all(self, session):\n for saver in self.get_all_savers():\n saver.load(session)\n\n def get_all_savers(self):\n return [self.fnet_saver, self.discriminator_temporal_saver, self.discriminator_spatial_b_saver,\n self.discriminator_spatial_a_saver, self.generator_ab_saver, self.generator_ba_saver,\n self.global_step_saver, self.vgg_saver]\n\n def get_init_path(self, name):\n if name is None or self.init_dir is None:\n return None\n else:\n return os.path.join(self.init_dir, name)\n\n def get_save_path(self, name):\n if name is None or self.save_dir is None:\n return None\n else:\n return os.path.join(self.save_dir, name)\n","sub_path":"src/components/savers.py","file_name":"savers.py","file_ext":"py","file_size_in_byte":5864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"118280694","text":"import unittest\nfrom binascii import unhexlify\n\nfrom pycose.cosemessage import CoseMessage\nfrom pycose.signmessage import SignMessage\n\n\nclass CoseSignTests(unittest.TestCase):\n \"\"\"tests for cose_mac message types\"\"\"\n\n signature_struct_params = \\\n {\n 'hash256/64_p': ['alg', 'HS256/64', 'PROTECTED', b'\\xa1\\x01\\x04'],\n 'hash256_p': ['alg', 'HS256', 'PROTECTED', b'\\xa1\\x01\\x05'],\n 'hash384_p': ['alg', 'HS384', 'PROTECTED', b'\\xa1\\x01\\x06'],\n 'hash512_p': ['alg', 'HS512', 'PROTECTED', b'\\xa1\\x01\\x07'],\n 'hash256/64_u': ['alg', 'HS256/64', 'UNPROTECTED', {1: 4}],\n 'hash256_u': ['alg', 'HS256', 'UNPROTECTED', {1: 5}],\n 'hash384_u': ['alg', 'HS384', 'UNPROTECTED', {1: 6}],\n 'hash512_u': ['alg', 'HS512', 'UNPROTECTED', {1: 7}],\n 'aes128/64_p': ['alg', 'AES-MAC128/64', 'PROTECTED', b'\\xa1\\x01\\x0e'],\n 'aes256/64_p': ['alg', 'AES-MAC256/64', 'PROTECTED', b'\\xa1\\x01\\x0f'],\n 'aes128/128_p': ['alg', 'AES-MAC128/128', 'PROTECTED', b'\\xa1\\x01\\x18\\x19'],\n 'aes256/128_p': ['alg', 'AES-MAC256/128', 'PROTECTED', b'\\xa1\\x01\\x18\\x1a'],\n 'aes128/64_u': ['alg', 'AES-MAC128/64', 'UNPROTECTED', {1: 14}],\n 'aes256/64_u': ['alg', 'AES-MAC256/64', 'UNPROTECTED', {1: 15}],\n 'aes128/128_u': ['alg', 'AES-MAC128/128', 'UNPROTECTED', {1: 25}],\n 'aes256/128_u': ['alg', 'AES-MAC256/128', 'UNPROTECTED', {1: 26}],\n 'kid_int_p': ['kid', 31868, 'PROTECTED', b'\\xa1\\x04\\x19||'],\n 'kid_string_p': ['kid', 'sleutel_id', 'PROTECTED', b'\\xa1\\x04Jsleutel_id'],\n 'kid_int_u': ['kid', 31868, 'UNPROTECTED', {4: 31868}],\n 'kid_string_u': ['kid', 'sleutel_id', 'UNPROTECTED', {4: b'sleutel_id'}],\n 'iv_p': ['iv', unhexlify(\"a8c984a984b498489d489e68498f6847\"), 'PROTECTED',\n b'\\xa1\\x05P\\xa8\\xc9\\x84\\xa9\\x84\\xb4\\x98H\\x9dH\\x9ehI\\x8fhG'],\n 'iv_u': ['iv', unhexlify(\"a8c984a984b498489d489e68498f6847\"), 'UNPROTECTED',\n {5: b'\\xa8\\xc9\\x84\\xa9\\x84\\xb4\\x98H\\x9dH\\x9ehI\\x8fhG'}]\n }\n\n signature_struct_find_params = \\\n {\n 'alg_in_p': ['alg', 'HS256', 'PROTECTED', \"HS256\"],\n 'alg_in_u': ['alg', 'HS256', 'UNPROTECTED', \"HS256\"],\n 'kid_in_p': ['kid', 31868, 'PROTECTED', 31868],\n 'kid_in_u': ['kid', 31868, 'PROTECTED', 31868],\n 'kid_str_in_p': ['kid', 'sleutel_id', 'PROTECTED', b'sleutel_id'],\n 'kid_str_in_u': ['kid', 'sleutel_id', 'UNPROTECTED', b'sleutel_id'],\n 'iv_in_p': ['iv', unhexlify(\"a8c984a984b498489d489e68498f6847\"), 'PROTECTED',\n unhexlify(\"a8c984a984b498489d489e68498f6847\")],\n 'iv_in_u': ['iv', unhexlify(\"a8c984a984b498489d489e68498f6847\"), 'UNPROTECTED',\n unhexlify(\"a8c984a984b498489d489e68498f6847\")]\n }\n\n cbor_1 = \"D8628440A054546869732069732074686520636F6E74656E742E818343A10126A1044231315840CBB8DAD9BEAFB890E1A4141\" \\\n \"24D8BFBC26BEDF2A94FCB5A882432BFF6D63E15F574EEB2AB51D83FA2CBF62672EBF4C7D993B0F4C2447647D831BA57CCA86B930A\"\n key_1 = \"V8kgd2ZBRuh2dgyVINBUqpPDr7BOMGcF22CQMIUHtNM\"\n external = unhexlify(\"11aa22bb33cc44dd55006699\")\n\n test_cose_sign_map = \\\n {\n 'msg1': [{}, {}, external, 'This is the content.', {\"alg\": \"ES256\"}, {\"kid\": \"11\"},\n key_1, unhexlify(cbor_1)],\n }\n\n cbor_2 = \"D8628440A054546869732069732074686520636F6E74656E742E818343A10126A1044231315840E2AEAFD40D69D19DFE6E5207\" \\\n \"7C5D7FF4E408282CBEFB5D06CBF414AF2E19D982AC45AC98B8544C908B4507DE1E90B717C3D34816FE926A2B98F53AFD2FA0F30A\"\n key_2 = \"V8kgd2ZBRuh2dgyVINBUqpPDr7BOMGcF22CQMIUHtNM\"\n\n test_cose_sign2_map = \\\n {\n 'msg1': [{}, {}, '', 'This is the content.', {\"alg\": \"ES256\"}, {\"kid\": \"11\"},\n key_2, unhexlify(cbor_2)],\n }\n\n def test_signers_params(self):\n for name_test, (a, b, c, d) in self.signature_struct_params.items():\n with self.subTest(name=name_test):\n sign_msg = SignMessage()\n sign_msg.add_to_signers(1, a, b, c)\n if c == 'PROTECTED':\n self.assertEqual(sign_msg.signers[0][0], d, name_test)\n if c == 'UNPROTECTED':\n self.assertEqual(sign_msg.signers[0][1], d, name_test)\n\n def test_signers_find(self):\n for name_test, (a, b, c, d) in self.signature_struct_find_params.items():\n with self.subTest(name=name_test):\n sign_msg = SignMessage()\n sign_msg.add_to_signers(1, a, b, c)\n self.assertEqual(sign_msg.find_in_signers(a), d, name_test)\n\n def test_cose_sign_creation(self):\n for name_test, (a, b, x, c, d, e, f, g) in self.test_cose_sign_map.items():\n with self.subTest(name=name_test):\n sign_msg = SignMessage()\n for k1 in a:\n sign_msg.add_to_headers(k1, a[k1], 'PROTECTED')\n for k2 in b:\n sign_msg.add_to_headers(k2, b[k2], 'UNPROTECTED')\n sign_msg.external_aad = x\n sign_msg.payload = c\n for k3 in d:\n sign_msg.add_to_signers(1, k3, d[k3], 'PROTECTED')\n for k4 in e:\n sign_msg.add_to_signers(1, k4, e[k4], 'UNPROTECTED')\n sign_msg.key = f\n try:\n alg = sign_msg.find_in_headers('alg')\n except KeyError as err:\n alg = sign_msg.find_in_signers('alg')\n\n sign_msg.add_signature_to_signers(1, sign_msg.compute_signature(alg))\n\n self.assertEqual(sign_msg.encode(), g)\n\n def test_received_cose_msg(self):\n for name_test, (a, b, x, c, d, e, f, g) in self.test_cose_sign2_map.items():\n with self.subTest(name=name_test):\n cose_msg = CoseMessage.decode(g)\n cose_msg.key = f\n try:\n alg = cose_msg.find_in_headers('alg')\n except KeyError as err:\n alg = cose_msg.find_in_signers('alg')\n\n self.assertTrue(cose_msg.verify_signature(alg, signer=1))\n\n\nif __name__ == \"main\":\n unittest.main()\n","sub_path":"tests/test_signmessage.py","file_name":"test_signmessage.py","file_ext":"py","file_size_in_byte":6372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"178987307","text":"import pygame\nimport sys\nfrom pygame.locals import *\nfrom math import *\nfrom queue import Queue\nfrom queue import PriorityQueue\n\n\n__version__ = '0'\n\n\nNAVY_BLUE = (0, 0, 128)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nLIME = (0, 255, 0)\n\n\nclass State:\n def Enter(agent):\n pass\n \n def Execute(agent):\n pass\n \n def Exit(agent):\n pass\n\n\nclass IdleState(State):\n def Enter(agent):\n print(agent, 'changed state to idle')\n \n def Execute(agent):\n if agent.war_count > 0:\n agent.change_state(WarState)\n elif agent.can_colonise:\n agent.change_state(ColonisationState)\n elif agent.mil_power > agent.enemy.mil_power:\n agent.declare_war(agent.enemy)\n agent.change_state(WarState)\n\n \n\nclass ColonisationState(State):\n def Enter(agent):\n print(agent, 'changed state to colonisation')\n\n def Execute(agent):\n if agent.war_count > 0:\n agent.change_state(WarState)\n elif not agent.can_colonise:\n agent.change_state(IdleState)\n else:\n agent.colonise_best()\n\nclass WarState(State):\n def Enter(agent):\n print(agent, 'changed state to war')\n\n def Execute(agent):\n if agent.in_war:\n agent.attack_best()\n else:\n self.change_state(IdleState)\n\n\nclass BaseEntity:\n def change_state(self, newState):\n self.state.Exit(self)\n self.state = newState\n self.state.Enter(self)\n\nclass StateEntity(BaseEntity):\n def __init__(self, color, name, world):\n self.color = color\n self.state = IdleState\n self.name = name\n self.can_colonise = False\n self.colonisation_target = -1\n self.cells = set()\n self.world = world\n self.mil_power = 20\n self.dip_relations = set()\n self.war_count = 0\n \n def update(self):\n self.update_targets()\n self.state.Execute(self)\n print(self.war_target)\n\n def update_targets(self):\n self.colonisation_target = -1\n curr = 0\n self.war_target = -1\n curr_war = 0\n self.can_colonise = False\n for i in self.cells:\n for j in [[-1, 0], [1, 0], [0, 1], [0, -1]]:\n if self.world.valid_cell(i[0] + j[0], i[1] + j[1]) and self.world.get_cell(i[0] + j[0], i[1] + j[1]).terrain == '0' and self.world.get_cell(i[0] + j[0], i[1] + j[1]).owner != self:\n current_cell = self.world.get_cell(i[0] + j[0], i[1] + j[1])\n if current_cell.owner == 0:\n if self.colonisation_target == -1:\n self.colonisation_target = [i[0] + j[0], i[1] + j[1]]\n curr = current_cell.get_weight(self)\n self.can_colonise = True\n elif current_cell.get_weight(self) > curr:\n self.colonisation_target = [i[0] + j[0], i[1] + j[1]]\n curr = current_cell.get_weight(self)\n if self.in_war_with(current_cell.owner) and self.mil_power > current_cell.owner.mil_power:\n print('ok')\n if self.war_target == -1:\n self.war_target = [i[0] + j[0], i[1] + j[1]]\n curr_war = current_cell.get_weight(self)\n self.can_attack = True\n elif current_cell.get_weight(self) > curr_war:\n self.war_target = [i[0] + j[0], i[1] + j[1]]\n curr_war = current_cell.get_weight(self)\n \n \n def colonise_best(self):\n x = self.colonisation_target[0]\n y = self.colonisation_target[1]\n self.world.get_cell(x, y).set_owner(self)\n self.add_cell(x, y)\n #print('ok')\n\n def attack_best(self):\n if self.war_target == -1:\n return\n else:\n x = self.war_target[0]\n y = self.war_target[1]\n self.world.get_cell(x, y).set_owner(self)\n self.add_cell(x, y)\n self.mil_power -= 1\n print(self.name, 'seizes', x, y)\n\n def add_cell(self, x, y):\n self.cells.add(tuple([x, y]))\n #print(x, y, 'added to', self.name)\n self.world.get_cell(x, y).set_owner(self)\n\n def del_cell(self, x, y):\n self.cells.discard(tuple([x, y]))\n\n def change_wars_count(self, t):\n self.war_count += t\n if self.war_count == 0:\n self.in_war = False\n else:\n self.in_war = True\n\n def in_war_with(self, actor):\n for rel in self.dip_relations:\n if (rel.first == actor or rel.second == actor) and rel.state == 1:\n return True\n return False\n\n def add_relation(self, rel):\n self.dip_relations.add(rel)\n\n\n#class IdleMoving(State):\n# def Execute(agent):\n# if agent.order != []:\n# agent.change_state(MoveToTargetMoving)\n#\n#class MoveToTargetMoving(State):\n# def Execute(agent):\n# if route.len()\n\n\nclass MovingEntity(BaseEntity):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.world = world\n self.state = IdleMoving\n\n def set_owner(self, actor):\n self.owner = actor\n\n def update(self):\n self.state.Execute(self)\n\n\nclass DipRelation:\n def __init__(self, x, y):\n self.first = x\n self.second = y\n self.state = 0 #peace\n\n def declare_war(self):\n print('war started')\n self.state = 1 #war\n self.first.change_wars_count(1)\n self.second.change_wars_count(1)\n\n def declare_peace(self):\n self.state = 0\n self.first.change_wars_count(-1)\n self.second.change_wars_count(-1)\n\n\nclass Cell:\n def __init__(self, x, y, terrain, world):\n self.x = x\n self.y = y\n self.color = BLACK\n self.owner = 0\n self.world = world\n self.terrain = terrain\n\n def set_owner(self, actor):\n if self.owner != actor and self.owner != 0:\n self.owner.del_cell(self.x, self.y)\n self.owner = actor\n self.color = actor.color\n\n def get_weight(self, actor):\n x, y = self.x, self.y\n res = 0\n if self.owner != 0:\n return 0\n for dx in [-1, 0, 1]:\n for dy in [-1, 0, 1]:\n if self.world.valid_cell(x + dx, y + dy) and self.world.get_cell(x + dx, y + dy).owner == actor:\n res += 1\n return res\n\n def get_color(self):\n return self.color\n\n def update(self):\n pass\n \n\n\nclass World:\n def __init__(self, x, y):\n self.name = 'world'\n self.x, self.y = x, y\n self.field = [[Cell(i, j, 0, self) for i in range(x)] for j in range(y)]\n self.objects = set()\n self.marked_for_delete = set()\n\n def get_cell(self, x, y):\n return self.field[x][y]\n\n def valid_cell(self, x, y):\n return (self.x > x >= 0) and (self.y > y >= 0)\n\n def read(self, input_file):\n for i in range(int(input_file.readline().split()[0])):\n tmp = list(input_file.readline().rstrip())\n for j in range(len(tmp)):\n self.field[i][j] = Cell(i, j, tmp[j], self)\n\n def update(self):\n for i in self.objects:\n i.update()\n for i in range(self.x):\n for j in range(self.y):\n self.field[i][j].update()\n self.discard_deleted()\n\n def add_object(self, new_obj):\n self.objects.add(new_obj)\n\n def delete_object(self, item):\n self.marked_for_delete.add(item)\n\n def discard_deleted(self):\n for i in self.marked_for_delete:\n self.objects.discard(i)\n self.marked_for_delete.clear()\n\n def draw(self):\n surface = pygame.PixelArray(DISPLAYSURF)\n for i in range(self.x):\n for j in range(self.y):\n color = self.field[i][j].get_color()\n try:\n surface[i][j] = color\n except:\n print(color)\n del surface\n\n\npygame.init()\npygame.display.set_caption('gsg')\nWRLD = World(50, 50)\nWRLD.read(open('newmap.txt'))\n\nprint('world init finished')\n\np1 = StateEntity(RED, 'red', WRLD)\np1.add_cell(1, 1)\np2 = StateEntity(LIME, 'lime', WRLD)\np2.add_cell(49, 49)\np3 = StateEntity(NAVY_BLUE, 'blue', WRLD)\np3.add_cell(25, 25)\n\nrel1 = DipRelation(p1, p2)\np1.add_relation(rel1)\np2.add_relation(rel1)\np1.enemy = p2\np2.enemy = p1\np3.enemy = p1\np3.mil_power = 0\np1.mil_power = 30\n\nprint('players init finished')\n\nDISPLAYSURF = pygame.display.set_mode((500, 500), 0, 32)\nDISPLAYSURF.fill((255, 255, 255))\n\nwhile True:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n WRLD.update()\n WRLD.draw()\n p1.update()\n p2.update()\n p3.update()\n pygame.display.update()\n","sub_path":"conquest.py","file_name":"conquest.py","file_ext":"py","file_size_in_byte":9027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"604477920","text":"# 基于select 的IO多路复用监听服务器\n\nfrom socket import *\nimport select\n\ns = socket()\ns.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\ns.bind(('127.0.0.1', 8888))\ns.listen(5)\n\nrlist = [s]\nwlist = []\nxlist = [s]\n\nwhile True:\n #监听三个列表中的IO事件\n rs, ws, es = select.select(rlist, wlist, xlist)\n for r in rs:\n if r is s:\n c, addr = r.accept()\n print(\"connect from\", addr)\n rlist.append(c) #将新的IO事件加入到监控列表\n xlist.append(c)\n else:\n data = r.recv(1024).decode()\n if not data:\n print(\"客户端退出\")\n rlist.remove(r)\n xlist.remove(r)\n r.close()\n else:\n wlist.append(r)\n# print(\"收到客户端消息:\",data)\n\n\n for w in ws:\n k.send('h'.encode())\n wlist.remove(w)\n for e in es:\n if e is s:\n s.close()\n sys.exit(0)\n else:\n e.close()\n rlist.remove(e)\n xlist.remove(e)\ns.close()\n","sub_path":"test/select_test.py","file_name":"select_test.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"188861854","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 22 16:28:37 2019\r\n\r\n@author: zona8001\r\n\"\"\"\r\n\r\nimport os\r\nimport shutil\r\nimport pandas as pd\r\nimport time\r\nimport numpy as np\r\nimport pdb\r\n\r\npd.set_option('display.width', None) # 设置字符显示宽度\r\npd.set_option('display.max_rows', None) # 设置显示最大行\r\npd.set_option('display.max_columns', None)\r\ndef folder_file(item_name):\r\n\t'''\r\n\tidentify file name, suffix for a string.\r\n\tif string don't have suffix, then identify as folder\r\n\treturn (file_name, file_suffix, file_type) for later string split. \r\n\t'''\r\n\t#item_name = '__MACOSX'\r\n\tfile_name,file_suffix = os.path.splitext(item_name)\r\n\tif file_suffix=='':\r\n\t\tfile_type='folder'\r\n\telse:\r\n\t\tfile_type='file'\r\n\treturn file_name,file_suffix,file_type\r\n\r\ndef update_log(mess_folder):\r\n\tfile_list = pd.DataFrame({'name':os.listdir(mess_folder)})\r\n\tfile_list['file_key'] = file_list['name'].apply(lambda x: folder_file(x))\r\n\tfile_list['file_name'] = file_list['file_key'].apply(lambda x: x[0])\r\n\tfile_list['file_suffix'] = file_list['file_key'].apply(lambda x: x[1])\r\n\tfile_list['file_type'] = file_list['file_key'].apply(lambda x: x[2])\r\n\tfile_list['file_created'] = file_list['name'].apply(lambda x:time.strftime(\"%Y-%m-%d %H:%M:%S\",time.gmtime(os.path.getctime(os.path.join(mess_folder,x)))))\r\n\tfile_list['file_modified'] = file_list['name'].apply(lambda x:time.strftime(\"%Y-%m-%d %H:%M:%S\",time.gmtime(os.path.getmtime(os.path.join(mess_folder,x)))))\r\n\tfile_list.drop(['file_key'],axis=1,inplace=True)\r\n\tfile_list['file_content'] = ''\r\n\tfile_list['name_history'] = ''\r\n\tfile_list['rename_request'] = ''\r\n\tfile_list['rename_str'] = ''\r\n\tfile_list['move_request'] =''\r\n\tfile_list['move_str'] = ''\r\n\tfile_list['search_label'] = ''\r\n\told_list = pd.read_excel(os.path.join(mess_folder+'folder_file_log.xlsx'),index_col=0)\r\n\tupdated_list = old_list.append(file_list)\r\n\tupdated_list = updated_list.drop_duplicates(subset=['name','file_created'])\r\n\t#droped_list = old_list[~old_list.name.isin(file_list.name)]\r\n\t#new_list = file_list[~file_list.name.isin(old_list.name)]\r\n\treturn updated_list\r\n\r\n\r\ndef generate_log(mess_folder):\r\n\t'''\r\n\tif new folder, then generate log file. \r\n\tif not, update log file. (will add in next version).\r\n\t'''\r\n\tif os.path.exists(os.path.join(mess_folder,'folder_file_log.xlsx')):\t\r\n\t\tprint('Log file already existed in %s'%mess_folder)\r\n\t\tupdated_list = update_log(mess_folder)\r\n\t\tupdated_list.to_excel(os.path.join(mess_folder,'folder_file_log.xlsx'))\r\n\t\tprint('Update and Fetch lastest log')\r\n\telse:\r\n\t\tfile_list = pd.DataFrame({'name':os.listdir(mess_folder)})\r\n\t\tfile_list['file_key'] = file_list['name'].apply(lambda x: folder_file(x))\r\n\t\tfile_list['file_name'] = file_list['file_key'].apply(lambda x: x[0])\r\n\t\tfile_list['file_suffix'] = file_list['file_key'].apply(lambda x: x[1])\r\n\t\tfile_list['file_type'] = file_list['file_key'].apply(lambda x: x[2])\r\n\t\tfile_list['file_created'] = file_list['name'].apply(lambda x:time.strftime(\"%Y-%m-%d %H:%M:%S\",time.gmtime(os.path.getctime(os.path.join(mess_folder,x)))))\r\n\t\tfile_list['file_modified'] = file_list['name'].apply(lambda x:time.strftime(\"%Y-%m-%d %H:%M:%S\",time.gmtime(os.path.getmtime(os.path.join(mess_folder,x)))))\r\n\t\tfile_list.drop(['file_key'],axis=1,inplace=True)\r\n\t\tfile_list['file_content'] = ''\r\n\t\tfile_list['name_history'] = ''\r\n\t\tfile_list['rename_request'] = ''\r\n\t\tfile_list['rename_str'] = ''\r\n\t\tfile_list['move_request'] =''\r\n\t\tfile_list['move_str'] = ''\r\n\t\tfile_list['search_label'] = ''\r\n\t\tfile_list.to_excel(os.path.join(mess_folder,'folder_file_log.xlsx'))\r\n\t\tprint('New log file has been generated')\r\n\r\ndef rename_process(rename_items):\r\n\t#rename_items = file_list.loc[rename_logic]\r\n\trename_items['old_name'] = rename_items['name']\r\n\trename_items['name'] = rename_items['rename_str']+rename_items['file_suffix']\r\n\tif isinstance(rename_items,pd.DataFrame):\r\n\t\tfor ii in rename_items.index:\r\n\t\t\t#pdb.set_trace()\r\n\t\t\t\tos.rename(os.path.join(mess_folder,rename_items.loc[ii,'old_name']),os.path.join(mess_folder,rename_items.loc[ii,'name']))\r\n\telif isinstance(rename_items,pd.Series):\r\n\t\tos.rename(os.path.join(mess_folder,rename_items['old_name']),os.path.join(mess_folder,rename_items['name']))\r\n\t#rename_items.drop(['old_name'],axis=1,inplace=True)\r\n\r\ndef move_process(move_items):\r\n\t#move_items = file_list.loc[move_logic]\r\n\t#pdb.set_trace()\r\n\tif isinstance(move_items,pd.DataFrame):\r\n\t\tfor ii in move_items.index:\r\n\t\t\tshutil.move(os.path.join(mess_folder,move_items.loc[ii,'name']),os.path.join(move_items.loc[ii,'move_str'],move_items.loc[ii,'name'])) \r\n\telif isinstance(move_items,pd.Series):\r\n\t\tshutil.move(os.path.join(mess_folder,move_items['name']),os.path.join(move_items['move_str'],move_items['name'])) \r\n\r\n\r\ndef rename_move_batch(mess_folder):\r\n\tfile_list = pd.read_excel(os.path.join(mess_folder+'folder_file_log.xlsx'),index_col=0)\r\n\trename_logic = file_list['rename_request']==1\r\n\tprint(file_list.loc[rename_logic,['file_name','rename_str','file_content']])\r\n\tprint('======'*6)\r\n\tprint('Rename request all correct?')\r\n\trename_confirm = input(\"TYPE NUMBER TO CONFIRM:\\n 0: I need revise rename request and stop whole process \\n 1: I need revise rename request, but can go for move request \\n 2: all correct \\n Here(ONLY 0 OR 1 OR 2):\")\r\n\tif rename_confirm =='0':\r\n\t\tos._exit(0)\r\n\telif rename_confirm == '1':\r\n\t\tpass\r\n\telif rename_confirm == '2':\r\n\t\tfile_list.loc[rename_logic].apply(rename_process,axis=1)\r\n\t\tfile_list.loc[rename_logic,'name_history'] = file_list.loc[rename_logic,'file_name']\r\n\t\tfile_list.loc[rename_logic,'file_name'] = file_list.loc[rename_logic,'rename_str']\r\n\t\tfile_list.loc[rename_logic,'name'] = file_list.loc[rename_logic,'file_name']+file_list.loc[rename_logic,'file_suffix']\r\n\t\tfile_list.loc[rename_logic,'rename_request'] = np.nan\r\n\tmove_logic = file_list['move_request']==1\r\n\tprint(file_list.loc[move_logic,['move_str','file_name','file_content']])\r\n\tprint('======'*6)\r\n\tprint('Move request all correct?')\r\n\tmove_confirm = input(\"TYPE NUMBER TO CONFIRM:\\n 0: I need revise move request and stop whole process \\n 1: all correct \\n Here(ONLY 0 OR 1):\")\r\n\tif move_confirm =='0':\r\n\t\tos._exit(0)\r\n\telif move_confirm == '1':\r\n\t\tfile_list.loc[move_logic].apply(move_process,axis=1)\r\n\t\tfile_list.drop(list(file_list.loc[move_logic].index),inplace = True)\r\n\tfile_list.to_excel(os.path.join(mess_folder,'folder_file_log.xlsx'))\r\n\r\nif __name__ == '__main__':\r\n\tmess_folder = 'C:/Users/zona8001/Downloads/'\r\n\tgenerate_log(mess_folder)\r\n\t\r\n\tstep1_confirm = input(\"TYPE NUMBER TO CONFIRM:\\n 0: stop process \\n 1: update log file \\n Here(ONLY 0 OR 1):\")\r\n\tif step1_confirm == '0':\r\n\t\tos._exit(0)\r\n\telif step1_confirm == '1':\r\n\t\tupdate_log(mess_folder)\r\n\t\t\r\n\tstep2_confirm = input(\"TYPE NUMBER TO CONFIRM:\\n 0: stop process \\n 1: go to rename & move \\n Here(ONLY 0 OR 1):\")\r\n\tif step2_confirm == '0':\r\n\t\tos._exit(0)\r\n\telif step2_confirm == '1':\r\n\t\trename_move_batch(mess_folder)","sub_path":"folder_organize_tool.py","file_name":"folder_organize_tool.py","file_ext":"py","file_size_in_byte":6920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"90265684","text":"from django.template.loader import get_template\nfrom django.template import Context\nfrom django.http import HttpResponse\nfrom django.http import Http404\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.contrib.auth import logout\nfrom django.conf.urls import patterns, include, url\nfrom endless_pagination.decorators import page_template\nimport shutil\nimport os.path\nimport re\nfrom django.db.models import Q\n\n\nfrom egrin2.models import *\n\ndef index(request):\n species = Species.objects.count()\n networks = Network.objects.count()\n corems = Corem.objects.count()\n genes = Gene.objects.count()\n conditions = Condition.objects.count()\n gres = Gre.objects.count()\n biclusters = Bicluster.objects.count()\n tfs = greTF.objects.count()\n \n return render_to_response('index.html', locals())\n\ndef about(request):\n return render_to_response('about.html', locals())\n\ndef contact(request):\n return render_to_response('contact.html', locals())\n\ndef browse(request):\n return render_to_response('browse.html', locals())\n\ndef downloads(request):\n s = Species.objects.all()\n return render_to_response('downloads.html', locals())\n\ndef search(request):\n return render_to_response('search.html', locals())\n\ndef search_results(request):\n\n def normalize_query(query_string,\n findterms=re.compile(r'\"([^\"]+)\"|(\\S+)').findall,\n normspace=re.compile(r'\\s{2,}').sub):\n ''' Splits the query string in invidual keywords, getting rid of unecessary spaces\n and grouping quoted words together.\n Example:\n \n >>> normalize_query(' some random words \"with quotes \" and spaces')\n ['some', 'random', 'words', 'with quotes', 'and', 'spaces']\n \n '''\n return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)] \n \n def get_query(query_string, search_fields):\n ''' Returns a query, that is a combination of Q objects. That combination\n aims to search keywords within a model by testing the given search fields.\n \n '''\n query = None # Query to search for every search term \n terms = normalize_query(query_string)\n for term in terms:\n or_query = None # Query to search for a given term in each field\n for field_name in search_fields:\n q = Q(**{\"%s__icontains\" % field_name: term})\n if or_query is None:\n or_query = q\n else:\n or_query = or_query | q\n if query is None:\n query = or_query\n else:\n query = query & or_query\n return query\n query_string = ''\n found_entries = None\n if ('q' in request.GET) and request.GET['q'].strip():\n query_string = request.GET['q']\n \n entry_query = get_query(query_string, ['title', 'body',])\n \n found_entries = Entry.objects.filter(entry_query).order_by('-pub_date')\n\n return render_to_response('search_results.html',\n { 'query_string': query_string, 'found_entries': found_entries },\n context_instance=RequestContext(request))\n\ndef sitemap(request):\n return render_to_response('sitemap.html', locals())\n\ndef species(request,species=None):\n # Return info about the organism\n if species:\n out = {}\n s = Species.objects.get(ncbi_taxonomy_id=species)\n n = Network.objects.get(species__name=s.name)\n g = Gene.objects.filter(species__name=s.name).count()\n cond = Condition.objects.filter(network__name=n.name).count()\n corems = Corem.objects.filter(network__name=n.name).count()\n gres = Gre.objects.filter(network__name=n.name).count()\n out[s.short_name] = {\"species\":s,\"network\":n,\"genes\":g,\"conditions\":cond,\"corems\":corems,\"gres\":gres}\n else:\n species = Species.objects.all()\n out = {}\n for i in species:\n s = i\n n = Network.objects.get(species__name=s.name)\n g = Gene.objects.filter(species__name=s.name).count()\n cond = Condition.objects.filter(network__name=n.name).count()\n corems = Corem.objects.filter(network__name=n.name).count()\n gres = Gre.objects.filter(network__name=n.name).count()\n out[s.short_name] = {\"species\":s,\"network\":n,\"genes\":g,\"conditions\":cond,\"corems\":corems,\"gres\":gres}\n return render_to_response('species.html', locals())\n\ndef genes(request, species=None):\n # Return info about the genes\n class GeneInfo:\n def __init__(self,species):\n self.species = Species.objects.get(ncbi_taxonomy_id=species)\n self.genes = Gene.objects.filter(species__ncbi_taxonomy_id=species)\n if species:\n out = []\n out.append(GeneInfo(species))\n else:\n species = [i.ncbi_taxonomy_id for i in Species.objects.all()]\n out = []\n for i in species:\n out.append(GeneInfo(i))\n return render_to_response('genes.html', locals())\n\ndef gene_detail(request, species=None, gene=None):\n # Return info about gene\n class greObject:\n def __init__(self,species,gre):\n self.species = Species.objects.get(ncbi_taxonomy_id=species)\n self.gre_id = gre.gre_id\n self.gene_pval = GreGenePval.objects.get(gene=g,gre_id=gre).p_val\n self.pssm = gre.pssm.matrix()\n g = Gene.objects.get(sys_name = gene)\n s = Species.objects.get(ncbi_taxonomy_id=species)\n corems = Corem.objects.filter(genes__sys_name = g.sys_name)\n conds = Condition.objects.filter(genes__sys_name = g.sys_name)\n conds_pval = GeneConditionPval.objects.filter(gene__sys_name = g.sys_name, \n cond_id__in = conds)\n # add cond name to conds_pval\n conds_pval_dict = {}\n for i in conds_pval:\n d = {\"cond_id\":i.cond_id.cond_id,\"cond_name\":Condition.objects.get(cond_id = i.cond_id.cond_id).cond_name,\"p_val\":i.p_val}\n conds_pval_dict[i] = d\n gres = Gre.objects.filter(genes=g)\n gre_obj = []\n for i in gres:\n gre_obj.append(greObject(species,i))\n biclusters = Bicluster.objects.filter(genes__sys_name = g.sys_name)\n return render_to_response('gene_detail.html', locals())\n\ndef corems(request, species=None):\n # Return info about corems\n # Return info about the genes\n class CoremInfo:\n def __init__(self,species):\n self.species = Species.objects.get(ncbi_taxonomy_id=species)\n self.network = Network.objects.filter(species__ncbi_taxonomy_id=species)\n self.corems = Corem.objects.filter(network__in=self.network)\n if species:\n out = []\n out.append(CoremInfo(species))\n else:\n species = [i.ncbi_taxonomy_id for i in Species.objects.all()]\n out = []\n for i in species:\n out.append(CoremInfo(i))\n return render_to_response('corems.html', locals())\n\ndef corem_detail(request, species=None, corem=None):\n # Return info about corem\n class greObject:\n def __init__(self,species,gre):\n self.species = Species.objects.get(ncbi_taxonomy_id=species)\n self.gre_id = gre.gre_id\n self.corem_pval = GreCoremPval.objects.get(corem=corem,gre_id=gre).p_val\n self.pssm = gre.pssm.matrix()\n # just to be sure\n s = Species.objects.get(ncbi_taxonomy_id=species)\n network = Network.objects.filter(species=s)\n corem = Corem.objects.get(corem_id = corem,network__species__ncbi_taxonomy_id=species)\n genes = Gene.objects.filter(corems=corem,species=s)\n conds = Condition.objects.filter(corems=corem)\n conds_pval = CoremConditionPval.objects.filter(corem=corem, \n cond_id__in = conds)\n conds_pval_dict = {}\n for i in conds_pval:\n d = {\"cond_id\":i.cond_id.cond_id,\"cond_name\":Condition.objects.get(cond_id = i.cond_id.cond_id).cond_name,\"p_val\":i.p_val}\n conds_pval_dict[i] = d\n gres = Gre.objects.filter(corems=corem)\n gre_obj = []\n for i in gres:\n gre_obj.append(greObject(species,i))\n biclusters = Bicluster.objects.filter(corems=corem,network__in=network)\n return render_to_response('corem_detail.html', locals())\n\ndef conditions(request, species=None):\n # Return info about conditions\n class ConditionInfo:\n def __init__(self,species):\n self.species = Species.objects.get(ncbi_taxonomy_id=species)\n self.network = Network.objects.filter(species__ncbi_taxonomy_id=species)\n self.conds = Condition.objects.filter(network__in=self.network)\n if species:\n out = []\n out.append(ConditionInfo(species))\n else:\n species = [i.ncbi_taxonomy_id for i in Species.objects.all()]\n out = []\n for i in species:\n out.append(ConditionInfo(i))\n return render_to_response('conditions.html', locals())\n\ndef condition_detail(request, species=None, condition=None):\n # Return info about conditions\n # just to be sure\n s = Species.objects.get(ncbi_taxonomy_id=species)\n condition = Condition.objects.get(cond_id = condition,network__species=s)\n genes = Gene.objects.filter(conditions=condition)\n corems = Corem.objects.filter(conditions=condition)\n corem_pval = CoremConditionPval.objects.filter(cond_id=condition, \n corem__in = corems)\n gres_pval =GreConditionPval.objects.filter(cond_id=condition)\n biclusters = Bicluster.objects.filter(conditions=condition)\n return render_to_response('condition_detail.html', locals())\n\ndef gres(request):\n species = Species.objects.all()\n out = {}\n for i in species:\n s = i\n n = Network.objects.get(species__name=s.name)\n g = Gene.objects.filter(species__name=s.name).count()\n cond = Condition.objects.filter(network__name=n.name).count()\n corems = Corem.objects.filter(network__name=n.name).count()\n gres = Gre.objects.filter(network__name=n.name).count()\n out[s.short_name] = {\"species\":s,\"network\":n,\"genes\":g,\"conditions\":cond,\"corems\":corems,\"gres\":gres}\n return render_to_response('gres.html', locals())\n \n \n@page_template(\"gres_page.html\")\ndef gres_s(request, template = \"gres_s.html\",species=None,extra_context=None):\n # Return info about gres\n class greObject:\n def __init__(self,species,gre):\n self.species = species\n self.gre_id = gre.gre_id\n self.cres = Cre.objects.filter(gre_id = gre).count()\n #self.pssm = gre.pssm.matrix()\n objects = []\n s = Species.objects.get(ncbi_taxonomy_id=species)\n gres = Gre.objects.filter(network__in=Network.objects.filter(species=s))\n for j in gres:\n objects.append(greObject(species=s,gre=j))\n context = {'objects':objects}\n if extra_context is not None:\n context.update(extra_context)\n return render_to_response(template, context,context_instance=RequestContext(request))\n\n\n\n@page_template(\"gres_detail_page.html\")\ndef gre_detail(request, template = \"gre_detail.html\",species=None, gre=None,extra_context=None):\n # Return info about gres\n class creObject:\n def __init__(self,species,cre):\n self.species = Species.objects.get(ncbi_taxonomy_id=species)\n self.cre_id = cre.cre_id\n self.bcs = cre.cre_id.split(\"_\")[0]+\"_\"+cre.cre_id.split(\"_\")[1]\n self.eval = cre.eval\n #self.pssm = cre.pssm.matrix()\n # just to be sure\n s = Species.objects.get(ncbi_taxonomy_id=species)\n gre = Gre.objects.get(gre_id = gre,network__species__ncbi_taxonomy_id=species)\n pssm = gre.pssm.matrix()\n genes = Gene.objects.filter(gres=gre)\n corems = Corem.objects.filter(gre_ids=gre)\n corem_pval = GreCoremPval.objects.filter(gre_id=gre, \n corem__in = corems)\n conds = Condition.objects.filter(gres=gre)\n conds_pval = GreConditionPval.objects.filter(gre_id=gre, \n cond_id__in = conds)\n conds_pval_dict = {}\n for i in conds_pval:\n d = {\"cond_id\":i.cond_id.cond_id,\"cond_name\":Condition.objects.get(cond_id = i.cond_id.cond_id).cond_name,\"p_val\":i.return_pval()}\n conds_pval_dict[i] = d\n biclusters = Bicluster.objects.filter(gre_ids=gre)\n cres = Cre.objects.filter(gre_id=gre)\n cre_dict = []\n for i in cres:\n cre_dict.append(creObject(species,i))\n return render_to_response(template, locals(),context_instance=RequestContext(request))\n\ndef biclusters(request, species=None):\n # Return info about biclusters\n class BCInfo:\n def __init__(self,network):\n self.network = Network.objects.get(version_id=network)\n self.species = self.network.species\n self.bcs = Bicluster.objects.filter(network=self.network)\n if species:\n networks = [i.version_id for i in Network.objects.filter(species__ncbi_taxonomy_id=species)]\n out = []\n for i in networks:\n out.append(BCInfo(i))\n else:\n networks = [i.version_id for i in Network.objects.all()]\n out = []\n for i in networks:\n out.append(BCInfo(i))\n return render_to_response('biclusters.html', locals())\n\n@page_template(\"biclusters_page.html\")\ndef biclusters_s(request, template = \"biclusters_s.html\",species=None,extra_context=None):\n # Return info about biclusters\n class bcObject:\n def __init__(self,species,bc):\n self.species = Species.objects.get(ncbi_taxonomy_id=species)\n self.network = Network.objects.filter(species=self.species)\n self.bc = Bicluster.objects.get(network__in=self.network,bc_id=bc)\n objects = []\n n = Network.objects.filter(species=Species.objects.get(ncbi_taxonomy_id=species))\n bcs = Bicluster.objects.filter(network__in=n)\n for j in bcs:\n objects.append(bcObject(species=species,bc=j.bc_id))\n context = {'objects':objects}\n if extra_context is not None:\n context.update(extra_context)\n return render_to_response(template, context,context_instance=RequestContext(request))\n\ndef bicluster_detail(request, species=None, bicluster=None):\n # Return info about bicluster\n # just to be sure\n s = Species.objects.get(ncbi_taxonomy_id=species)\n bc = Bicluster.objects.get(bc_id = bicluster,network__species=s)\n genes = Gene.objects.filter(bcs=bc)\n conds = Condition.objects.filter(bcs=bc)\n corems = Corem.objects.filter(top_bcs=bc)\n cres = Cre.objects.filter(bcs=bc)\n gres = Gre.objects.filter(bcs=bc)\n return render_to_response('bicluster_detail.html', locals())\n\ndef networks(request, species=None):\n # Return info about the network\n if species:\n out = {}\n s = Species.objects.get(ncbi_taxonomy_id=species)\n n = Network.objects.get(species__name=s.name)\n g = Gene.objects.filter(species__name=s.name).count()\n cond = Condition.objects.filter(network__name=n.name).count()\n corems = Corem.objects.filter(network__name=n.name).count()\n gres = Gre.objects.filter(network__name=n.name).count()\n out[s.short_name] = {\"species\":s,\"network\":n,\"genes\":g,\"conditions\":cond,\"corems\":corems,\"gres\":gres}\n else:\n species = Species.objects.all()\n out = {}\n for i in species:\n s = i\n n = Network.objects.get(species__name=s.name)\n g = Gene.objects.filter(species__name=s.name).count()\n cond = Condition.objects.filter(network__name=n.name).count()\n corems = Corem.objects.filter(network__name=n.name).count()\n gres = Gre.objects.filter(network__name=n.name).count()\n out[s.short_name] = {\"species\":s,\"network\":n,\"genes\":g,\"conditions\":cond,\"corems\":corems,\"gres\":gres}\n return render_to_response('networks.html', locals())\n\ndef regulators(request,species=None):\n # get info about all regulators\n class regulators:\n def __init__(self,species,tf):\n self.CUTOFF = .75\n self.s = species\n self.tf = tf\n self.gres = list(set([o.gre_id for o in greTF.objects.filter(tf=tf,score__gte=self.CUTOFF)]))\n self.corems = list(set(Corem.objects.filter(gre_ids__in=self.gres)))\n self.genes = list(set(Gene.objects.filter(gres__in=self.gres)))\n self.conds = list(set(Condition.objects.filter(gres__in=self.gres)))\n tfs = list(set([o.tf for o in greTF.objects.all()]))\n s = Species.objects.get(ncbi_taxonomy_id=species)\n out = []\n for i in tfs:\n out.append(regulators(species=s,tf=i))\n return render_to_response('regulators.html', locals())\n\ndef regulator_detail(request,species=None,regulator=None):\n # get info about specific regulators\n class greObject:\n def __init__(self,species,tf,gre):\n self.species = species\n self.gre_id = gre.gre_id\n self.pssm = gre.pssm.matrix()\n self.score = greTF.objects.get(tf=tf,gre_id=gre).score\n CUTOFF = .75\n s = Species.objects.get(ncbi_taxonomy_id=species)\n tf = regulator\n gres = list(set([o.gre_id for o in greTF.objects.filter(tf=tf,score__gte=CUTOFF)]))\n corems = list(set(Corem.objects.filter(gre_ids__in=gres)))\n corem_pval = GreCoremPval.objects.filter(corem__in=corems,gre_id__in=gres)\n genes = list(set(Gene.objects.filter(gres__in=gres)))\n gene_pval = GreGenePval.objects.filter(gene__in=corems,gre_id__in=gres)\n conds = list(set(Condition.objects.filter(gres__in=gres)))\n conds_pval = GreConditionPval.objects.filter(cond_id__in=conds,gre_id__in=gres)\n greObjs = []\n for i in gres:\n greObjs.append(greObject(species=s,tf=tf,gre=i))\n return render_to_response('regulator_detail.html', locals())\n","sub_path":"django/django_projects/Project/egrin2/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"206802596","text":"\n# @file: main.py\n# @author: Abraham Dick\n# @date: October 2017\n# @desc: main controller for EECS 690 semester project\n\nimport sys\n\nfrom src.controller import Controller\n\ndef main(): \n _controller = Controller()\n _controller.run()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"48922643","text":"from django.shortcuts import render\n\n# Create your views here.\n\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\n\nfrom history.models import Teamindex\n#from history.models import Seasonindex\nfrom history.models import Seasondata\n\ndef index(request):\n\t# Obtain the context from the HTTP request.\n\tcontext = RequestContext(request)\n\n\t# QUERY THE DB FOR A LIST OF TEAMS PRESENT\n\tteam_list = Teamindex.objects.order_by('teamname')\n\tcontext_dict = {'teams': team_list}\n\n\t# RENDER THE RESPONSE AND FIRE IT BACK\n\treturn render_to_response('index.html', context_dict, context)\n\ndef history_report(request, team_name):\n\t# Obtain the context from the HTTP request.\n\tcontext = RequestContext(request)\n\n\tteam_check = Teamindex.objects.filter(teamname=team_name)\n\n\tif not team_check: # REPORT THAT THE TEAM DOES NOT SEEM TO EXIST\n\t\tmessage = \"Team is nonexistant\"\n\t\tteam_info = ''\n\t\tteam_data = ''\n\telse: # GO GET THIS TEAM'S DATA\n\t\tmessage = ''\n\n\t\tteam_info = Teamindex.objects.get(teamname=team_name)\n\t\tteam_id = team_info.id\n\t\t\t\n\t\t# GO GET ALL COMPLETED SEASON DATA FROM THE DB FOR THIS TEAM\n\t\tteam_data = Seasondata.objects.filter(teamid=team_id)\n\t\t\n\t\tfor team in team_data:\n\t\t\tteam.weekfinalrating = team.weekfinalrating * 10000\n\t\t\tteam.weekfinalrating = round(team.weekfinalrating, 1)\n\t\t\tteam.weekfinalsos = round(team.weekfinalsos, 5)\n\n\tcontext_dict = {'teamname': team_name, 'teaminfo': team_info, 'message': message, 'teamdata': team_data}\n\n\t# RENDER THE RESPONSE AND FIRE IT BACK\n\treturn render_to_response('history.html', context_dict, context)\n","sub_path":"gberatings/history/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"91367144","text":"# -*- coding: utf-8 -*-\nimport random\n\n\ndef solicitaSimbolodoHumano(a):\n a = input('Simbolo que quer jogar: ')\n while a!='O' and a!='X' and a!='o' and a!='x':\n a = input('Simbolo que quer jogar: ')\n return 1\n\ndef sorteioPrimeiraJogada(a):\n a = random.choice((0,1))\n if a ==1:\n print('Vencedor do sorteio para inicio do jogo : Jogador')\n \n else:\n print('Vencedor do sorteio para inicio do jogo : Computador')\n\ndef jogadaComputador(a):\n pc = random.choice(('0 0', '0 1','0 2','1 0', '1 1','1 2','2 0', '2 1','2 2'))\n print (pc)\n return 1\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"moodledata/vpl_data/380/usersdata/310/97330/submittedfiles/minha_bib.py","file_name":"minha_bib.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"261751368","text":"from .group import *\n\ndef load(group):\n group.load()\n print(\"Success load\\n\")\n\ndef send(group):\n group.send()\n print(\"Success send\\n\")\n\ngroup = Group()\n\ndef main(): \n print(\"Menu\")\n print(\"1. Load\")\n print(\"2. Send\")\n print(\"0. Back\")\n choice = input(\" >> \")\n exec_menu(choice)\n\n \ndef exec_menu(choice):\n try:\n menu_actions[choice](group)\n except KeyError:\n if choice != '0':\n print(\"Invalid selection!\\n\")\n if choice != '0': \n menu_actions['main']()\n else:\n return\n\n\nmenu_actions = {\n 'main': main,\n '1': load,\n '2': send,\n # '0': exit,\n}\n","sub_path":"st04/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"447927484","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\ntest_services\n----------------------------------\n\nTests for `teamsupport.services` module.\n\"\"\"\nimport unittest\n\nfrom lxml.builder import E\n\nfrom teamsupport.services import XMLHTTPServiceClient\nfrom tests import PatchedSessionXmlTests\n\n\nclass TestBaseXMLClient(PatchedSessionXmlTests):\n\n def setUp(self):\n super(TestBaseXMLClient, self).setUp()\n self.client = XMLHTTPServiceClient(url='https://localhost/')\n\n def test_parse_xml_response_returns_element(self):\n self.response.content = ''\n result = self.client.parse_xml_response(self.response)\n self.assertEqualXml(result, E.Tickets())\n\n def test_send_as_xml_properly_formats_request(self):\n request_params = {\n 'data': {'Field1': 'Test field'},\n 'root': 'OuterField',\n 'send_as_xml': True\n }\n request_params = self.client._format_xml_request(request_params)\n\n self.assertEqual(request_params['data'], self.xml_element_string)\n self.assertEqual(\n request_params['headers']['Content-Type'], 'application/xml')\n\n def test_send_as_xml_properly_formats_xml(self):\n request_element = self.xml_element\n request_params = {\n 'data': request_element,\n 'send_as_xml': True\n }\n request_params = self.client._format_xml_request(request_params)\n\n self.assertEqual(request_params['data'], self.xml_element_string)\n self.assertEqual(\n request_params['headers']['Content-Type'], 'application/xml')\n\n def tearDown(self):\n super(TestBaseXMLClient, self).tearDown()\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_services.py","file_name":"test_services.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"459234351","text":"def f(x):\n try:\n return float(x)\n except ValueError:\n return ord(x)\n\n#https://archive.ics.uci.edu/ml/machine-learning-databases/credit-screening/crx.data\nwith open('crx.data') as inf:\n samples = []\n for line in inf:\n vals = line.rstrip().replace('?', 'nan').split(',')\n sample = [f(x) for x in vals]\n sample[-1] = int(sample[-1] == ord('+'))\n samples.append(sample)\n\nwith open('samples.csv', 'wb') as outf:\n for i, sample in enumerate(samples):\n outf.write('{}\\n'.format(','.join(str(x) for x in sample)))\n\nwith open('featurenames.txt', 'wb') as outf:\n for i in range(1, 16):\n outf.write('A{}\\n'.format(i))\n","sub_path":"ml-4641/hw1/datasets/credit/quickclean.py","file_name":"quickclean.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"462335513","text":"class Solution(object):\n def exist(self, board, word):\n \"\"\"\n :type board: List[List[str]]\n :type word: str\n :rtype: bool\n \"\"\"\n ROW = len(board)\n COL = len(board[0])\n visited = set()\n\n def dfs(row, col, idx):\n if idx >= len(word):\n return True\n\n visited.add((row, col))\n directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n for direction in directions:\n new_row = row + direction[0]\n new_col = col + direction[1]\n if (\n new_row >= 0\n and new_row < ROW\n and new_col >= 0\n and new_col < COL\n and (new_row, new_col) not in visited\n and board[new_row][new_col] == word[idx]\n ):\n if dfs(new_row, new_col, idx + 1):\n return True\n visited.remove((row, col))\n return False\n\n for i in range(ROW):\n for j in range(COL):\n if board[i][j] == word[0]:\n if dfs(i, j, 1):\n return True\n return False\n","sub_path":"algorithm/l2/79.word-search.py","file_name":"79.word-search.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"325810673","text":"import logging\nimport MySQLdb\n\nlogging.basicConfig(format='%(asctime)s-%(levelname)s-%(name)s - %(message)s')\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\nconfig = {\n 'host': '127.0.0.1',\n 'user': 'koha_zenon',\n 'passwd': 'zenon',\n 'db': 'koha_mapping_db',\n 'port': 3307,\n 'use_unicode': True,\n 'charset': 'utf8'\n}\n\nconnection = None\n\n\ndef get_db_name():\n return 'koha_mapping_db'\n\n\ndef get_cursor():\n global connection\n\n return connection.cursor()\n\n\ndef establish_connection():\n global connection\n\n connection = MySQLdb.connect(host=\"127.0.0.1\", user=\"koha_zenon\", passwd=\"zenon\", db=get_db_name(), port=3307,\n use_unicode=True, charset='utf8')\n\n\ndef open_mariadb_connection():\n global connection\n\n if connection is None:\n try:\n logger.debug(\"Trying to connect to MariaDB ...\")\n connection = MySQLdb.connect(**config)\n logger.debug(\"Connection to MariaDB established.\")\n return connection\n except MySQLdb.Error as err:\n logger.error(err)\n raise Exception\n except MySQLdb.Warning as warn:\n logger.warning(warn)\n raise Exception\n else:\n logger.debug('Connection to MariaDB already established!\\n')\n\n\ndef close_mariadb_connection():\n global connection\n\n if connection is not None:\n connection.close()\n logger.debug(\"Connection to MariaDB closed.\\n\")\n else:\n logger.debug(\"Connection to MariaDB was already closed!\\n\")\n\n\ndef commit():\n global connection\n\n connection.commit()\n\n\ndef get_aqbookseller_by_aleph_vendor_key(aleph_vendor_key):\n global connection\n\n cursor = connection.cursor()\n cursor.execute('SELECT * FROM aqbooksellers WHERE `ALEPH_VENDOR_CODE`=\"'+aleph_vendor_key+'\";')\n result = cursor.fetchone()\n\n return result\n\n\ndef get_aleph_vendor_code_koha_aqbookseller_mapping():\n global connection\n result = None\n\n try:\n logger.debug(\"Fetching 'Aleph_Vendor_Code Koha_Aqbookseller' mapping ...\")\n cursor = connection.cursor()\n cursor.execute(\"SELECT `ALEPH_VENDOR_CODE`, `NAME` FROM aqbooksellers;\")\n result = cursor.fetchall()\n logger.debug('Mapping fetched.')\n except MySQLdb.Error as err:\n logger.error(err)\n except MySQLdb.Warning as warn:\n logger.warning(warn)\n\n return result\n\n\ndef get_koha_aqbookseller_name_by_aleph_vendor_key(aleph_vendor_key):\n global connection\n result = None\n\n try:\n cursor = connection.cursor()\n cursor.execute(\"SELECT DISTINCT `NAME` FROM aqbooksellers WHERE `ALEPH_VENDOR_CODE`=%s;\", aleph_vendor_key)\n result = cursor.fetchone()\n except MySQLdb.Error as err:\n logger.error(err)\n except MySQLdb.Warning as warn:\n logger.warning(warn)\n\n return result\n\n\ndef get_aqbaskets():\n global connection\n\n cursor = connection.cursor()\n cursor.execute('SELECT * FROM aqbasket;')\n result = cursor.fetchall()\n return result\n\n\ndef get_aqbasket_by_aleph_rec_key(aleph_rec_key):\n global connection\n\n cursor = connection.cursor()\n cursor.execute('SELECT * FROM aqbasket WHERE `ALEPH_Z68_REC_KEY`=\"' + aleph_rec_key + '\";')\n result = cursor.fetchone()\n return result\n\n\ndef get_aqbasketgroups():\n global connection\n\n cursor = connection.cursor()\n cursor.execute('SELECT * FROM aqbasketgroups;')\n result = cursor.fetchall()\n return result\n\n\ndef get_aqbasketgroup_by_aleph_rec_key(aleph_rec_key):\n global connection\n\n cursor = connection.cursor()\n cursor.execute('SELECT * FROM aqbasketgroups WHERE `ALEPH_Z68_REC_KEY`=\"' + aleph_rec_key + '\";')\n\n result = cursor.fetchone()\n\n return result\n","sub_path":"lib/database_connections/mariadb.py","file_name":"mariadb.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"290746509","text":"#!/usr/bin/env python3\n\"\"\"\nPerforms a \"smart wrap\" of the input lines. Will find a prefix of each line and\nwill include it in the final output.\n\"\"\"\nimport sys\nimport textwrap\nimport os\n\ntarget = sys.stdin.readlines()\nif len(target) == 1:\n prefix = \"\"\nelse:\n # We replace the newlines with spaces so \"empty\" comment lines won't cause\n # subsequent lines to be printed immediately after the comment mark\n prefix = os.path.commonprefix([line.replace(\"\\n\", \" \") for line in target])\n# Remove prefix for the textwrap module, we'll let it put them back in\nfixedtext = [ line[len(prefix):].strip() for line in target ]\noutput = []\nfor line in fixedtext:\n if not line:\n output.append(prefix.rstrip())\n else:\n output.append(textwrap.fill(line, width=80, initial_indent=prefix,\n subsequent_indent=prefix))\nprint(\"\\n\".join(output))\n","sub_path":"tools/bin/autowrap.py","file_name":"autowrap.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"362872852","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 1 18:59:09 2015\n\n@author: ghost\n\"\"\"\n\nimport csv\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport statsmodels.tsa.stattools as ts\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\nimport pandas.io.data as web\nimport datetime\nfrom arch.univariate import ARX\nimport arch\nimport calendar\n\n# Open and tidy oil price data\nwith open('DCOILWTICO.csv', 'r') as f:\n reader = csv.reader(f)\n oil = list(reader)\n oil = [x for x in oil if x[1] != '.']\n oil = [x for x in oil if x != 0]\n oil = oil[1:]\n \n# open and tidy CERI data\nwith open('lookup2.csv', 'r') as f:\n reader = csv.reader(f)\n ceri = list(reader)\n ceri = [x for x in ceri if len(x) == 2]\n ceri = ceri[::-1][:len(ceri)-1]\n \n# Extract dates from data \noindex = list(map(lambda x: x[0],oil))\ncindex = list(map(lambda x: x[0],ceri))\n\n#Ensure only common dates are used\ninter = [x for x in cindex if x in oindex]\nvalid = [x for x in oindex if x in inter]\n\n# Extract accompanying prices from valid dates, using CERI\noilprice = [np.log(float(x[1])) for x in oil if x[0] in valid]\nexrate = [np.log(float(x[1])) for x in ceri if x[0] in valid]\n\n\n#WTI and Nominal Exchange Rate, data cleaning\nstart = datetime.datetime(1987, 5, 20)\nend = datetime.datetime(2015, 9, 27)\nDEXCAUS = web.DataReader(\"DEXCAUS\", \"fred\", start,end)\nDCOILWTICO = web.DataReader(\"DCOILWTICO\", \"fred\", start,end)\nDCOILBRENTEU = web.DataReader(\"DCOILBRENTEU\", \"fred\", start,end)\nfilterex = DEXCAUS[~np.isnan(DEXCAUS.values)]\nfilterwti = DCOILWTICO[~np.isnan(DCOILWTICO.values)]\nfilterbrent = DCOILBRENTEU[~np.isnan(DCOILBRENTEU.values)]\ndates = filterwti.index\ndex = filterex[filterex.index.isin(dates)]\ndco = filterwti[filterwti.index.isin(dex.index)]\ndexb = filterex[filterex.index.isin(filterbrent.index)]\ndcob = filterbrent[filterbrent.index.isin(dexb.index)]\noilprice = [np.log(x[0]) for x in dco.values]\nexrate = [np.log(x[0]) for x in dex.values]\n#oilprice = [x[0] for x in dco.values]\n#exrate = [x[0] for x in dex.values]\n\n#averageoil = [(oilprice[i]+oilprice[i+1]+oilprice[i+2]+oilprice[i+3]+oilprice[i+4])/5 for i in range(0,7415,5)]\n#averager = [(exrate[i]+exrate[i+1]+exrate[i+2]+exrate[i+3]+exrate[i+4])/5 for i in range(0,7415,5)]\n\n#diffp = np.diff(averageoil)\n#diffr = np.diff(averager)\n\n# Construct the monthly prices\nmoilpricedates = [x for x in dco.index if x.day == calendar.monthrange(x.year,x.month)[1]]\nmexratedates = [x for x in dex.index if x.day == calendar.monthrange(x.year,x.month)[1]]\n\nmoilprice = dco[dco.index.isin(moilpricedates)]\nmexrate = dex[dex.index.isin(mexratedates)]\nexrate = [np.log(x[0]) for x in mexrate.values]\noilprice = [np.log(x[0]) for x in moilprice.values]\n\n#Difference the data\ndiffp = np.diff(oilprice)\ndiffr = np.diff(exrate)\n\n# Zipped list for price/exrate and first difference\npdata = list(zip(oilprice,exrate))\n\n\n# Parameter for the length of the forecast\nk = 300\n\n\ndf = pd.DataFrame(pdata, columns = ['Price', 'exrate'])\npdata2 = list(zip(diffp,diffr))\ndf2 = pd.DataFrame(pdata2, columns = ['Price', 'exrate'])\npdata3 = list(zip(diffp[1:len(diffp)-k],diffr[1:len(diffp)-k]))\ndf3 = pd.DataFrame(pdata3, columns = ['Price', 'exrate'])\nlag = 1\nlaggeddata = list(zip(diffp[1:len(diffp)-k-lag-1],diffr[1+lag:len(diffp)-k-1],diffr[1:len(diffp)-k-1-lag]))\nlagdf = pd.DataFrame(laggeddata, columns = ['Price', 'exrate','lagexrate'])\n\nlagsample = smf.ols(formula = 'exrate ~ Price + lagexrate', data=lagdf).fit()\n\n#Fit the data using lagged differences\ninsample = smf.ols(formula='exrate ~ Price', data=df3).fit()\n# list of exchange rate estimates using fitted values\nestimates = list(map(lambda x:np.sum(insample.params*[1,x]),diffp[len(diffp)-k:]))\nlagestimates = [lagsample.params[0] + lagsample.params[1]*diffp[len(diffp)-k-1:][i] +\n lagsample.params[2]*diffp[len(diffp)-k-1:][i] for i in range(k)]\n# Rolling window estimates\ntemp= pdata3\nrestimates = []\nfor i in range(k):\n tempdf = pd.DataFrame(temp, columns=['Price', 'exrate'])\n insample = smf.ols(formula='exrate ~ Price', data=tempdf).fit().params\n restimates = restimates + [insample[0] +insample[1]*diffp[len(diffp)-k +i]]\n temp = temp[1:]\n# Results : Slightly lower MSFE\n \n\n# list of actual exchange rates\nactual = diffr[len(diffp)-k:]\ninitialval = exrate[len(diffp)-k]\n\n\n#Fit Random Walk Model to diff\n\n\n# Generate a random walk\ndef genwalk(x=len(actual)+1,estdev = np.std(diffr)):\n i= -1 \n epsilons = np.random.normal(0,estdev,x)\n temp = epsilons[::-1]\n for x in temp:\n i+= 1\n temp[i] = x + np.sum(epsilons[:len(epsilons)-1-i])\n rwalk = temp[::-1]\n rwalk = np.diff(rwalk)\n return rwalk\n\ndef plotwalks(x):\n temp = list(zip(restimates,actual))\n columnz = [\"Estimates\", \"Actual\"]\n for i in range(x):\n temp = list(zip(temp,genwalk()))\n columnz = columnz + [\"Random Walk\" + str(i)]\n temp = [list(x[0]) + [x[1]] for x in temp]\n print(temp)\n compare = pd.DataFrame(temp, columns = columnz)\n compare.plot(figsize=(10,10))\n\n\n# Retrieve ADF pvalue for the series and the first difference\n# \r\n 45\r\n\"\"\"\r\ndef sum(x):\r\n sum = 0\r\n for i in range(1, x+1):\r\n sum += i\r\n return sum\r\n\r\nfor n in range(1, 101):\r\n if sum(n)>1000:\r\n print(n)\r\n break","sub_path":"quiz/pre_python_07.py","file_name":"pre_python_07.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"93215997","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nImplement the Q-networks used by the agents\r\n\r\n\r\n@author: udacity, ucaiado\r\n\r\nCreated on 10/07/2018\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport pdb\r\n\r\n\r\n'''\r\nBegin help functions\r\n'''\r\n\r\n\r\ndef hidden_init(layer):\r\n # source: The other layers were initialized from uniform distributions\r\n # [− 1/sqrt(f) , 1/sqrt(f) ] where f is the fan-in of the layer\r\n fan_in = layer.weight.data.size()[0]\r\n lim = 1. / np.sqrt(fan_in)\r\n return (-lim, lim)\r\n\r\n'''\r\nEnd help functions\r\n'''\r\n\r\n\r\nclass Actor(nn.Module):\r\n \"\"\"Actor (Policy) Model.\"\"\"\r\n\r\n def __init__(self, state_size, action_size, seed, fc1_units=400,\r\n fc2_units=300):\r\n \"\"\"Initialize parameters and build model.\r\n\r\n :param state_size: int. Dimension of each state\r\n :param action_size: int. Dimension of each action\r\n :param seed: int. Random seed\r\n :param fc1_units: int. Number of nodes in first hidden layer\r\n :param fc2_units: int. Number of nodes in second hidden layer\r\n \"\"\"\r\n super(Actor, self).__init__()\r\n self.seed = torch.manual_seed(seed)\r\n # source: The low-dimensional networks had 2 hidden layers\r\n self.fc1 = nn.Linear(state_size, fc1_units)\r\n self.fc2 = nn.Linear(fc1_units, fc2_units)\r\n self.fc3 = nn.Linear(fc2_units, action_size)\r\n self.reset_parameters()\r\n\r\n def reset_parameters(self):\r\n self.fc1.weight.data.uniform_(*hidden_init(self.fc1))\r\n self.fc2.weight.data.uniform_(*hidden_init(self.fc1))\r\n # source: The final layer weights and biases of the actor and were\r\n # initialized from a uniform distribution [−3 × 10−3, 3 × 10−3]\r\n self.fc3.weight.data.uniform_(-3e-3, 3e-3)\r\n\r\n def forward(self, state):\r\n \"\"\"\r\n Build an actor (policy) network that maps states -> actions.\r\n \"\"\"\r\n # source: used the rectified non-linearity for all hidden layers\r\n x = F.relu(self.fc1(state))\r\n x = F.relu(self.fc2(x))\r\n # source The final output layer of the actor was a tanh layer,\r\n # to bound the actions\r\n return torch.tanh(self.fc3(x))\r\n\r\n\r\nclass Critic(nn.Module):\r\n \"\"\"Critic (Value) Model.\"\"\"\r\n\r\n def __init__(self, state_size, action_size, nb_agents, seed,\r\n fcs1_units=400, fc2_units=300):\r\n \"\"\"Initialize parameters and build model.\r\n\r\n :param state_size: int. Dimension of each state\r\n :param action_size: int. Dimension of each action\r\n :param seed: int. Random seed\r\n :param fcs1_units: int. Nb of nodes in the first hiddenlayer\r\n :param fc2_units: int. Nb of nodes in the second hidden layer\r\n \"\"\"\r\n super(Critic, self).__init__()\r\n self.seed = torch.manual_seed(seed)\r\n self.fcs1 = nn.Linear((state_size+action_size)*nb_agents, fcs1_units)\r\n self.fc2 = nn.Linear(fcs1_units, fc2_units)\r\n self.fc3 = nn.Linear(fc2_units, 1)\r\n self.reset_parameters()\r\n\r\n def reset_parameters(self):\r\n self.fcs1.weight.data.uniform_(*hidden_init(self.fcs1))\r\n self.fc2.weight.data.uniform_(*hidden_init(self.fc2))\r\n # source: The final layer weights and biases of the critic were\r\n # initialized from a uniform distribution [3 × 10−4, 3 × 10−4]\r\n self.fc3.weight.data.uniform_(-3e-3, 3e-3)\r\n\r\n def forward(self, state, action):\r\n \"\"\"\r\n Build a critic (value) network that maps\r\n (state, action) pairs -> Q-values\r\n\r\n :param state: tuple.\r\n :param action: tuple.\r\n \"\"\"\r\n xs = torch.cat((state, action.float()), dim=1)\r\n x = F.relu(self.fcs1(xs))\r\n x = F.relu(self.fc2(x))\r\n return self.fc3(x)\r\n","sub_path":"drlnd/ddpg/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"471794166","text":"# coding:utf-8\n\nfrom urldownload.BOOKManager import BookManager\nfrom urldownload.HtmlDownloader import HtmlDownloader\nfrom urldownload.HtmlParser import HtmlParser\nfrom urldownload.DataOutput import DataOutput\nfrom urldownload.book import Book\n\n\nclass SpiderMan(object):\n\n def __init__(self):\n self.manager = BookManager()\n self.downloader = HtmlDownloader()\n self.parser = HtmlParser()\n self.output = DataOutput()\n\n def crawl_book(self, root_url):\n # 添加入坑URL\n # 获取主页数据\n html = self.downloader.download(root_url)\n html_content = self.parser.parser_root(html)\n for item in html_content:\n book_title = item['title']\n self.downloader.getDownloadPath(book_title)\n for item_item in item['content']:\n href = item_item['href']\n box_title = item_item['box_title']\n book = Book(\n chapter=book_title,\n section=box_title,\n url=href\n )\n self.manager.add_book_url(book)\n\n while (self.manager.has_new_book() and self.manager.old_bookt_url_size() < 500):\n try:\n # 从URL管理器获取新的url\n book = self.manager.get_new_book()\n # HTML下载器下载网页\n html = self.downloader.download(book.url)\n # HTML解析器抽取网页数据\n data = self.parser.parser(book.url, html)\n self.output.store_data(data)\n path = self.downloader.getDownloadPath(book.chapter) + '/' + book.section + '.html'\n self.output.output_html(path, data)\n print(book.chapter,'/', book.section, '拉取完成')\n except Exception as e:\n # 失败后是否需要重试,根据需求\n # self.manager.add_book_url(book)\n print(book.chapter, '/', book.section, '拉取失败')\n\n\n def crawl(self, root_url):\n # 添加入坑URL\n self.manager.add_new_url(root_url)\n # 判断url管理器中国呢是否有新的url, 同时判断抓取了多少个url\n while(self.manager.has_new_url() and self.manager.old_url_size() < 100 ):\n try:\n # 从URL管理器获取新的url\n new_url = self.manager.get_new_url()\n # HTML下载器下载网页\n html = self.downloader.download(new_url)\n # HTML解析器抽取网页数据\n new_urls,data = self.parser.parser(new_url, html)\n # 将抽取到url添加到ULR管理器中\n self.manager.add_new_ulrs(new_urls)\n # 将数据存储到文件\n self.output.store_data(data)\n except Exception as e:\n print('crawl failed')\n self.output.output_html()\n\nif __name__ == '__main__':\n spider_man = SpiderMan()\n spider_man.crawl_book('http://seputu.com/')","sub_path":"urldownload/SpiderMan.py","file_name":"SpiderMan.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"42906151","text":"\"\"\"\nFile to process the homogeneized stress and strain values for an RVE simulated in Abaqus/Explicit for every frame\n\"\"\"\n\nimport numpy as np\nimport time\nimport os\nimport sys\nfrom odbAccess import openOdb\n\ndef logtotrueStrain(vector):\n import math\n l_l0 = [math.e**value for value in vector]\n true_E = [1.0-(1.0/x) for x in l_l0]\n return true_E\n\ndef logtoEngStrain(vector):\n import math\n l_l0 = [math.e**value for value in vector]\n eng_E = [x-1.0 for x in l_l0]\n return eng_E\n\ncwd = '/home/cerecam/Desktop/Crack_Models/'\n# odbname = 'NPG_TensileTest_1.odb'\n# outputFile = 'NPG_TensileTest_1_results.txt'\nodbnames = ['/60PER/1/Results/RVE_40Vox_60PER_2_Final']\nfor odbname in odbnames:\n outputFile = odbname + '_results.txt'\n odb = openOdb(cwd + odbname + '.odb')\n assem = odb.rootAssembly\n # myInstance = assem.instances['RVE']\n stepKey = odb.steps.keys()\n steps = odb.steps[stepKey[-1]]\n all_frames = steps.frames\n last_frame = all_frames[-1]\n\n resultsFile = open(cwd+outputFile, 'w')\n t0 = time.time()\n for frame in all_frames:\n print >> sys.__stdout__, (\"Processing frame: \" + str(frame.frameValue))\n\n trace_e_list = []\n e_dev = []\n trace_s_list = []\n s_dev = []\n\n stress = frame.fieldOutputs['S']\n # strain = frame.fieldOutputs['LE']\n\n s_sum = np.array([0.0]*len(stress.values[0].data))\n # e_sum = np.array([0.0]*len(strain.values[0].data))\n RVE_ele = 0\n t1 = time.time()\n for x in range(len(stress.values)):\n if stress.values[x].elementLabel > 5000000:\n RVE_ele += 1\n s_data = np.array(stress.values[x].data)\n s_sum += s_data\n t2 = time.time()\n # e_data = np.array(strain.values[x].data)\n # e_sum += e_data\n # t3 = time .time()\n # if frame.frameValue == last_frame.frameValue:\n # x_tensor = np.array([[s_data[0], s_data[3], s_data[5]],\n # [s_data[3], s_data[1], s_data[4]],\n # [s_data[5], s_data[4], s_data[2]]])\n # trace_s = np.tensordot(x_tensor, np.eye(3))/3.0\n # s_dev.append(x_tensor-trace_s*np.eye(3))\n # trace_s_list.append(trace_s)\n # t4 = time .time()\n #\n # y_tensor = np.array([[e_data[0], e_data[3], e_data[5]],\n # [e_data[3], e_data[1], e_data[4]],\n # [e_data[5], e_data[4], e_data[2]]])\n # trace_e = np.tensordot(y_tensor, np.eye(3))\n # e_dev.append(y_tensor-trace_e*np.eye(3))\n # trace_e_list.append(trace_e)\n # t5 = time.time()\n\n print >> sys.__stdout__, (\"s_data extraction complete: \" + str((t2-t1)/60.0))\n # print >> sys.__stdout__, (\"e_data extraction complete: \" + str((t3-t2)/60.0))\n # print >> sys.__stdout__, (\"s_data homogenization variables complete: \" + str(t3-t4))\n # print >> sys.__stdout__, (\"e_data homogenization variables complete: \" + str(t4-t5))\n homog_stress = s_sum/RVE_ele\n # homog_strain = e_sum/(len(e_data))\n\n resultsFile.write(\"Frame ID: \" + str(frame.frameValue) + '\\n')\n resultsFile.write(\"Stress: \" + str(list(homog_stress)).strip('[').strip(']') + '\\n')\n # resultsFile.write(\"Strain: \" + str(list(homog_strain)).strip('[').strip(']') + '\\n')\n print >> sys.__stdout__, (\"Frame ID: \" + str(frame.frameValue))\n print >> sys.__stdout__, (\"Stress: \" + str(list(homog_stress)))\n # print >> sys.__stdout__, (\"Strain: \" + str(list(homog_strain)))\n print >> sys.__stdout__, (\"Results file written\")\n print >> sys.__stdout__, (\"Total time {}\".format((t2-t0)/60.0))\n # if frame.frameValue == last_frame.frameValue:\n # s_dev_sum = np.sum(np.array(s_dev),0)\n # e_dev_sum = np.sum(np.array(e_dev),0)\n # trace_s_sum = np.sum(trace_s_list)\n # trace_e_sum = np.sum(trace_e_list)\n #\n # mu = 0.5*np.sqrt(np.tensordot(s_dev_sum, s_dev_sum)/np.tensordot(e_dev_sum,e_dev_sum))\n # kappa = (1.0/3.0)*(trace_s_sum/trace_e_sum)\n # em = (9.0*kappa*mu)/(3.0*kappa + mu)\n # poisson = (3.0*kappa-2.0*mu)/(6.0*kappa + 2.0*mu)\n # resultsFile.write(\"Youngs mod, poissons ratio, bulk (kappa), shear (mu) modulus: \" +\n # str(em) + ', ' + str(poisson) + ', ' + str(kappa) + ', ' + str(mu) + '\\n')\n # print >> sys.__stdout__, (\"Homogenization variable written\")\n print >> sys.__stdout__, (\"COMPLETED frame: \" + str(frame.frameValue))\n odb.close()\n resultsFile.close()\n","sub_path":"StressStrainPostProc.py","file_name":"StressStrainPostProc.py","file_ext":"py","file_size_in_byte":4878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"469481167","text":"import unittest\nfrom unittest import TestCase\n\nimport numpy as np\nimport deepchem as dc\nfrom deepchem.splits.splitters import ScaffoldSplitter\n\n\nclass TestScaffoldSplitter(TestCase):\n\n def test_scaffolds(self):\n tox21_tasks, tox21_datasets, transformers = \\\n dc.molnet.load_tox21(featurizer='GraphConv')\n train_dataset, valid_dataset, test_dataset = tox21_datasets\n\n splitter = ScaffoldSplitter()\n scaffolds_separate = splitter.generate_scaffolds(train_dataset)\n scaffolds_train, scaffolds_valid, _ = splitter.split(train_dataset)\n\n # The amount of datapoints has to be the same\n data_cnt = sum([len(sfd) for sfd in scaffolds_separate])\n self.assertTrue(data_cnt == train_dataset.X.shape[0])\n\n # The number of scaffolds generated by the splitter\n # has to be smaller or equal than number of total molecules\n scaffolds_separate_cnt = len(scaffolds_separate)\n self.assertTrue(scaffolds_separate_cnt <= train_dataset.X.shape[0])\n","sub_path":"deepchem/splits/test_scaffold_splitter.py","file_name":"test_scaffold_splitter.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"315088170","text":"import logging\nimport numpy as np\n\nfrom sklearn.model_selection import KFold\nfrom deepecoach.utils import unvectorize\nfrom deepecoach.models.utils import save_to_file\n\nlogger = logging.getLogger(__name__)\n\n\nclass CrossValidation:\n def __init__(self, data_set_manager, train_manager, options):\n self.dsm = data_set_manager\n self.train_manager = train_manager\n self.epochs = options['epochs']\n self.folds = options['kfold']\n self.val_split = options['val_split']\n l_name = options['models'][0]\n p_name = options['models'][1]\n self.predictions_filename = '%s-%s-%s-%s-%s' % (\n l_name, p_name, options['dataset'], options['pos_type'], options['emb_type'])\n self.predictions_dirname = options['save_predictions']\n self.save_predictions = options['save_predictions']\n self.task = options['task']\n\n def run(self, verbose=True):\n '''\n Micro averaged or Macro averaged F1?\n http://stats.stackexchange.com/questions/156923/should-i-make-decisions-based-on-micro-averaged-or-macro-averaged-evaluation-mea\n paper sobre: http://www.sciencedirect.com/science/article/pii/S0306457309000259\n '''\n lexical_stats = [0, 0, 0]\n prosodic_stats = [0, 0, 0]\n combiner_stats = [0, 0, 0]\n best_partition = 0\n\n n_samples = sum(x.nb_texts for x in self.dsm.originals)\n if self.folds == -1 or n_samples < self.folds: # leave one out\n self.folds = n_samples\n kf = KFold(n_splits=self.folds, shuffle=True)\n placeholder = np.zeros(n_samples)\n\n for k, (train_index, test_index) in enumerate(kf.split(placeholder)):\n logger.info('K fold: {} of {}'.format(k + 1, self.folds))\n\n logger.info('Train/Test summary: ')\n ds_train, ds_test = self.dsm.split_by_index(train_index, test_index)\n ds_train.info()\n ds_test.info()\n\n ls, ps, cs, best_p, = self.train_manager.train(ds_train, ds_test, nb_epoch=self.epochs, verbose=verbose)\n predictions = self.train_manager.get_test_predictions()\n\n lexical_stats = [x + y for x, y in zip(lexical_stats, ls)]\n prosodic_stats = [x + y for x, y in zip(prosodic_stats, ps)]\n combiner_stats = [x + y for x, y in zip(combiner_stats, cs)]\n best_partition = best_partition + best_p\n\n if self.save_predictions:\n self._save_predictions(ds_test.word_texts, ds_test.shuffle_indexes, predictions, fold=k)\n\n logger.info('\\n---\\n')\n\n if verbose:\n self._show_stats(lexical_stats, prosodic_stats, combiner_stats, best_partition)\n\n def nested_run(self, verbose=True):\n '''\n Nested CV vs Non-Nested:\n http://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html\n http://stats.stackexchange.com/questions/65128/nested-cross-validation-for-model-selection\n http://stats.stackexchange.com/questions/167066/double-nested-wrapper-crossvalidation-final-trained-model\n '''\n # hyperparam to be tuned\n best_p = []\n n_splits = 3\n n_samples = sum(x.nb_texts for x in self.dsm.originals)\n kf = KFold(n_splits=n_splits, shuffle=True)\n placeholder = np.zeros(n_samples)\n\n # Inner CV\n for k, (train_index, val_index) in enumerate(kf.split(placeholder)):\n logger.info('K fold: {}'.format(k + 1))\n logger.info('Train/Test summary: ')\n ds_train, ds_val = self.dsm.split_by_index(train_index, val_index)\n ds_train.info()\n ds_val.info()\n self.train_manager.train(ds_train, ds_test=None, ds_val=ds_val, nb_epoch=10, verbose=verbose)\n best_p.append(self.train_manager.c_instance.best_p)\n\n logger.debug(\"Avg p that max F1: %.2f (%.2f)\" % (np.mean(best_p), np.std(best_p)))\n\n # Outer CV\n self.train_manager.best_p = np.mean(best_p)\n self.run()\n\n def _save_predictions(self, original_texts, original_indexes, predictions, fold=0):\n fname = self.predictions_filename + '-fold_%d' % fold\n dname = self.predictions_dirname\n if isinstance(predictions[0][0], (list, np.ndarray)):\n predictions = list(map(unvectorize, predictions))\n save_to_file(original_texts, original_indexes, predictions, fname=fname, dname=dname, task=self.task)\n\n def _show_stats(self, lexical_stats, prosodic_stats, combiner_stats, best_partition):\n logger.debug(\"Text Precision = %.4f Recall = %.4f F-Measure = %.4f\" % (\n lexical_stats[1] / self.folds, lexical_stats[2] / self.folds, lexical_stats[0] / self.folds))\n logger.debug(\"Audio Precision = %.4f Recall = %.4f F-Measure = %.4f\" % (\n prosodic_stats[1] / self.folds, prosodic_stats[2] / self.folds, prosodic_stats[0] / self.folds))\n logger.debug(\"All Precision = %.4f Recall = %.4f F-Measure = %.4f\" % (\n combiner_stats[1] / self.folds, combiner_stats[2] / self.folds, combiner_stats[0] / self.folds))\n logger.debug('TO CSV: %.4f\\t%.4f\\t%.4f\\t%.4f\\t%.4f\\t%.4f\\t%.4f\\t%.4f\\t%.4f\\t%.1f\\t%.1f' % (\n lexical_stats[1] / self.folds, lexical_stats[2] / self.folds, lexical_stats[0] / self.folds,\n prosodic_stats[1] / self.folds, prosodic_stats[2] / self.folds, prosodic_stats[0] / self.folds,\n combiner_stats[1] / self.folds, combiner_stats[2] / self.folds, combiner_stats[0] / self.folds,\n best_partition / self.folds, 1 - best_partition / self.folds))\n","sub_path":"deepecoachts/deepecoach/models/cv.py","file_name":"cv.py","file_ext":"py","file_size_in_byte":5577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"348006052","text":"import nltk\n\ngrammar = nltk.CFG.fromstring(\"\"\"\n E -> E PLUS T\n E -> T\n T -> T TIMES F\n T -> F\n F -> LPAREN E RPAREN\n F -> ID\n PLUS -> '+'\n TIMES -> '*'\n LPAREN -> '('\n RPAREN -> ')'\n ID -> 'a'\n ID -> 'b'\n ID -> 'c'\n \"\"\")\n\nfor prod in grammar.productions():\n print(prod)\n\nsent = 'a * b + c'.split()\nnltk.app.srparser_app.ShiftReduceApp(grammar, sent).mainloop()\n\n","sub_path":"assets/demos/nltk/sr_expr2.py","file_name":"sr_expr2.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"557302185","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom env.env.env_loader import s5_approach_D\nfrom scipy.interpolate import interp1d\nfrom matplotlib.font_manager import FontProperties\n\nfrom matplotlib import rc\nrc('text', usetex=True)\nimport matplotlib\nmatplotlib.rcParams['mathtext.fontset'] = 'stix'\nmatplotlib.rcParams['font.family'] = 'STIXGeneral'\n\n\n\n\"\"\"\nDescription:\nMake a figure that shows the portion of the track that I use for my data analysis\n\nDate:\n2/1/2021\n\nAuthor: Hunter Akins\n\nInstitution: Scripps Institution of Oceanography, UC San Diego\n\"\"\"\n\n\n#font = FontProperties()\n#font.set_family('serif')\n#font.set_name('Times New Roman')\n\n\ntgrid = np.load('npys/s5_r_tgrid.npy')\nr_km = np.load('npys/s5_r.npy')\ninterp = interp1d(tgrid[:,0], r_km[:,0])\n\nfig,axes = plt.subplots(2,1, sharex=True)\nax = axes[0]\nfor i in range(len(r_km)):\n pt = ax.scatter(tgrid[i], r_km[i], color='k',alpha=0.5,s=5)\nprint(type(pt))\npt.set_label('GPS')\n\nsegments = [(1.6, 16.5), (23.5, 37), (40, 52)]\nlines = []\ncolors = ['r', 'g', 'b']\nlinestyle =['-', 'dashdot', 'dashed']\ni=0\nfor t0, t1 in segments:\n rel_t = np.linspace(t0, t1, 10)\n rel_track = interp(rel_t)\n line, = ax.plot(rel_t, rel_track, color=colors[i], linewidth=2.5, alpha=1, linestyle=linestyle[i])\n lines.append(line)\n i += 1\nletters = ['A', 'B', 'C']\nax.legend([pt] +lines, ['Ship GPS points for S5 event'] + ['Segment ' + str(x) for x in letters])\nax.set_ylabel('Range (km)',fontsize=15)\n\n\n\nbath = np.load('/home/hunter/data/bachman/bachmanDB/extras/s5_bathy.npy')\nax2 = axes[1]\nline, = ax2.plot(bath[0,:]/60, bath[1,:], color='k')\nax2.invert_yaxis()\nax2.set_xlabel('Time (min)', fontsize=15)\nax2.set_ylabel('Depth at source (m)', fontsize=15)\n\nax.set_ylim([0.5, 9])\nax2.legend(['Water column depth at source location'])\nax.text(5, 8.5*0.1, 'a)', fontsize = 15)\nax2.set_ylim([280, 165])\nax2.text(5, 280 - (280-165)*0.1, 'b)', fontsize=15)\nax2.set_xlim([0, 75])\n#ax2.text(0, 1, 'b)')\n\nfig.set_size_inches(6,6)\nplt.savefig('/home/hunter/research/coherent_matched_field/paper/pics/shiptrack.png', dpi=500)\n\nplt.show()\n","sub_path":"ship/make_s5_track_fig.py","file_name":"make_s5_track_fig.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"173175818","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nUsage: \r\npython app.py \r\n\"\"\"\r\nfrom app import InstagramScraper\r\nfrom InstagramAPI import InstagramAPI\r\nfrom mongotools import MongoTools\r\nimport tqdm\r\nimport concurrent.futures\r\n\r\nInstagramAPI = InstagramAPI(\"justexplorehaha\", \"biu1biu2biu3\")\r\nMongoTools = MongoTools()\r\nInstagramAPI.login() # login\r\nresult = InstagramAPI.getSelfUsersFollowing()\r\ntotal = 0\r\nwhile result:\r\n # with open('measurements.json', 'w') as f:\r\n # f.write(json.dumps(InstagramAPI.LastJson, sort_keys=True, indent=4))\r\n for i in InstagramAPI.LastJson.get('users'):\r\n MongoTools.insertUser(i)\r\n count = len(InstagramAPI.LastJson.get('users'))\r\n total = total + count\r\n next=InstagramAPI.LastJson.get('next_max_id')\r\n result = InstagramAPI.getUserFollowings(InstagramAPI.username_id, next)\r\nprint(total)\r\n\r\nfor i in MongoTools.getUsers():\r\n print(i[\"username\"])\r\n scraper = InstagramScraper(i[\"username\"])\r\n scraper.crawl()\r\n\r\n for future in tqdm.tqdm(concurrent.futures.as_completed(scraper.future_to_item), total=len(scraper.future_to_item), desc='Downloading'):\r\n item = scraper.future_to_item[future]\r\n\r\n if future.exception() is not None:\r\n print('%r generated an exception: %s') % (item['id'], future.exception())","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"328244476","text":"from aws_cdk import core\nfrom aws_cdk import aws_s3 as _s3\n\nclass MyFirstCdkProjectStack(core.Stack):\n\n def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:\n super().__init__(scope, construct_id, **kwargs)\n\n # The code that defines your stack goes here\n\n _s3.Bucket(\n self,\n \"myBucketId\",\n bucket_name=\"myfirstcdkproject0101\",\n versioned=True,\n encryption=_s3.BucketEncryption.KMS_MANAGED\n )\n","sub_path":"my_first_cdk_project/my_first_cdk_project_stack.py","file_name":"my_first_cdk_project_stack.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"129073598","text":"\"\"\"empty message\n\nRevision ID: 21808a470526\nRevises: bf8a1557b052\nCreate Date: 2016-08-02 16:54:50.782946\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '21808a470526'\ndown_revision = 'bf8a1557b052'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('project')\n op.add_column('category', sa.Column('name', sa.String(), nullable=False))\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('category', 'name')\n op.create_table('project',\n sa.Column('id', sa.INTEGER(), nullable=False),\n sa.PrimaryKeyConstraint('id', name='project_pkey')\n )\n ### end Alembic commands ###\n","sub_path":"migrations/versions/21808a470526_.py","file_name":"21808a470526_.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"609761440","text":"# SPDX-FileCopyrightText: 2017 Tony DiCola for Adafruit Industries\n# SPDX-FileCopyrightText: 2017 James DeVito for Adafruit Industries\n# SPDX-License-Identifier: MIT\n\n# This example is for use on (Linux) computers that are using CPython with\n# Adafruit Blinka to support CircuitPython libraries. CircuitPython does\n# not support PIL/pillow (python imaging library)!\nimport math\nimport time\nimport subprocess\nimport Adafruit_GPIO.SPI as SPI\n#from board import SCL, SDA\n#import busio\nfrom PIL import Image, ImageDraw, ImageFont\nimport Adafruit_SSD1306\n# Create the I2C interface.\n# i2c = busio.I2C(SCL, SDA)\n# Create the SSD1306 OLED class.\n# The first two parameters are the pixel width and pixel height. Change these\n# to the right size for your display!\n# Raspberry Pi pin configuration:\nRST = None # on the PiOLED this pin isnt used\n# Note the following are only used with SPI:\nDC = 23\nSPI_PORT = 0\nSPI_DEVICE = 0\n\n\n\n#disp = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)\ndisp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)\n\n# Initialize library.\ndisp.begin()\n\n# Clear display.\ndisp.clear()\ndisp.display()\n\n\n# Clear display.\n# disp.fill(0)\n# disp.show()\n\n# Create blank image for drawing.\n# Make sure to create image with mode '1' for 1-bit color.\nwidth = disp.width\nheight = disp.height\nimage = Image.new(\"1\", (width, height))\n\n# Get drawing object to draw on image.\ndraw = ImageDraw.Draw(image)\n# Draw a black filled box to clear the image.\ndraw.rectangle((0, 0, width, height), outline=0, fill=0)\n# Load default font.\n#font = ImageFont.load_default()\n#font = ImageFont.truetype(\"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf\", 28)\n\nfont = ImageFont.truetype(\"DejaVuSans.ttf\", 16)\n\n\n# Draw text.\n\ndraw.text((0, 32), \"Hi, MBTech!\", font=font, fill=255)\n\n\nfont = ImageFont.truetype(\"DejaVuSans.ttf\", 22)\n\ndraw.text((0, 5), \"MBTECH\", font=font, fill=255)\n # Display image.\ndisp.image(image)\ndisp.display()\n# Pause briefly before drawing next frame.\ntime.sleep(3)\n\n\n\n\n\nfont = ImageFont.load_default()\n# Draw some shapes.\n# First define some constants to allow easy resizing of shapes.\npadding = -2\ntop = padding\nbottom = height - padding\n# Move left to right keeping track of the current x position for drawing shapes.\nx = 0\nwhile True:\n # Draw a black filled box to clear the image.\n draw.rectangle((0, 0, width, height), outline=0, fill=0)\n\n # Shell scripts for system monitoring from here:\n # https://unix.stackexchange.com/questions/119126/command-to-display-memory-usage-disk-usage-and-cpu-load\n cmd = \"hostname -s | cut -d\\' \\' -f1\"\n HOSTN = subprocess.check_output(cmd, shell=True).decode(\"utf-8\")\n cmd = \"hostname -I | cut -d' ' -f1\"\n IP = subprocess.check_output(cmd, shell=True).decode(\"utf-8\")\n cmd = \"top -bn1 | grep load | awk '{printf \\\"CPU Load: %.2f\\\", $(NF-2)}'\"\n CPU = subprocess.check_output(cmd, shell=True).decode(\"utf-8\")\n cmd = \"free -m | awk 'NR==2{printf \\\"Mem: %s/%s MB %.2f%%\\\", $3,$2,$3*100/$2 }'\"\n MemUsage = subprocess.check_output(cmd, shell=True).decode(\"utf-8\")\n cmd = 'df -h | awk \\'$NF==\"/\"{printf \"Disk: %d/%d GB %s\", $3,$2,$5}\\''\n Disk = subprocess.check_output(cmd, shell=True).decode(\"utf-8\")\n\n # Write four lines of text.\n \n\n font = ImageFont.truetype(\"DejaVuSans.ttf\", 22)\n # draw.text((30, 0), \"MBTECH\", font=font, fill=255)\n draw.text((2, 0), HOSTN, font=font, fill=255)\n \n font = ImageFont.load_default()\n \n # draw.text((20, top + 16), HOSTN, font=font, fill=255) \n draw.text((x, top + 28), \"IP: \" + IP, font=font, fill=255)\n draw.text((x, top + 38), CPU, font=font, fill=255)\n draw.text((x, top + 46), MemUsage, font=font, fill=255)\n draw.text((x, top + 56), Disk, font=font, fill=255)\n\n # Display image.\n disp.image(image)\n disp.display()\n time.sleep(0.1)\n","sub_path":"pi_stats3.py","file_name":"pi_stats3.py","file_ext":"py","file_size_in_byte":3798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"579590053","text":"from flask import Flask, request, redirect,g, url_for, render_template\nfrom flask import session as login_session\nimport os, requests, json\nimport urllib as urllibparse\nimport base64\nfrom urlparse import urlparse\nfrom databases import *\napp = Flask(__name__)\n\n@app.route('/')\ndef quote():\n\tdef extract_urls(text):\n\t out = []\n\t for word in text.split(' '):\n\t thing = urlparse(word.strip())\n\t if thing.scheme:\n\t out.append(word)\n\t return out\n\theaders= {'Accept': 'application/hal+json'}\n\tresponse = requests.get(\"https://tronalddump.io/random/quote\", headers=headers)\n\tparsed_content = json.loads(response.content)\n\tquote = parsed_content[\"value\"]\n\tquote1 = quote\n\torg_url = parsed_content[\"_embedded\"][\"source\"][0][\"url\"]\n\torg_url1=org_url\n\t#quote += \" https://twitter.com/realDonaldTrump/status/770330631783972868 \"\n\tlink = ''\n\tmedia = ''\n\thashtags = []\n\tht = ''\n\tafter_ht = False\n\thashtag = ''\n\t\n\tif extract_urls(quote)!=[]:\n\t \tlink = extract_urls(quote)[0]\n\tif (link[:27]==\"https://twitter.com/i/status\" or link[:26]=='https://pbs.twimg.com/media'):\n\t\tmedia = link\n\tfor i in quote:\n\t\tif after_ht == True:\n\t\t\tht += i\n\n\t\tif i=='#':\n\t\t\tafter_ht = True\n\t\telif i==' ':\n\t\t\tafter_ht = False\n\t\t\thashtags.append(ht)\n\t\t\tht=''\n\tif (hashtags!=[]):\n\t\thashtag = hashtags[0]\n\torg_url\n\thashtag1=hashtag\n\n\tif(hashtag1!='' and media!=''):\n\t\tadd_quote(quote1, hashtag1, media, org_url)\n\telif(hashtag1=='' and media!=''):\n\t\tadd_quote(quote1, ' ', media, org_url)\n\telif(hashtag1!='' and media==''):\n\t\tadd_quote(quote1, hashtag1, ' ', org_url)\n\telse:\n\t\tadd_quote(quote1, ' ', ' ', org_url)\n\n\treturn render_template(\"index.html\", quote=quote, org_url=org_url, media=media, hashtag=hashtag)\n\n@app.route('/history')\ndef history():\n\tprint_all()\n\tquotes_parsed = query_all()\n\tquotes =[]\n\tlinks = []\n\thashtags = []\n\tmedia = []\n\thashtag_links = []\n\tfor i in quotes_parsed:\n\t\tquotes.append(i.quote)\n\t\tlinks.append(i.link)\n\t\thashtags.append(i.hashtag)\n\t\tmedia.append(i.media)\n\t\thashtag_links.append(\"https://twitter.com/hashtag/\"+i.hashtag+\"?src=hash\")\n\t\n\tif len(links)!=1 and len(links)!=2:\n\t\tif (len(links)%2==0):\n\t\t\tquotes_len = int(len(links)/2)\n\t\telse:\n\t\t\tquotes_len = int(len(links)/2)+1\n\telif len(links)==2:\n\t\tquotes_len=1\n\telse:\n\t\tquotes_len = 0\n\n\treturn render_template(\"results.html\",quotes=quotes,links=links, hashtags=hashtags, media=media, hashtag_links=hashtag_links, quotes_len=quotes_len)\n\n@app.route('/del_quotes')\ndef del_quotes():\n\tdel_all_quotes()\n\tquotes_parsed = query_all()\n\tquotes =[]\n\tlinks = []\n\thashtags = []\n\tmedia = []\n\thashtag_links = []\n\tfor i in quotes_parsed:\n\t\tquotes.append(i.quote)\n\t\tlinks.append(i.link)\n\t\thashtags.append(i.hashtag)\n\t\tmedia.append(i.media)\n\t\thashtag_links.append(\"https://twitter.com/hashtag/\"+i.hashtag+\"?src=hash\")\n\t\n\tif len(links)!=1 and len(links)!=2:\n\t\tif (len(links)%2==0):\n\t\t\tquotes_len = int(len(links)/2)\n\t\telse:\n\t\t\tquotes_len = int(len(links)/2)+1\n\telif len(links)==2:\n\t\tquotes_len=1\n\telse:\n\t\tquotes_len = 0\n\n\treturn render_template(\"results.html\",quotes=quotes,links=links, hashtags=hashtags, media=media, hashtag_links=hashtag_links, quotes_len=quotes_len)\n\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n ","sub_path":"projectYL/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"613817606","text":"from __future__ import annotations\n\nimport sys\n\nif sys.version_info >= (3, 8):\n from typing import Literal\nelse:\n from typing_extensions import Literal\n\nfrom rich.console import Console, ConsoleOptions, RenderableType\nfrom rich.segment import Segment\n\nfrom ..widget import Widget, Reactive\nfrom ..geometry import Point, Dimensions\nfrom ..scrollbar import VerticalBar\n\nScrollMethod = Literal[\"always\", \"never\", \"auto\", \"overlay\"]\n\n\nclass Window(Widget):\n def __init__(\n self, renderable: RenderableType, y_scroll: ScrollMethod = \"always\"\n ) -> None:\n self.renderable = renderable\n self.y_scroll = y_scroll\n self._virtual_size: Dimensions | None = None\n self._renderable_updated = True\n self._lines: list[list[Segment]] = []\n super().__init__()\n\n position: Reactive[int] = Reactive(60)\n show_vertical_bar: Reactive[bool] = Reactive(True)\n\n @property\n def virtual_size(self) -> Dimensions:\n return self._virtual_size or self.size\n\n def require_repaint(self) -> None:\n del self._lines[:]\n return super().require_repaint()\n\n def get_lines(\n self, console: Console, options: ConsoleOptions\n ) -> list[list[Segment]]:\n if not self._lines:\n width = self.size.width\n if self.show_vertical_bar and self.y_scroll != \"overlay\":\n width -= 1\n self._lines = console.render_lines(\n self.renderable, options.update_width(width)\n )\n return self._lines\n\n def update(self, renderable: RenderableType) -> None:\n self.renderable = renderable\n del self._lines[:]\n\n def render(self, console: Console, options: ConsoleOptions) -> RenderableType:\n height = options.height or console.height\n lines = self.get_lines(console, options)\n\n return VerticalBar(\n lines[self.position : self.position + height],\n height,\n len(lines),\n self.position,\n overlay=self.y_scroll == \"overlay\",\n )\n","sub_path":"src/textual/widgets/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"646846748","text":"from flask import Flask\nfrom flask_restful import Resource, Api\nimport requests\nimport nltk\n\napp = Flask(__name__)\napi = Api(app)\n\n\nclass MeetupEvents(Resource):\n def get(self):\n r = requests.get(\n 'https://api.meetup.com/find/upcoming_events?photo-host=public&page=20&sig_id=11127355&sig=50cafaa0a03571e532062f5ebf355cdab6c1b413')\n events = r.json()\n document = events[\"events\"][0][\"description\"]\n print(document)\n sentences = nltk.sent_tokenize(document)\n sentences = [nltk.word_tokenize(sent) for sent in sentences]\n sentences = [nltk.pos_tag(sent) for sent in sentences]\n nouns = []\n for sentance in sentences:\n nouns.append([word for word, pos in sentance\n if (pos == 'NN' or pos == 'NNP' or pos == 'NNS' or pos == 'NNPS' or pos == \"VB\" or pos == \"VBD\" or pos == \"VBG\" or pos == \"VBN\") and len(word) > 3])\n return nouns\n\n\napi.add_resource(MeetupEvents, '/')\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"server/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"432336803","text":"\"\"\"Python client for Sift Science's API.\nSee: https://siftscience.com/docs/references/events-api\n\"\"\"\n\nimport json\nimport logging\nimport requests\nimport traceback\nimport sys\nif sys.version_info[0] < 3:\n import urllib\nelse:\n import urllib.parse as urllib\n\nimport sift\nfrom . import version\n\nAPI_URL = 'https://api.siftscience.com'\nlogging.basicConfig()\nsift_logger = logging.getLogger('sift_client')\n\n\nclass Client(object):\n def __init__(self, api_key = None, api_url=API_URL, timeout=2.0):\n \"\"\"Initialize the client.\n\n Args:\n api_key: Your Sift Science API key associated with your customer\n account. You can obtain this from\n https://siftscience.com/quickstart\n api_url: The URL to send events to.\n timeout: Number of seconds to wait before failing request. Defaults\n to 2 seconds.\n \"\"\"\n if not isinstance(api_url, str) or len(api_url.strip()) == 0:\n raise RuntimeError(\"api_url must be a string\")\n\n if api_key is None:\n api_key = sift.api_key\n\n if not isinstance(api_key, str) or len(api_key.strip()) == 0:\n raise RuntimeError(\"valid api_key is required\")\n\n self.api_key = api_key\n self.url = api_url + '/v%s' % version.API_VERSION\n self.timeout = timeout\n if sys.version_info[0] < 3:\n self.UNICODE_STRING = basestring\n else:\n self.UNICODE_STRING = str\n\n def user_agent(self):\n return 'SiftScience/v%s sift-python/%s' % (version.API_VERSION, version.VERSION)\n\n def event_url(self):\n return self.url + '/events'\n\n def score_url(self, user_id):\n return self.url + '/score/%s' % urllib.quote(user_id)\n\n def label_url(self, user_id):\n return self.url + '/users/%s/labels' % urllib.quote(user_id)\n\n def track(self, event, properties, path=None, return_score=False, timeout = None):\n \"\"\"Track an event and associated properties to the Sift Science client.\n This call is blocking. Check out https://siftscience.com/resources/references/events_api\n for more information on what types of events you can send and fields you can add to the\n properties parameter.\n\n Args:\n event: The name of the event to send. This can either be a reserved\n event name such as \"$transaction\" or \"$create_order\" or a custom event\n name (that does not start with a $).\n properties: A dict of additional event-specific attributes to track\n return_score: Whether the API response should include a score for this \n user (the score will be calculated using this event). This feature must be\n enabled for your account in order to use it. Please contact\n support@siftscience.com if you are interested in using this feature.\n Returns:\n A requests.Response object if the track call succeeded, otherwise\n a subclass of requests.exceptions.RequestException indicating the\n exception that occurred.\n \"\"\"\n if not isinstance(event, self.UNICODE_STRING) or len(event.strip()) == 0:\n raise RuntimeError(\"event must be a string\")\n\n if not isinstance(properties, dict) or len(properties) == 0:\n raise RuntimeError(\"properties dictionary may not be empty\")\n\n headers = { 'Content-type' : 'application/json',\n 'Accept' : '*/*',\n 'User-Agent' : self.user_agent() }\n\n if path is None:\n path = self.event_url()\n\n if timeout is None:\n timeout = self.timeout\n\n properties.update({ '$api_key': self.api_key, '$type': event })\n params = {}\n if return_score:\n params.update({ 'return_score' : return_score })\n try:\n response = requests.post(path, data=json.dumps(properties),\n headers=headers, timeout=timeout, params=params)\n return Response(response)\n except requests.exceptions.RequestException as e:\n sift_logger.warn('Failed to track event: %s' % properties)\n sift_logger.warn(traceback.format_exception_only(type(e), e))\n\n return e\n\n def score(self, user_id, timeout = None):\n \"\"\"Retrieves a user's fraud score from the Sift Science API.\n This call is blocking. Check out https://siftscience.com/resources/references/score_api.html\n for more information on our Score response structure\n\n Args:\n user_id: A user's id. This id should be the same as the user_id used in\n event calls.\n Returns:\n A requests.Response object if the score call succeeded, otherwise\n a subclass of requests.exceptions.RequestException indicating the\n exception that occurred.\n \"\"\"\n if not isinstance(user_id, self.UNICODE_STRING) or len(user_id.strip()) == 0:\n raise RuntimeError(\"user_id must be a string\")\n\n if timeout is None:\n timeout = self.timeout\n\n headers = { 'User-Agent' : self.user_agent() }\n params = { 'api_key': self.api_key }\n\n try:\n response = requests.get(self.score_url(user_id),\n headers=headers, timeout=timeout, params=params)\n return Response(response)\n except requests.exceptions.RequestException as e:\n sift_logger.warn('Failed to get score for user %s' % user_id)\n sift_logger.warn(traceback.format_exception_only(type(e), e))\n\n return e\n\n def label(self, user_id, properties, timeout = None):\n \"\"\"Labels a user as either good or bad through the Sift Science API.\n This call is blocking. Check out https://siftscience.com/resources/references/labels_api.html\n for more information on what fields to send in properties.\n\n Args:\n user_id: A user's id. This id should be the same as the user_id used in\n event calls.\n properties: A dict of additional event-specific attributes to track\n timeout(optional): specify a custom timeout for this call\n Returns:\n A requests.Response object if the label call succeeded, otherwise\n a subclass of requests.exceptions.RequestException indicating the\n exception that occurred.\n \"\"\"\n if not isinstance(user_id, self.UNICODE_STRING) or len(user_id.strip()) == 0:\n raise RuntimeError(\"user_id must be a string\")\n\n return self.track('$label', properties, self.label_url(user_id), timeout=timeout)\n\n def unlabel(self, user_id, timeout = None):\n \"\"\"unlabels a user through the Sift Science API.\n This call is blocking. Check out https://siftscience.com/resources/references/labels_api.html\n for more information.\n\n Args:\n user_id: A user's id. This id should be the same as the user_id used in\n event calls.\n timeout(optional): specify a custom timeout for this call\n Returns:\n A requests.Response object if the unlabel call succeeded, otherwise\n a subclass of requests.exceptions.RequestException indicating the\n exception that occurred.\n \"\"\"\n if not isinstance(user_id, self.UNICODE_STRING) or len(user_id.strip()) == 0:\n raise RuntimeError(\"user_id must be a string\")\n\n if timeout is None:\n timeout = self.timeout\n\n headers = { 'User-Agent' : self.user_agent() }\n params = { 'api_key': self.api_key }\n\n try:\n\n response = requests.delete(self.label_url(user_id),\n headers=headers, timeout=timeout, params=params)\n return Response(response)\n\n except requests.exceptions.RequestException as e:\n sift_logger.warn('Failed to unlabel user %s' % user_id)\n sift_logger.warn(traceback.format_exception_only(type(e), e))\n\n return e\n\n\n\nclass Response(object):\n\n HTTP_CODES_WITHOUT_BODY = [204, 304]\n\n def __init__(self, http_response):\n\n # Set defaults.\n self.body = None\n self.request = None\n self.api_status = None\n self.api_error_message = None\n self.http_status_code = http_response.status_code\n self.url = http_response.url\n\n if (self.http_status_code not in self.HTTP_CODES_WITHOUT_BODY) \\\n and 'content-length' in http_response.headers:\n self.body = http_response.json()\n self.api_status = self.body['status']\n self.api_error_message = self.body['error_message']\n if 'request' in self.body.keys() \\\n and isinstance(self.body['request'], str):\n self.request = json.loads(self.body['request'])\n else:\n self.request = None\n\n def __str__(self):\n return ('{%s \"http_status_code\": %s}' %\n ('' if self.body == None else '\"body\": ' +\n json.dumps(self.body) + ',', str(self.http_status_code)))\n\n def is_ok(self):\n\n if self.http_status_code in self.HTTP_CODES_WITHOUT_BODY:\n return 204 == self.http_status_code\n\n return self.api_status == 0\n\n\n","sub_path":"sift/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":9285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"538586565","text":"\"\"\"\nThe main point of this module is the 'enforce' method.\n\nNOTE: Lot's of meta-stuff here causing mypy errors.\nSeems rather difficult to avoid, but I think as long\nas it's contained to just this file, it should be ok.\n\"\"\"\nfrom abc import ABCMeta\nfrom mtots import test\nfrom mtots.util.dataclasses import dataclass\nfrom typing import Tuple\nfrom typing import Type\nfrom typing import TypeVar\nimport functools\nimport typing\n\n\nT = typing.TypeVar('T')\n\n\ndef enforce(cls: typing.Type[T]) -> typing.Type[T]:\n if hasattr(cls, '__annotations__'):\n init = cls.__init__\n @functools.wraps(init)\n def _check(self, *args, **kwargs) -> None: # type: ignore\n init(self, *args, **kwargs) # type: ignore\n # Choosing get_type_hints, rather than cls.__annotations__ has\n # the advantage that ForwardRefs are resolved.\n annotations = typing.get_type_hints(cls) # type: ignore\n items = annotations.items() # type: ignore\n for field_name, field_type in items: # type: ignore\n field_val = getattr(self, field_name) # type: ignore\n if not _isinstance(field_val, field_type): # type: ignore\n raise TypeError(\n f'Expected field {repr(field_name)} ' # type: ignore\n f'of {cls} to be {field_type} but got '\n f'{repr(field_val)}')\n cls.__init__ = _check # type: ignore\n return cls\n\n\ndef _get_type_args(type_: type) -> Tuple[type, ...]:\n # WARNING: '...__args__' field for typing annotation\n # types is undocumented\n return type_.__args__ # type: ignore\n\n\ndef _is_generic(type_: type, *origin_types: object) -> bool:\n # This isn't perfect, esp since if we see a meta-class that isn't\n # whitelisted here, we assume it is a special typing type.\n\n # We allow for multiple origin types, since 3.6, and 3.7+ have\n # generally different values for these.\n # In 3.6, the __origin__ types are generally the typing.*\n # classes (e.g. Tuple[int].__origin__ is Tuple)\n # In 3.7+, the real types are used generally whenever possible\n # (e.g. Tuple[int].__origin__ is tuple).\n return (\n hasattr(type_, '__origin__') and\n type_.__origin__ in origin_types # type: ignore\n )\n\n\ndef _isinstance(obj: object, type_: type) -> bool:\n if _is_generic(type_, tuple, typing.Tuple):\n if not isinstance(obj, tuple):\n return False\n args = _get_type_args(type_)\n if args[-1] == Ellipsis:\n subtype, _ellipsis = args\n return all(_isinstance(x, subtype) for x in obj)\n else:\n return (\n len(obj) == len(args) and\n all(_isinstance(x, t) # type: ignore\n for x, t in zip(obj, args)) # type: ignore\n )\n if _is_generic(type_, dict, typing.Dict):\n ktype, vtype = _get_type_args(type_)\n return (\n isinstance(obj, dict) and\n all(\n _isinstance(k, ktype) and _isinstance(v, vtype)\n for k, v in obj.items()\n )\n )\n if _is_generic(type_, list, typing.List):\n typearg, = _get_type_args(type_)\n return (\n isinstance(obj, list) and\n all(_isinstance(x, typearg) for x in obj)\n )\n if _is_generic(type_, typing.Union):\n args = _get_type_args(type_)\n return any(_isinstance(obj, t) for t in args)\n return isinstance(obj, type_)\n\n\n@test.case\ndef test_enforce() -> None:\n\n @enforce\n @dataclass(frozen=True)\n class Foo:\n a: int\n\n @enforce\n @dataclass(frozen=True)\n class Bar(Foo):\n b: str\n\n @test.throws(TypeError)\n def for_Foo() -> None:\n Foo('a') # type: ignore\n\n Foo(5)\n\n @test.throws(TypeError)\n def for_Bar() -> None:\n Bar(5, 5) # type: ignore\n\n Bar(123, 'abc')\n","sub_path":"mtots/util/enforcer.py","file_name":"enforcer.py","file_ext":"py","file_size_in_byte":3920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"522641013","text":"# Public functions included:\n#\n# 1. extractTriplets_real(PATH_TDI,PATHorFILE_triplets)\n\n# 2. extractTriplets_rand(PATH_TDI_rand,PATH_triplets_rand)\n\n# 3. extractTriplets_singleSGA(PATH_TDI_singleSGA,PATH_triplets_singleSGA)\n\n# 4. determinePosteriorThd_parallel(PATH_randTriplets_in,FILE_SGAMatrix_in,FILE_threshold_out, sig=0.05)\n\n# 5. filterTriplets(FILEorPATH_in, FILE_threshold, FILEorPATH_out)\n\n# 6. determinePosteriorThd (PATH_randTriplets_in,FILE_SGAMatrix_in,FILE_threshold_out,start=1, end=999, sig=0.05)\n\nif 'os' not in dir():\n import os\nif 'time' not in dir():\n import time\nif 'pd' not in dir():\n import pandas as pd\nif 'mp' not in dir():\n import multiprocessing as mp\nif 'np' not in dir():\n import numpy as np\nif 're' not in dir():\n import re\nif 'sys' not in dir():\n import sys\n\n\nclass Timer:\n def __init__(self):\n self.start = time.time()\n\n def restart(self):\n self.start = time.time()\n\n def get_time_hhmmss(self):\n end = time.time()\n m, s = divmod(end - self.start, 60)\n h, m = divmod(m, 60)\n time_str = \"%02d:%02d:%02d\" % (h, m, s)\n return time_str\n\n\ndef getTopGtpostprob_parallel(PATH_TDI, FILE):\n df = pd.read_csv(PATH_TDI + FILE, index_col=0)\n tumor = FILE[:-4] # remove '.csv'\n TSDPs = []\n for col in df:\n topIdx = df[col].idxmax()\n SGA = topIdx\n DEG = col\n postprob = df[col].loc[topIdx]\n TSDP = [tumor, SGA, DEG, postprob]\n TSDPs.append(TSDP)\n return TSDPs\n\n\ndef outputTriplets(triplets, PATHNAME_triplet):\n df_triplets = pd.DataFrame(data=triplets,\n columns=['patient_name', 'cause_gene_name', 'result_gene_name', 'posterior'])\n df_triplets.to_csv(PATHNAME_triplet, index=False)\n\ndef extractTriplets_parallel(PATH_TDI,FILE_triplets):\n\n num_cores = mp.cpu_count()\n pool = mp.Pool() # defalut is num_cores == pool = mp.Pool(num_cores)\n\n # triplets = [pool.apply_async( getTopGtpostprob_parallel, args=(PATH_TDI,FILE) ) for FILE in os.listdir(PATH_TDI))]\n results = []\n for FILE in os.listdir(PATH_TDI):\n results.append(pool.apply_async(getTopGtpostprob_parallel, args=(PATH_TDI, FILE)))\n\n triplets = []\n for result in results:\n triplet = result.get()\n triplets += triplet\n\n outputTriplets(triplets, FILE_triplets)\n\ndef extractTriplets(PATH_TDI, FILEorPATH_triplets):\n my_timer = Timer()\n FILE_Triplets = \"\"\n if PATH_TDI[-1] != \"\\\\\" and PATH_TDI[-1] != \"/\":\n PATH_TDI += \"/\"\n\n if FILEorPATH_triplets[-4:] == \".csv\":\n FILE_Triplets = FILEorPATH_triplets\n else:\n if FILEorPATH_triplets[-1] != \"\\\\\" and FILEorPATH_triplets[-1] != \"/\":\n FILEorPATH_triplets += \"/\"\n FILE_Triplets = FILEorPATH_triplets+\"Triplets.csv\"\n\n print(\"Extracting triplets from \" + PATH_TDI + \"...\")\n extractTriplets_parallel(PATH_TDI,FILE_Triplets)\n print(\"Triplet has been extracted successfully! \")\n\n\n time_hhmmss = my_timer.get_time_hhmmss()\n print(\"Total time elapsed: %s\\n\" % time_hhmmss)\n\ndef extractTriplets_rand(path_in, path_out, start=1, end=999):\n my_timer = Timer()\n\n if path_in[-1] != \"\\\\\" and path_in[-1] != \"/\":\n path_in += \"/\"\n if path_out[-1] != \"\\\\\" and path_out[-1] != \"/\":\n path_out += \"/\"\n\n dirList = os.listdir(path_in)\n \n dirList_sorted = sorted(dirList, key=lambda x: (int(re.sub('\\D', '', x)), x))\n count = 0\n for item in dirList_sorted:\n if os.path.isfile(path_in + item ): #given the specific rand path in path_in\n #get the rand number\n randnum = int(re.sub('\\D', '', path_in[path_in.rfind('/')+1:]))\n print(\"Extracting triplets from \" + path_in + \"...\")\n extractTriplets_parallel(path_in, path_out + \"Triplets_rand\" + str(randnum) +\".csv\" )\n print(\"Triplets_rand\" + str(randnum) +\".csv\" + \" has been successfully extracted to \" + path_out)\n break\n else:\n count += 1\n if count < start:\n continue\n if count > end:\n break\n print(\"Extracting triplets from \" + path_in + item + \"...\")\n extractTriplets_parallel(path_in + item + \"/\", path_out + \"Triplets_rand\" + str(count) +\".csv\")\n print(\"triplet_rand\" + str(count) +\".csv\" + \" has been successfully extracted to \" + path_out + \"\\n\")\n\n time_hhmmss = my_timer.get_time_hhmmss()\n print(\"Total time elapsed: %s\\n\" % time_hhmmss)\n\ndef extractTriplets_singleSGA(path_in, path_out, SGAs=\"\"):\n my_timer = Timer()\n\n if path_in[-1] != \"\\\\\" and path_in[-1] != \"/\":\n path_in += \"/\"\n if path_out[-1] != \"\\\\\" and path_out[-1] != \"/\":\n path_out += \"/\"\n\n if SGAs == '':\n for item in os.listdir(path_in):\n print(\"Extracting triplets from \" + path_in + item + \"...\")\n extractTriplets_parallel(path_in + item + \"/\", path_out + \"triplet.\" + item + \".csv\")\n print(item + \".csv\" + \" has been successfully extracted to \" + path_out + \"\\n\")\n else: #SGAs is a one or multiple SGAs separated by comma\n l_SGAs = SGAs.split(',')\n for item in l_SGAs:\n print(\"Extracting triplets from \" + path_in + item + \"...\")\n extractTriplets_parallel(path_in + item + \"/\", path_out + \"triplet.\" + item + \".csv\")\n print(item + \".csv\" + \" has been successfully extracted to \" + path_out + \"\\n\")\n\n time_hhmmss = my_timer.get_time_hhmmss()\n print(\"Total time elapsed: %s\\n\" % time_hhmmss)\n\ndef getHistCount_parallel(PATH_randTriplets_in,file,bins):\n if PATH_randTriplets_in[-1] != \"\\\\\" and PATH_randTriplets_in[-1] != \"/\":\n PATH_randTriplets_in += \"/\"\n df = pd.read_csv(PATH_randTriplets_in + file)\n dict_SGAhist = {}\n for SGA, group in df.groupby(\"cause_gene_name\")['posterior']:\n count, bins_pp = np.histogram(group,bins)\n dict_SGAhist[SGA]=count\n df_hist = pd.DataFrame(dict_SGAhist)#rows are bins, columns are SGA\n return df_hist\n\ndef determinePosteriorThd_parallel(PATH_randTriplets_in,FILE_SGAMatrix_in,FILE_threshold_out, sig=0.05):\n my_timer = Timer()\n print(\"Processing ....\" ) \n bins = np.linspace(0, 1, num=1001)\n pool = mp.Pool() # defalut is num_cores == pool = mp.Pool(num_cores)\n results = []\n for file in os.listdir(PATH_randTriplets_in):\n results.append(pool.apply_async(getHistCount_parallel, args=(PATH_randTriplets_in,file,bins)))\n \n df_hist_total = pd.DataFrame()\n for result in results:\n df_hist = result.get()\n df_hist_total = df_hist_total.add(df_hist, fill_value=0)\n\n # normalize the count of each column(SGA)\n df_norm = df_hist_total / df_hist_total.sum()\n # calculate the CDF of each column(SGA)\n df_CDF = df_norm.cumsum()\n # set index of df_CDF to the smaller side of bin, so we choose bins[:-1]\n df_CDF.index = bins[:-1]\n # get the index of threshold for each column(SGA)\n # this is a seriers with index of SGAs and value of bins\n SGA_thd = abs(df_CDF - (1 - sig)).idxmin()\n SGA_thd = SGA_thd.round(3)\n # Get the total SGA names of SGAMatrix\n # read first line of SGAMatrix to get SGA name list\n if \"csv\" not in dir():\n import csv\n with open(FILE_SGAMatrix_in, 'r') as f:\n reader = csv.reader(f)\n SGAs = next(reader)[1:] # line start from comma\n # convert SGAs list to pandas dataframe\n df_SGAthd = pd.DataFrame(SGAs, columns=['SGA'])\n df_SGAthd['PostProbcutoff'] = df_SGAthd['SGA'].map(SGA_thd).fillna(1)\n\n df_SGAthd.to_csv(FILE_threshold_out, index=False)\n print(\"Process finished successfully\")\n time_hhmmss = my_timer.get_time_hhmmss()\n print(\"Total time elapsed: %s\\n\" % time_hhmmss)\n \ndef determinePosteriorThd(PATH_randTriplets_in,FILE_SGAMatrix_in,FILE_threshold_out,start=1, end=999, sig=0.05):\n my_timer = Timer()\n print(\"Processing ....\")\n bins = np.linspace(0,1,num=1001)\n\n df_hist_total = pd.DataFrame()\n files = os.listdir(PATH_randTriplets_in)\n # sort file name by it's digital number\n files_sorted = sorted(files, key=lambda x: (int(re.sub('\\D', '', x)), x)) # replace all non-digits to empty, then convert to int\n filecount = 0\n for file in files_sorted:\n filecount += 1\n if filecount < start:\n continue\n if filecount > end:\n break\n df = pd.read_csv(PATH_randTriplets_in + file)\n\n dict_SGAhist = {}\n for SGA, group in df.groupby(\"cause_gene_name\")['posterior']:\n count, bins_pp = np.histogram(group,bins)\n dict_SGAhist[SGA]=count\n\n df_hist = pd.DataFrame(dict_SGAhist)#rows are bins, columns are SGA\n #add dataframe of each cell by column(SGA), fill the difference with 0\n df_hist_total = df_hist_total.add(df_hist, fill_value=0)\n\n #normalize the count of each column(SGA)\n df_norm = df_hist_total/df_hist_total.sum()\n #calculate the CDF of each column(SGA)\n df_CDF = df_norm.cumsum()\n #set index of df_CDF to the smaller side of bin, so we choose bins[:-1]\n df_CDF.index = bins[:-1]\n #get the index of threshold for each column(SGA)\n # this is a seriers with index of SGAs and value of bins\n SGA_thd = abs(df_CDF - (1-sig)).idxmin()\n SGA_thd = SGA_thd.round(3)\n #Get the total SGA names of SGAMatrix\n # read first line of SGAMatrix to get SGA name list\n with open(FILE_SGAMatrix_in, 'r') as f:\n reader = csv.reader(f)\n SGAs = next(reader)[1:] #line start from comma\n #convert SGAs list to pandas dataframe\n df_SGAthd = pd.DataFrame(SGAs,columns=['SGA'])\n df_SGAthd['PostProbcutoff']=df_SGAthd['SGA'].map(SGA_thd).fillna(1)\n\n df_SGAthd.to_csv(FILE_threshold_out,index=False)\n\n print(\"Process finished successfully\")\n time_hhmmss = my_timer.get_time_hhmmss()\n print(\"Total time elapsed: %s\\n\" % time_hhmmss)\n\ndef filterTriplets(FILEorPATH_in, FILE_threshold, FILEorPATH_out ):\n # if os.path.isfile(FILEorPATH_in) != os.path.isfile(FILEorPATH_out) :\n # print \"The file path Input and output are not consistant\"\n # exit(1)\n if os.path.isfile(FILEorPATH_in):\n FILE_triplets = FILEorPATH_in\n FILE_fileterdTriplets = FILEorPATH_out\n df = pd.read_csv(FILE_triplets)\n df_posterior = pd.read_csv(FILE_threshold)\n tmp = dict(zip(df_posterior[df_posterior.columns[0]], df_posterior[df_posterior.columns[1]]))\n df['a'] = df.cause_gene_name.map(tmp)\n # cutoff by posterior\n df_updated_cutoff = df.loc[df['posterior'] >= df['a']]\n df_updated_cutoff.to_csv(FILE_fileterdTriplets)\n return df_updated_cutoff\n \n\n# if __name__ == '__main__':\n # sig = 0.05\n # PATH_randTriplets_in = \"/mnt/Data_2TB/TDIReults_Analysis/PanCancer13tts_20171217/ExtractInfo/triplets/100DEGfreqRands/\"\n # FILE_SGAMatrix_in = \"/home/xim33/DataSource/PanCancer13tts.SGAmatrix.4TCI.csv\"\n # FILE_threshold_out = \"/mnt/Data_2TB/TDIReults_Analysis/PanCancer13tts_20171217/ExtractInfo/postprobthd.p=\"+str(sig)+\".csv\"\n # start = 1 # the start random experiement\n # end = 3 # the end random experiement\n # determinePosteriorThd(PATH_randTriplets_in,FILE_SGAMatrix_in,FILE_threshold_out)\n\n\nPATH_TDI = \"./Results/TDI\"\nPATH_triplets = \"./Results\"\nextractTriplets(PATH_TDI,PATH_triplets)\n\nPATH_TDI = \"./Results/TDI_rand\"\nPATH_triplets = \"./Results\"\nextractTriplets_rand(PATH_TDI,PATH_triplets)\n\nPATH_TDI = \"./Results/TDI_randbyfreq\"\nPATH_triplets = \"./Results/Triplets_randbyfreq\"\nextractTriplets_rand(PATH_TDI,PATH_triplets)\n\nsig = 0.05\nPATH_randTriplets_in = \"./Results/Triplets_randbyfreq\"\nFILE_SGAMatrix_in = sys.argv[1]#\"../DataSource/PanCancer13tts.SGAmatrix.4TCI.1217.csv\"\nFILE_threshold_out = \"./Results/postprobthd.p=\"+str(sig)+\".csv\"\ndeterminePosteriorThd_parallel(PATH_randTriplets_in,FILE_SGAMatrix_in,FILE_threshold_out,sig)\n \nFILEorPATH_in = \"./Results/Triplets.csv\"\nFILE_threshold = \"./Results/postprobthd.p=0.05.csv\"\nFILEorPATH_out = \"./Results/FilteredTriplets.csv\"\nfilterTriplets(FILEorPATH_in, FILE_threshold, FILEorPATH_out)\n","sub_path":"TDI_experiment/postAnalysisDataPreparation.py","file_name":"postAnalysisDataPreparation.py","file_ext":"py","file_size_in_byte":12103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"422880833","text":"from src import RGBNirBioModule, RGBNirBioDataModule\nimport pytorch_lightning as pl\nimport sys\nimport yaml\nfrom src import deep_update\nfrom pytorch_lightning.loggers import WandbLogger\nfrom pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping\n\nconfig = {\n 'backbone': 'resnet18',\n 'pretrained': True,\n 'optimizer': 'Adam',\n 'num_bio': 27,\n 'bio_layers': [100],\n 'bio_dropout': 0.,\n 'optimizer_params': {\n 'lr': 1e-3\n },\n 'early_stopping': False,\n 'trainer': {\n 'gpus': 1,\n 'max_epochs': 30,\n 'logger': None,\n 'enable_checkpointing': False,\n 'overfit_batches': 0,\n 'deterministic': True,\n 'precision': 16\n },\n 'datamodule': {\n 'batch_size': 512,\n 'num_workers': 10,\n 'pin_memory': True\n },\n}\n\n\ndef train(config, name):\n pl.seed_everything(42, workers=True)\n dm = RGBNirBioDataModule(**config['datamodule'])\n module = RGBNirBioModule(config)\n if config['trainer']['logger']:\n config['trainer']['logger'] = WandbLogger(\n project=\"GeoLifeCLEF2022\",\n name=name,\n config=config\n )\n config['trainer']['callbacks'] = []\n if config['trainer']['enable_checkpointing']:\n config['trainer']['callbacks'] += [\n ModelCheckpoint(\n dirpath='./checkpoints',\n filename=f'{name}-{{val_loss:.5f}}-{{epoch}}',\n monitor='val_loss',\n mode='min',\n save_top_k=1\n )\n ]\n if config['early_stopping']:\n config['trainer']['callbacks'] += [\n EarlyStopping(\n monitor='val_loss',\n patience=5,\n verbose=True\n )\n ]\n trainer = pl.Trainer(**config['trainer'])\n trainer.fit(module, dm)\n trainer.save_checkpoint('final.ckpt')\n\n\nif __name__ == '__main__':\n name = None\n if len(sys.argv) > 1:\n config_file = sys.argv[1]\n name = config_file[:-4]\n if config_file:\n with open(config_file, 'r') as stream:\n loaded_config = yaml.safe_load(stream)\n deep_update(config, loaded_config)\n print(config)\n train(config, name)\n","sub_path":"GeoLifeCLEF2022/RGBNirBio.py","file_name":"RGBNirBio.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"50277039","text":"# ---\r\n# jupyter:\r\n# jupytext:\r\n# formats: jupyter_scripts//ipynb,ifis_tools//py\r\n# text_representation:\r\n# extension: .py\r\n# format_name: light\r\n# format_version: '1.3'\r\n# jupytext_version: 1.0.0\r\n# kernelspec:\r\n# display_name: Python 3\r\n# language: python\r\n# name: python3\r\n# ---\r\n\r\n# # series_tools:\r\n#\r\n# set of tools that work with streamflow records.\r\n# - Identify events.\r\n# - Identidy baseflow and runoff.\r\n#\r\n\r\nimport pandas as pd \r\nimport numpy as np \r\nfrom read_dat import *\r\nfrom scipy import stats as sta\r\nfrom multiprocessing import Pool\r\nimport glob\r\ntry:\r\n import h5py\r\nexcept:\r\n print('no h5py module, cant read HLM hdf snapshots')\r\nfrom scipy.signal import find_peaks as __find_peaks__\r\nfrom hydroeval import evaluator, kge, nse, pbias\r\n# ## Digital filters\r\n#\r\n# Collection of functions to separate runoff from baseflow.\r\n\r\n# +\r\n\r\ndef percentiles(obs, sim, steps = 10, bins = None, perc = 50, percMax = 99.5):\r\n '''Obtains the percentile for the sim value that corresponds to\r\n an oberved value.\r\n Parameters:\r\n -obs: observed peaks or time serie.\r\n -sim: simulated peaks or time serie.\r\n -steps: number of splits to estimate the percentile.\r\n -perc: percentile to estimate\r\n -percMax: Max value to divide the observations.\r\n Returns:\r\n -A vector (2,N) where the first row corresponds to the percentiles\r\n at the observation and the second to the percentiles at the simulation'''\r\n if bins is None:\r\n bins = np.linspace(obs.min(), np.percentile(obs, percMax), steps)\r\n X = []; Y = []\r\n for i,j in zip(bins[:-1], bins[1:]):\r\n Y.append(np.percentile(sim[(obs>i) & (obs<=j)], perc))\r\n X.append((i+j)/2.)\r\n #Y.append(np.percentile(sim[(obs>i) & (obs<=j)], perc))\r\n return np.vstack([X,Y])\r\n\r\ndef read_dat_file(path, date_start,state = 0, freq = '60min'):\r\n '''Read fast a .dat file produced by HLM and returns a pandas DataFrame\r\n Parameters:\r\n -path: path to the .dat file.\r\n -date_start: starting date of the simulation\r\n -State: model state.\r\n -freq: Time step of the .dat given in min (ej. 60min).'''\r\n Ncon, Nrec,Nstat = read_dat.get_size(path)\r\n cont, data = read_dat.get_data(path, Ncon, Nrec, Nstat)\r\n dates = pd.date_range(date_start, periods=Nrec, freq=freq)\r\n \r\n return pd.DataFrame(data[:,state,:].T, index=dates, columns=cont)\r\n\r\ndef read_hdf(path):\r\n '''Reads an hdf usually written by the model as a snapshot, \r\n returns a pandas dataFrame with the results'''\r\n f = h5py.File(path,'r')\r\n df = pd.DataFrame(f['snapshot'][:])\r\n df.set_index('link_id', inplace = True)\r\n f.close()\r\n return df\r\n\r\n\r\ndef read_bin(path):\r\n return np.fromfile(path,\r\n dtype=np.dtype([('lid', np.int32),\r\n ('val', np.float32)]) ,\r\n offset=4,) \r\n\r\nclass performance:\r\n\r\n #Initialization and hide functions\r\n def __init__(self, temp_scale = '1H', links_prop = None, \r\n prop_col_names = None, rain_path = None, rain_ending = ''):\r\n '''class for the performance analysos of model simulations\r\n Params:\r\n - temp_scale: temporal scale at which the analysis will be done.\r\n -links_prop: a data frame that must have link_id as index, and columns \r\n related with the area and the travel time of the watershed.\r\n -prop_col_names: dictionary with the actual name in the link_prop and \r\n the name for this tool. which are 'area' for the acumulated area and \r\n 'ttime' for the travel time\r\n -rain_path: the path to find the mean reainfall series of each watershed\r\n This is relevant for the some of the performance metrics, if not given they\r\n will be deactivated.\r\n -rain_ending: the name at the end of the rainfall files (if exist)'''\r\n #Define initial things of the class \r\n self.analysis_dic = {}\r\n self.base_name = None\r\n self.temp_scale = temp_scale\r\n self.link_act = None\r\n self.tocompare = []\r\n #Get link props that is a dataFrame\r\n if links_prop is not None:\r\n self.link_prop = links_prop\r\n self.link_prop = self.link_prop.rename(columns = prop_col_names)[[prop_col_names[k] for k in prop_col_names.keys()]]\r\n #Rainfall path \r\n if rain_path is not None:\r\n self.update_dic('rain', False, path = rain_path, abr = 'r', file_ending = rain_ending)\r\n self.__has_rain__ = True\r\n else:\r\n self.__has_rain__ = False\r\n \r\n def __mapVar__(self, x, new_min = 0, new_max = 1):\r\n '''Function to map any vatriable between a range'''\r\n return ((x-x.min())/(x.max()-x.min()))*(new_max - new_min) + new_min \r\n\r\n def __intersection__(self, n_list1, n_list2): \r\n '''Get the intersection of two links lists'''\r\n lst1 = self.analysis_dic[n_list1]['link_names']\r\n lst2 = self.analysis_dic[n_list2]['link_names'] \r\n paths2 = self.analysis_dic[n_list2]['link_paths'] \r\n valueN = []\r\n pathsN = []\r\n for value,path in zip(lst2, paths2):\r\n if value in lst1:\r\n valueN.append(value)\r\n pathsN.append(path)\r\n return valueN, pathsN \r\n\r\n def __path2name__(self, paths):\r\n '''Extracts the link numbers from a list of paths.'''\r\n names = []\r\n for i in paths:\r\n j = i.split('/')[-1]\r\n names.append(''.join([s for s in j if s.isdigit()]))\r\n return names\r\n\r\n def __func_qpeakTimeDiff__(self,qo,qs, ttime = None):\r\n '''Calc the time difference between two hydrographs\r\n parameters:\r\n - qo: observed hydrograph.\r\n - qs: simulated hydrograph\r\n - ttime: reference time for the hydrograph\r\n returns:\r\n - dt: delta time difference, \r\n - negative stands for time(sim) > time(obs): late arrival\r\n - positibve time(sim) < time(obs): early arrival'''\r\n to = qo.idxmax()\r\n ts = qs.idxmax()\r\n dt = to - ts\r\n dt = dt.seconds / 3600.\r\n if ttime is not None:\r\n dt = dt / ttime\r\n if to > ts:\r\n return dt*-1\r\n else:\r\n return dt\r\n\r\n def __func_qpeakMagDiff__(self,qo,qs):\r\n '''Calc the magnitude difference between two hydrographs'''\r\n qmo = qo.max()\r\n qms = qs.max()\r\n return (qmo - qms) / qmo\r\n\r\n def __func_qpeakMagDiff2(self, qo,qs):\r\n '''Same as func_qpeakMagDiff but put first the simulated'''\r\n qmo = qo.max()\r\n qms = qs.max()\r\n return (qms - qmo) / qmo\r\n\r\n def __func_HyM__(self, qo, qs, flood):\r\n '''Calculates the amount of Hits and misses compared to certain flood\r\n value'''\r\n a = qo[(qo >= flood) & (qs >= flood)].size\r\n c = qo[qo>=flood].size\r\n if c ==0:\r\n return np.nan\r\n else:\r\n return float(a)/float(c)\r\n\r\n def __func_KGE__(self, qo, qs):\r\n '''Gets the KGE for an event'''\r\n try:\r\n return evaluator(kge, qs.values, qo.values)[0][0]\r\n except:\r\n return evaluator(kge, qs, qo)[0][0]\r\n\r\n def __func_KGE_mean__(self, qo,qs):\r\n '''Gets the mean ratio difference of the KGE'''\r\n qo.dropna(inplace = True)\r\n qs.dropna(inplace = True)\r\n idx = qo.index.intersection(qs.index)\r\n return qs.loc[idx].mean() / qo.loc[idx].mean()\r\n\r\n def __func_KGE_std__(self, qo,qs):\r\n '''Gets the std ratio of the KGE'''\r\n qo.dropna(inplace = True)\r\n qs.dropna(inplace = True)\r\n idx = qo.index.intersection(qs.index)\r\n return qs.loc[idx].std() / qo.loc[idx].std()\r\n\r\n def __func_pbias__(self, qo, qs):\r\n '''Gets the Percent bias for an event'''\r\n try:\r\n return evaluator(pbias, qs.values, qo.values)[0] * (-1)\r\n except:\r\n return evaluator(pbias, qs, qo)[0] * (-1)\r\n\r\n def __func_nse__(self, qo, qs):\r\n '''Gets the Nash for an event'''\r\n try:\r\n return evaluator(nse, qs.values, qo.values)[0]\r\n except:\r\n return evaluator(nse, qs, qo)[0]\r\n\r\n def __func_qpeakTravelTime__(self, q):\r\n ttime = int(self.link_tt)*4\r\n dt = pd.Timedelta(str(ttime)+'H')\r\n peakMax = q.idxmax()\r\n max_r_idx = self.link_r[peakMax-dt:peakMax].idxmax()\r\n max_r_val = self.link_r[peakMax-dt:peakMax].max()\r\n ttime = peakMax - max_r_idx\r\n return max_r_val, ttime.seconds/3600.\r\n\r\n def __func_find_max_corr(self, qo,qs,w = 100):\r\n #Get only the data that is not nan\r\n qo.dropna(inplace=True)\r\n qs.dropna(inplace=True)\r\n idx = qo.index.intersection(qs.index)\r\n qo = qo[idx]\r\n qs = qs[idx]\r\n #find the best correlation \r\n bestCorr = -9999\r\n bestMove = -9999\r\n zeroCorr = 0.0\r\n for move in np.arange(-w+1,w):\r\n ct = sta.pearsonr(qo.values[w:-w],qs.values[w+move:-w+move])[0]\r\n if ct > bestCorr:\r\n bestCorr = ct\r\n bestMove = move\r\n if move == 0:\r\n zeroCorr = ct\r\n return bestCorr, zeroCorr, bestMove\r\n\r\n\r\n def set_link2analyze(self, link, min4event = 'P90', link_tt = 30.):\r\n '''For a link read the data of the different options\r\n Parameters:\r\n - link: the link to analyze.\r\n - min4event: the minim value to consider an event, could be a number or\r\n the percentile (eg P50, P60, P90)\r\n - link_tt: traver time of the link is to determine the length of the hydrograph.\r\n Returns:\r\n - Updates the analysis_dic of the performance class'''\r\n self.link_act = link\r\n self.link_tt = link_tt\r\n for k in self.analysis_dic:\r\n pos = self.analysis_dic[k]['link_names'].index(str(link))\r\n #try:\r\n #reads the data\r\n q = pd.read_msgpack(self.analysis_dic[k]['link_paths'][pos])\r\n if self.analysis_dic[k]['isDataFrame']:\r\n q = q[self.analysis_dic[k]['DataFrameColumn']]\r\n self.analysis_dic[k]['data']['q'] = q.resample(self.temp_scale).mean()\r\n self.link_q = q.resample(self.temp_scale).mean()\r\n #rainfall data \r\n if self.__has_rain__:\r\n self.link_r = pd.read_msgpack(self.analysis_dic['rain']['link_paths'][pos])\r\n #Gert the events for the base\r\n if k == self.base_name:\r\n #Set the type of minimum value\r\n if type(min4event) == int or type(min4event) == float:\r\n qmin = min4event\r\n elif min4event.startswith('P'):\r\n per = float(min4event[1:])\r\n if per>1.0: per = per/100.\r\n min4event = q[q.notnull()].quantile(per) \r\n #Get tyhe events for that station\r\n pos,ph = __find_peaks__(q, min4event, distance = link_tt)\r\n self.analysis_dic[k]['data']['peaks'] = q.index[pos]\r\n self.link_mpeak = ph['peak_heights']\r\n self.link_tpeak = q.index[pos]\r\n #except:\r\n #If any error just put nan\r\n # self.analysis_dic[k]['data']['q'] = np.nan\r\n\r\n #Function to update the main analysiis dic.\r\n def update_dic(self, name, base = False, path = 'not set', abr = 'not set', file_ending = '',\r\n path2linkFunc = None, isDataFrame = False, DataFrameColumn = ''):\r\n '''Creates a dictionary for the performance of the model analysis:\r\n Parameters:\r\n -name: name to the model run or observed serie.\r\n -base: is this an observation or not?.\r\n -path: directory with the msgpack series of the links.\r\n -abr: small name.\r\n -file_ending: text at the end of the files for that run\r\n -path2fileFunc: optinal function to extract the links from the given paths.\r\n -isDataFrame: if the data came from a data frame.\r\n -DataFrameColumn: the name of the column to extract from the data. \r\n Returns (no explicit return):\r\n Updates the dictionary with the information for the analysis with\r\n series.'''\r\n #Defines if it is the base key\r\n if base:\r\n self.base_name = name\r\n else:\r\n self.tocompare.append(name)\r\n #Get the links and paths to the links of that class\r\n links_paths = glob.glob(path+'.msg')\r\n if path2linkFunc is None:\r\n links_names = self.__path2name__(links_paths)\r\n else:\r\n links_names = path2linkFunc(links_paths)\r\n #Updates the information of the performance dictionary\r\n self.analysis_dic.update({\r\n name: {'base': base,\r\n 'path': path,\r\n 'abr': abr,\r\n 'file_ending': file_ending,\r\n 'isDataFrame': isDataFrame,\r\n 'DataFrameColumn': DataFrameColumn,\r\n 'link_paths': links_paths,\r\n 'link_names': links_names,\r\n 'data':{\r\n 'q': None,\r\n 'peaks': None\r\n }},\r\n })\r\n #If has the base makes the intersect to hav just the good links\r\n if self.base_name is not None and name != self.base_name:\r\n # Gets the intersection of the links\r\n links_names, links_paths = self.__intersection__(self.base_name, name)\r\n self.analysis_dic[name]['link_paths'] = links_paths\r\n self.analysis_dic[name]['link_names'] = links_names\r\n #Updates the intersection of all the evaluable links\r\n self.links_eval = links_names\r\n\r\n #To make ealuations by events\r\n def eval_by_events(self, link = None, min4peak = None):\r\n '''Get the performance of multiple excecutions for all the events of that link'''\r\n\r\n if link is not None:\r\n args = {'link_tt': self.link_prop['ttime'][int(link)]}\r\n if min4peak is not None:\r\n args.update({'min4event' : min4peak})\r\n self.set_link2analyze(link, **args)\r\n area_link = self.link_prop.loc[float(link),'area'] / 1e6\r\n\r\n #Define list to fill \r\n Dates = []\r\n Qpeak = []\r\n QpeakMDiff = []\r\n QpeakTDiff = []\r\n KGE = []\r\n PBIAS = []\r\n NASH = []\r\n product = []\r\n if self.__has_rain__:\r\n RainPeak = []\r\n TimePeak = []\r\n Qmean = []\r\n Area = []\r\n meanRatio = []\r\n stdRatio = []\r\n\r\n #Iterate in all the models\r\n for k in self.analysis_dic.keys():\r\n if k != 'rain':\r\n #Get data\r\n qs = self.analysis_dic[k]['data']['q']\r\n qo = self.analysis_dic[self.base_name]['data']['q']\r\n dt = pd.Timedelta(str(self.link_tt)+'H')\r\n qmean = qs.mean()\r\n\r\n for date in self.analysis_dic[self.base_name]['data']['peaks']:\r\n qot = qo[date-dt:date+dt]\r\n qst = qs[date-dt:date+dt]\r\n if self.__has_rain__:\r\n rt = self.link_r[date-dt*4:date+dt]\r\n if len(qot)>0 and len(qst)>0:\r\n good_o = qot[qot.notnull()].size / qot.size\r\n good_s = qst[qst.notnull()].size / qst.size\r\n #Only makes the calculus if both series have more than half of their records\r\n if good_o > 0.5 and good_s > 0.5 and len(qot) == len(qst):\r\n #Good date\r\n Dates.append(date)\r\n product.append(k)\r\n Qmean.append(qmean)\r\n Area.append(area_link)\r\n #Get the performance of the qpeak max\r\n QpeakMDiff.append(self.__func_qpeakMagDiff__(qot,qst))\r\n Qpeak.append(np.nanmax(qst))\r\n #Time performance \r\n travelDif = self.__func_qpeakTimeDiff__(qot, qst)\r\n QpeakTDiff.append(travelDif)\r\n #Get the oberved and simulated travel time\r\n if self.__has_rain__:\r\n i_max,tpeak = self.__func_qpeakTravelTime__(qst)\r\n TimePeak.append(tpeak)\r\n RainPeak.append(i_max)\r\n #Overall performance\r\n KGE.append(self.__func_KGE__(qot, qst))\r\n PBIAS.append(self.__func_pbias__(qot, qst)*-1)\r\n NASH.append(self.__func_nse__(qot, qst))\r\n #Mean sn std ratios\r\n meanRatio.append(self.__func_KGE_mean__(qot,qst))\r\n stdRatio.append(self.__func_KGE_std__(qot,qst))\r\n\r\n #Set up to include or not to include rain analysis.\r\n if self.__has_rain__:\r\n columns = ['product','qpeak','qmean','Imax','qpeakDiff',\r\n 'tpeak','tpeakDiff','kge','nse', 'pbias','mean_ratio','std_ratio','up_area']\r\n ListProducts = [product, Qpeak, Qmean,RainPeak, QpeakMDiff,\r\n TimePeak,QpeakTDiff, KGE, NASH, PBIAS, meanRatio, stdRatio, Area]\r\n formats = {'qpeak':'float','tpeak':'float', 'qpeakDiff':'float','kge':'float', 'tpeakDiff':'float', \r\n 'nse':'float', 'pbias':'float',\r\n 'Imax':'float','qmean':'float',\r\n 'mean_ratio':'float','std_ratio':'float', 'up_area':'float'}\r\n else:\r\n columns = ['product','qpeak','qmean','qpeakDiff',\r\n 'tpeakDiff','kge','nse', 'pbias','mean_ratio','std_ratio','up_area']\r\n ListProducts = [product, Qpeak, Qmean,QpeakMDiff,\r\n QpeakTDiff, KGE, NASH, PBIAS, meanRatio, stdRatio, Area]\r\n formats = {'qpeak':'float','qpeakDiff':'float','kge':'float', 'tpeakDiff':'float', \r\n 'nse':'float',\r\n 'pbias':'float',\r\n 'mean_ratio':'float','std_ratio':'float',\r\n 'qmean':'float','up_area':'float'}\r\n #Convert to a Data frame with the results.\r\n D = pd.DataFrame(np.array(ListProducts).T, index = Dates, columns = columns, )\r\n D = D.astype(formats)\r\n D['link'] = self.link_act\r\n return D\r\n\r\n def eval_years(self, link = None, usgs = None, fi = '',\r\n flood = None, Pflood = 96, window = 100):\r\n '''Eval the performance of the model results for every year'''\r\n\r\n if link is not None:\r\n self.set_link2analyze(link)\r\n\r\n Vol = []\r\n KGE = []\r\n NSE = []\r\n Hits = []\r\n Misses = []\r\n Pbias = []\r\n PD = []\r\n QP = []\r\n Years = []\r\n Product = []\r\n bestCorr = []\r\n zeroCorr = []\r\n bestMove = []\r\n meanRatio = []\r\n stdRatio = []\r\n for k in self.analysis_dic.keys():\r\n qs = self.analysis_dic[k]['data']['q']\r\n qo = self.analysis_dic[self.base_name]['data']['q']\r\n\r\n idx = qo.index.intersection(qs.index)\r\n qot = qo[idx]\r\n qst = qs[idx]\r\n qA = qot.resample('A').mean()\r\n\r\n if flood is None:\r\n flood = np.percentile(qo[qo>0], Pflood)\r\n\r\n for y in qA.index.year.values:\r\n #Position of the numeric values\r\n p = np.where((np.isnan(qot[str(y)]) == False) & (np.isnan(qst[str(y)]) == False))[0]\r\n #Performance\r\n KGE.append(self.__func_KGE__(qot[str(y)][p],qst[str(y)][p]))\r\n NSE.append(self.__func_nse__(qot[str(y)][p],qst[str(y)][p]))\r\n Pbias.append(self.__func_pbias__(qot[str(y)][p],qst[str(y)][p]))\r\n Hits.append(self.__func_HyM__(qot[str(y)][p],qst[str(y)][p],flood))\r\n PD.append(self.__func_qpeakMagDiff2(qot[str(y)][p],qst[str(y)][p]))\r\n #Mean sn std ratios\r\n meanRatio.append(self.__func_KGE_mean__(qot[str(y)],qst[str(y)]))\r\n stdRatio.append(self.__func_KGE_std__(qot[str(y)],qst[str(y)]))\r\n #Best correlation and correlatoin\r\n try:\r\n beCorr, zeCorr, beMove = self.__func_find_max_corr(qo[str(y)],qs[str(y)],window)\r\n bestCorr.append(beCorr)\r\n zeroCorr.append(zeCorr)\r\n bestMove.append(beMove)\r\n except:\r\n bestCorr.append(0.0)\r\n zeroCorr.append(0.0)\r\n bestMove.append(0)\r\n #Prop\r\n Vol.append(qst[str(y)][p].sum())\r\n QP.append(qst[str(y)][p].max())\r\n #Add the year\r\n Years.append(y)\r\n Product.append(k)\r\n\r\n #Convert to a Data frame with the results.\r\n ListProducts = [Product, KGE, NSE, Vol, Pbias, Hits, PD, QP,\r\n zeroCorr, bestCorr, bestMove, meanRatio,\r\n stdRatio]\r\n columns = ['product','kge','nse','vol','pbias', 'Hits',\r\n 'PeakDif','Qpeak',\r\n 'corr','best_corr','moves','meanRatio','stdRatio']\r\n formats = {'kge':'float', 'nse':'float','vol':'float','pbias':'float',\r\n 'Hits':'float', 'PeakDif':'float','Qpeak':'float',\r\n 'corr':'float','best_corr':'float','moves':'int',\r\n 'meanRatio':'float','stdRatio':'float'}\r\n D = pd.DataFrame(np.array(ListProducts).T, index = Years, columns = columns, )\r\n D = D.astype(formats)\r\n D['Misses'] = 1 - D['Hits']\r\n D['link'] = self.link_act\r\n if usgs is not None:\r\n D['usgs'] = usgs\r\n return D\r\n\r\n # class performance:\r\n\r\n # def __init__(self):\r\n # '''class for the performance analysos of model simulations''' \r\n # self.analysis_dic = {}\r\n\r\n # def mapVar(self, x, new_min = 0, new_max = 1):\r\n # '''Function to map any vatriable between a range'''\r\n # return ((x-x.min())/(x.max()-x.min()))*(new_max - new_min) + new_min\r\n\r\n # def func_qpeakTimeDiff(self,qo,qs, ttime = None):\r\n # '''Calc the time difference between two hydrographs\r\n # parameters:\r\n # - qo: observed hydrograph.\r\n # - qs: simulated hydrograph\r\n # - ttime: reference time for the hydrograph\r\n # returns:\r\n # - dt: delta time difference, \r\n # - negative stands for time(sim) > time(obs): late arrival\r\n # - positibve time(sim) < time(obs): early arrival'''\r\n # to = qo.idxmax()\r\n # ts = qs.idxmax()\r\n # dt = to - ts\r\n # dt = dt.seconds / 3600.\r\n # if ttime is not None:\r\n # dt = dt / ttime\r\n # if to > ts:\r\n # return dt*-1\r\n # else:\r\n # return dt\r\n\r\n # def func_qpeakMagDiff(self,qo,qs):\r\n # '''Calc the magnitude difference between two hydrographs'''\r\n # qmo = qo.max()\r\n # qms = qs.max()\r\n # return (qmo - qms) / qmo\r\n\r\n # def update_dic(self, name, base = False, path = 'not set', abr = 'not set', file_ending = '',\r\n # isDataFrame = False, DataFrameColumn = ''):\r\n # '''Creates a dictionary for the performance of the model analysis:\r\n # Parameters:\r\n # -name: name to the model run or observed serie.\r\n # -base: is this an observation or not?.\r\n # -path: directory with the msgpack series of the links.\r\n # -abr: small name.\r\n # -file_ending: text at the end of the files for that run\r\n # -isDataFrame: if the data came from a data frame.\r\n # -DataFrameColumn: the name of the column to extract from the data. \r\n # Returns (no explicit return):\r\n # Updates the dictionary with the information for the analysis with\r\n # series.'''\r\n # self.analysis_dic.update({\r\n # name: {'base': base,\r\n # 'path': path,\r\n # 'abr': abr,\r\n # 'file_ending': file_ending,\r\n # 'isDataFrame': isDataFrame,\r\n # 'DataFrameColumn': DataFrameColumn},\r\n # })\r\n\r\n # def percentiles(self, obs, sim, steps = 10, bins = None, perc = 50, percMax = 99.5):\r\n # '''Obtains the percentile for the sim value that corresponds to\r\n # an oberved value.\r\n # Parameters:\r\n # -obs: observed peaks or time serie.\r\n # -sim: simulated peaks or time serie.\r\n # -steps: number of splits to estimate the percentile.\r\n # -perc: percentile to estimate\r\n # -percMax: Max value to divide the observations.\r\n # Returns:\r\n # -A vector (2,N) where the first row corresponds to the percentiles\r\n # at the observation and the second to the percentiles at the simulation'''\r\n # if bins is None:\r\n # bins = np.linspace(obs.min(), np.percentile(obs, percMax), steps)\r\n # X = []; Y = []\r\n # for i,j in zip(bins[:-1], bins[1:]):\r\n # Y.append(np.percentile(sim[(obs>i) & (obs<=j)], perc))\r\n # X.append((i+j)/2.)\r\n # #Y.append(np.percentile(sim[(obs>i) & (obs<=j)], perc))\r\n # return np.vstack([X,Y])\r\n\r\n # def perform_analysis(self, link, qpeakmin, keys = None, yi = 2012, yf = 2018):\r\n # '''Produce the performance analysis of several simulation by taking a \r\n # dictionary with the information of the series names, path and abreviation.\r\n # Parameters:\r\n # -ForAnalysis: Dictionary with the structure given by Dic4Analysis.\r\n # -link: number of the link to be analyzed, the link must be saved in a msgpack\r\n # format under the path given by the dictionary of ForAnalysis.\r\n # -qpeakmin: minimum value to consider a qpeak.\r\n # -keys: (optional) if not given it takes the keys from the dictionary.\r\n # - yi and yf: initial and end year of the anlysis.\r\n # Returns:\r\n # - Metrics: DataFrame with the metrics for the models.\r\n # - QpeakAnalysis: DataFrmae with the metrics of all the peaks found.'''\r\n # #Define function to obtain median value\r\n # def median(x):\r\n # try:\r\n # return np.percentile(x, 50)\r\n # except:\r\n # pass \r\n # def FindMax(Serie, Smax, tw = '1W'):\r\n # index = []\r\n # values = []\r\n # shared = []\r\n # dt = pd.Timedelta(tw)\r\n # for i in Smax.index:\r\n # try:\r\n # val = Serie[i-dt:i+dt].max()\r\n # if val > 0:\r\n # index.append(Serie[i-dt:i+dt].idxmax())\r\n # values.append(val)\r\n # shared.append(i)\r\n # except:\r\n # pass\r\n # return pd.Series(values, index), shared \r\n # #Read the data\r\n # if keys is None:\r\n # keys = [k for k in self.analysis_dic.keys()]\r\n # yf += 1\r\n # Data = {}\r\n # for k in keys:\r\n # if self.analysis_dic[k]['isDataFrame']:\r\n # q = pd.read_msgpack(self.analysis_dic[k]['path']+str(link)+self.analysis_dic[k]['file_ending']+'.msg')\r\n # q = q[self.analysis_dic[k]['DataFrameColumn']]\r\n # print(q.type)\r\n # else:\r\n # q = pd.read_msgpack(self.analysis_dic[k]['path']+str(link)+self.analysis_dic[k]['file_ending']+'.msg')\r\n # #Updates data in a dictionary\r\n # D = {k: {'q': q,\r\n # 'base': self.analysis_dic[k]['base'],\r\n # 'abr': self.analysis_dic[k]['abr']}}\r\n # #If it is the base obtains the peak values\r\n # if self.analysis_dic[k]['base']:\r\n # qo = q.copy()\r\n # qo_max = Events_Get_Peaks(q, qpeakmin, tw = pd.Timedelta('5d'))\r\n # D[k].update({'qmax': qo_max})\r\n # Data.update(D)\r\n # #Produce the analysis\r\n # Metrics = {} \r\n # for k in keys:\r\n # if self.analysis_dic[k]['base'] is False:\r\n # #Obtains the peaks in the simulation\r\n # key_sim = k\r\n # qs = Data[k]['q']\r\n # qs_max, sh = FindMax(qs, qo_max)\r\n # #Obtain peak differences metrics \r\n # qpeakMagDiff = (qo_max[sh].values - qs_max.values) / qo_max[sh].values\r\n # #Differences at the time to peak\r\n # qpeakTimeDiff = qo_max[sh].index - qs_max.index\r\n # pos = np.where(qo_max[sh].index > qs_max.index)[0]\r\n # qpeakTimeDiff = qpeakTimeDiff.seconds / 3600.\r\n # qpeakTimeDiff = qpeakTimeDiff.values\r\n # qpeakTimeDiff[pos] = -1*qpeakTimeDiff[pos]\r\n # #Yearly differences\r\n # kge_val = []\r\n # VolDif = []\r\n # Qannual = []\r\n # Dtannual = []\r\n # Anos = []\r\n # qpAnnual = pd.Series(qpeakMagDiff, index=qo_max[sh].index)\r\n # qpAnnual = qpAnnual.resample('A').apply(median)\r\n # dtAnnual = pd.Series(qpeakTimeDiff, index=qo_max[sh].index)\r\n # dtAnnual = dtAnnual.resample('A').apply(median) \r\n # for i in range(yi,yf):\r\n # pos = np.where(np.isnan(qs[str(i)]) == False)[0]\r\n # qsimOver = qo[qs[str(i)].index[pos]].values\r\n # kge_temp = evaluator(kge, qs[str(i)].values[pos], qo[qs[str(i)].index[pos]].values)[0][0]\r\n # voldif_temp = ((np.nansum(qsimOver)*3600/1e6) -(qs[str(i)].sum()*3600/1e6)) / (np.nansum(qsimOver)*3600/1e6)\r\n # if kge_temp > -999:\r\n # try:\r\n # #print(i,qpAnnual[str(i)].values[0])\r\n # Qannual.append(qpAnnual[str(i)].values[0])\r\n # Dtannual.append(dtAnnual[str(i)].values[0])\r\n # except:\r\n # Qannual.append(np.nan)\r\n # Dtannual.append(np.nan)\r\n # kge_val.append(kge_temp)\r\n # VolDif.append(voldif_temp)\r\n # Anos.append(pd.Timestamp(year = i, month = 12, day = 31)) \r\n # else: \r\n # key_base = k\r\n # qs_max = qo_max.copy()\r\n # sh = qs_max.index\r\n # qpeakMagDiff = np.zeros(qs_max.size)\r\n # qpeakTimeDiff = np.zeros(qs_max.size)\r\n # kge_val = np.ones(np.arange(yi,yf).size) \r\n # VolDif = np.zeros(np.arange(yi,yf).size)\r\n # Qannual = np.zeros(np.arange(yi,yf).size)\r\n # Dtannual = np.zeros(np.arange(yi,yf).size)\r\n # Anos = []\r\n # for i in range(yi,yf):\r\n # Anos.append(pd.Timestamp(year = i, month = 12, day = 31))\r\n \r\n # #Update the dictionary.\r\n # MetQp = np.vstack([qs_max, qpeakMagDiff, qpeakTimeDiff]).T\r\n # idxQp = qo_max[sh].index\r\n # columnsQp = ['qpeak','qpeakMagDif', 'qpeakTimeDif']\r\n # MetEff = np.vstack([kge_val, VolDif, Qannual, Dtannual]).T\r\n # idxEff = Anos\r\n # columnsEff = ['kge', 'VolDif', 'qpeakMagDif', 'qpeakTimeDif']\r\n # Metrics.update({\r\n # k:{\r\n # 'link': link,\r\n # 'qpeakMetrics': pd.DataFrame(MetQp, index = idxQp, columns = columnsQp),\r\n # 'effMetrics': pd.DataFrame(MetEff, index = idxEff, columns = columnsEff)\r\n # }\r\n # })\r\n \r\n # #Converts everything into a DataFrame\r\n # usgs_idx = Metrics[key_base]['qpeakMetrics'].index\r\n # model_idx = Metrics[key_sim]['qpeakMetrics'].index\r\n # shared_idx = model_idx.intersection(usgs_idx)\r\n # Metrics[key_base]['qpeakMetrics'] = Metrics[key_base]['qpeakMetrics'].loc[shared_idx]\r\n # initial = 'usgs'\r\n # QpeakAnalysis = Metrics[key_base]['qpeakMetrics']\r\n # QpeakAnalysis['model'] = key_base\r\n # QpeakAnalysis['link'] = link\r\n # for k in Metrics.keys():\r\n # if k != initial:\r\n # a = Metrics[k]['qpeakMetrics']\r\n # a['model'] = k\r\n # a['link'] = link\r\n # QpeakAnalysis = QpeakAnalysis.append(a)\r\n # #Converts metrics into a dataFrame\r\n # MetrData = Metrics[key_base]['effMetrics']\r\n # MetrData['model'] = key_base\r\n # MetrData['link'] = link\r\n # for k in Metrics.keys():\r\n # if k != initial:\r\n # a = Metrics[k]['effMetrics']\r\n # a['model'] = k\r\n # a['link'] = link\r\n # MetrData = MetrData.append(a)\r\n \r\n # return MetrData, QpeakAnalysis\r\n\r\n\r\n\r\n\r\n\r\ndef DigitalFilters(Q,tipo = 'Eckhart', a = 0.98, BFI = 0.8):\r\n '''Digital filters to separate baseflow from runoff in a continuos time series.\r\n Parameters:\r\n - tipo: type of filter to be used.\r\n - Eckhart o 1.\r\n - Nathan o 2.\r\n - Chapman o 3.\r\n - Q: pandas series with the streamflow records.\r\n - a: paramter for the filter.\r\n - Eckhart: 0.98.\r\n - Nathan: 0.8.\r\n - Chapman: 0.8.\r\n - BFI: 0.8 only applies for Eckhart filter.\r\n Returns:\r\n - Pandas DataFrame with the Runoff, Baseflow.'''\r\n #Functions definitions.\r\n def Nathan1990(Q, a = 0.8):\r\n '''One parameter digital filter of Nathan and McMahon (1990)'''\r\n R = np.zeros(Q.size)\r\n c = 1\r\n for q1,q2 in zip(Q[:-1], Q[1:]):\r\n R[c] = a*R[c-1] + ((1+a)/2.)*(q2-q1)\r\n if R[c]<0: \r\n R[c] = 0\r\n elif R[c]>q2:\r\n R[c] = q2 \r\n c += 1\r\n B = Q - R\r\n return R, B\r\n\r\n def Eckhart2005(Q, BFI=0.8, a = 0.98):\r\n '''Two parameter Eckhart digital filter\r\n Parameters:\r\n - Q: np.ndarray with the streamflow records.\r\n - BFI: The maximum amount of baseflow (%).\r\n - a: parameter alpha (0.98)\r\n Output: \r\n - R: total runoff.\r\n - B: total baseflow.'''\r\n #SEparation\r\n B = np.zeros(Q.size)\r\n B[0] = Q[0]\r\n c = 1\r\n for q in Q[1:]:\r\n #SEparation equation\r\n B[c] = ((1.0-BFI)*a*B[c-1]+(1.0-a)*BFI*q)/(1.0-a*BFI)\r\n #Constrains\r\n if B[c] > q:\r\n B[c] = q\r\n c+=1\r\n R = Q - B\r\n return R, B\r\n\r\n def ChapmanMaxwell1996(Q, a = 0.98):\r\n '''Digital filter proposed by chapman and maxwell (1996)'''\r\n B = np.zeros(Q.size)\r\n c = 1\r\n for q in Q[1:]:\r\n B[c] = (a / (2.-a))*B[c-1] + ((1.-a)/(2.-a))*q\r\n c+=1\r\n R = Q-B\r\n return R,B\r\n \r\n #Cal the filter \r\n if tipo == 'Eckhart' or tipo == 1:\r\n R,B = Eckhart2005(Q.values, a, BFI)\r\n elif tipo =='Nathan' or tipo == 2:\r\n R,B = Nathan1990(Q.values, a,)\r\n elif tipo == 'Chapman' or tipo ==3:\r\n R,B = ChapmanMaxwell1996(Q.values, a)\r\n #Returns the serie\r\n return pd.DataFrame(np.vstack([R,B]).T, index = Q.index, columns = ['Runoff','Baseflow']) \r\n\r\n\r\n# -\r\n\r\n# ## Events selection functions\r\n#\r\n# Collection of functions to identify peaks in a series and the end of each peak recession.\r\n\r\n# +\r\ndef Events_Get_Peaks(Q, Qmin = None, tw = pd.Timedelta('12h')):\r\n '''Find the peack values of the hydrographs of a serie\r\n Params:\r\n - Q: Pandas serie with the records.\r\n - Qmin: The minimum value of Q to be considered a peak.\r\n if None takes the 99th percentile of the series as the min\r\n - tw: size of the ime window used to eliminate surrounding maximum values'''\r\n if Qmin is None:\r\n Qmin = np.percentile(Q.values[np.isfinite(Q.values)], 99)\r\n #Find the maximum\r\n Qmax = Q[Q>Qmin]\r\n QmaxCopy = Qmax.copy()\r\n #Search the maxium maximorums\r\n Flag = True\r\n PosMax = []\r\n while Flag:\r\n MaxIdx = Qmax.idxmax()\r\n PosMax.append(MaxIdx)\r\n Qmax[MaxIdx-tw:MaxIdx+tw] = -9\r\n if Qmax.max() < Qmin: Flag = False\r\n #Return the result\r\n return QmaxCopy[PosMax].sort_index()\r\n\r\ndef Events_Get_End(Q, Qpeaks):\r\n '''Obtains the end of each event extracted by Events_Get_Peaks'''\r\n #Expands the Qpeaks\r\n Qpeaks = Qpeaks.append(Q[-1:])\r\n Qpeaks.values[-1] = Qpeaks.max()\r\n #Finds the ends\r\n dates_min = []\r\n val_mins = []\r\n for star, end in zip(Qpeaks.index[:-1], Qpeaks.index[1:]):\r\n dates_min.append(Q[star:end].idxmin())\r\n val_mins.append(Q[star:end].min())\r\n return pd.Series(val_mins, dates_min)\r\n\r\n# def Events_Get_End(Q, Qmax, minDif = 0.04, minDistance = None,maxSearch = 10, Window = '1h'):\r\n# '''Find the end of each selected event in order to know the \r\n# longitude of each recession event.\r\n# Parameters: \r\n# - Q: Pandas series with the records.\r\n# - Qmax: Pandas series with the peak streamflows.\r\n# - minDif: The minimum difference to consider that a recession is over.\r\n# Optional:\r\n# - minDistance: minimum temporal distance between the peak and the end.\r\n# - maxSearch: maximum number of iterations to search for the end.\r\n# - Widow: Size of the temporal window used to smooth the streamflow \r\n# records before the difference estimation (pandas format).\r\n# Returns: \r\n# - Qend: The point indicating the en of the recession.'''\r\n# #Obtains the difference\r\n# X = Q.resample('1h').mean()\r\n# dX = X.values[1:] - X.values[:-1]\r\n# dX = pd.Series(dX, index=X.index[:-1])\r\n# #Obtains the points.\r\n# DatesEnds = []\r\n# Correct = []\r\n# for peakIndex in Qmax.index:\r\n# try:\r\n# a = dX[dX.index > peakIndex]\r\n# if minDistance is None:\r\n# DatesEnds.append(a[a>minDif].index[0])\r\n# Correct.append(0)\r\n# else:\r\n# Dates = a[a>minDif].index\r\n# flag = True\r\n# c = 0\r\n# while flag:\r\n# distancia = Dates[c] - peakIndex\r\n# if distancia > minDistance:\r\n# DatesEnds.append(Dates[c])\r\n# flag= False\r\n# Correct.append(0)\r\n# c += 1\r\n# if c>maxSearch:\r\n# flag = False\r\n# Correct.append(1)\r\n# except: \r\n# Correct.append(1)\r\n# #Returns the pandas series with the values and end dates \r\n# Correct = np.array(Correct)\r\n# return pd.Series(Q[DatesEnds], index=DatesEnds), Qmax[Correct == 0]\r\n\r\n\r\n# -\r\n\r\n# ## Runoff analysis \r\n\r\n# +\r\ndef Runoff_SeparateBaseflow(Qobs, Qsim):\r\n '''From observed records obtain the baseflow and runoff streamflow records.\r\n Parameters:\r\n - Qobs: Observed record dt < 1h.\r\n - Qsim: Simulated records dt < 1h.\r\n Returns: \r\n - Qh: Observed records at hourly scale.\r\n - Qsh: Simulated records at a hourly scale.\r\n - Qsep: Observed separated records at hourly scale'''\r\n #Observed series to hourly scale.\r\n Qh = Qobs.resample('1h').mean()\r\n Qh.interpolate(method='linear',inplace=True)\r\n Qsep = DigitalFilters(Qh, tipo = 'Nathan', a = 0.998)\r\n #Pre-process of simulated series to hourly scale.\r\n Qsh = Qsim.resample('1h').mean()\r\n Qsh[np.isnan(Qsh)] = 0.0\r\n #Return results\r\n return Qh, Qsh, Qsep\r\n\r\ndef Runoff_FindEvents(Qobs, Qsim, umbral = None,minTime = 1, minConcav = None, minPeak = None):\r\n '''Separates runoff from baseflow and finds the events.\r\n Parameters:\r\n - Qobs: Hourly obseved streamflow.\r\n - Qsim: Hourly simulated streamflow.\r\n - minTime: minimum duration of the event.\r\n - minConcav: minimum concavity of the event.\r\n - minPeak: minimum value of the peakflows.\r\n Returns: \r\n - pos1: pandas index lists with the initial positions.\r\n - pos2: pandas index lists with the end positions.'''\r\n #Obtain the positions of the start and \r\n if umbral is None:\r\n umbral = np.percentile(Qobs[np.isfinite(Qobs)], 20)\r\n pos1, pos2 = __Runoff_Get_Events__(Qsim, umbral)\r\n pos1, pos2 = __Runoff_Del_Events__(Qobs, pos1, pos2, minTime=1, minConcav=minConcav, minPeak = minPeak)\r\n #Returns results \r\n return pos1, pos2\r\n\r\ndef Runoff_CompleteAnalysis(Area, Qobs, Rain, Qsep, pos1, pos2, N=None, Nant = None):\r\n '''Obtains the DataFrame with the resume of the RC analysis.\r\n Parameters:\r\n - Area: the area of the basin in km2.\r\n - Qobs: Hourly observed streamflow.\r\n - Rain: Hourly rainfall.\r\n - Qsep: Hourly dataFrame with the separated flows.\r\n - pos1: pandas index lists with the initial positions.\r\n - pos2: pandas index lists with the end positions.\r\n - N: Number of days to eval the rainfall between p1-N: p2.\r\n - Nant: Number of antecedent days to eval the rainfall between p1-Nant : p1-N.\r\n Results:\r\n - DataFrame with the columns: RC, RainEvent, RainBefore, RainInt, Qmax'''\r\n #Search for N\r\n if N is None:\r\n #Time window based on the basin area.\r\n N = Area**0.2\r\n N = np.floor(N) // 2 * 2 + 1\r\n if N<3: N = 3\r\n if N>11: N = 11 \r\n Ndays = pd.Timedelta(str(N)+'d')\r\n if Nant is None:\r\n Nant = pd.Timedelta(str(N+3)+'d')\r\n else:\r\n Ndays = N\r\n if Nant is None:\r\n Nant = N + pd.Timedelta('3d')\r\n \r\n #Lists of data\r\n RC = []\r\n RainTot = []\r\n Date = []\r\n Qmax = []\r\n RainInt = []\r\n RainAnt = []\r\n\r\n #Get Values for events\r\n for pi,pf in zip(pos1, pos2):\r\n #General variables obtention\r\n Runoff = Qsep['Runoff'][pi:pf+Ndays].sum()*3600.\r\n Rainfall = (Rain[pi-Ndays:pf].sum()/1000.)*(Area*1e6)\r\n #Runoff and streamflow List updates\r\n Qmax.append(Qobs[pi:pf].max())\r\n RC.append(Runoff / Rainfall)\r\n #Rainfall list updates\r\n RainTot.append(Rain[pi-Ndays:pf].sum())\r\n RainInt.append(Rain[pi-Ndays:pf].max())\r\n RainAnt.append(Rain[pi-Ndays-Nant:pi-Ndays].sum())\r\n #Dates.\r\n Date.append(pi)\r\n #Converts to arrays\r\n RC = np.array(RC)\r\n RainTot = np.array(RainTot)\r\n RainInt = np.array(RainInt)\r\n RainAnt = np.array(RainAnt)\r\n Date = np.array(Date)\r\n Qmax = np.array(Qmax)\r\n #Select the correct values\r\n p1 = np.where(np.isfinite(RC))[0]\r\n p2 = np.where((RC[p1]<=1.0) & (RC[p1]>0.0))[0]\r\n #Lo que es \r\n RC = RC[p1[p2]]\r\n RainTot = RainTot[p1[p2]]\r\n RainInt = RainInt[p1[p2]]\r\n RainAnt = RainAnt[p1[p2]]\r\n Date = Date[p1[p2]]\r\n Qmax = Qmax[p1[p2]]\r\n #Los malos \r\n pos = np.where((RC>0.04) & (RainTot<10))[0]\r\n #Depura de nuevo \r\n RC = np.delete(RC, pos)\r\n RainTot = np.delete(RainTot, pos)\r\n RainInt = np.delete(RainInt, pos)\r\n RainAnt = np.delete(RainAnt, pos)\r\n Date = np.delete(Date, pos)\r\n Qmax = np.delete(Qmax, pos)\r\n #Turns things into a DataFrame\r\n Data = pd.DataFrame(\r\n np.vstack([RC, RainTot, RainAnt, RainInt, Qmax]).T,\r\n index= Date, \r\n columns=['RC', 'RainEvent', 'RainBefore','RainInt','Qmax'])\r\n return Data\r\n\r\ndef Runoff_groupByRain(D, groupby = 'RainEvent' , bins = None,\r\n Vmin=None, Vmax=None, Nb = 10, logx = True):\r\n '''Group the values of RC in function of a variable.\r\n Parameters:\r\n - D: pandas Dataframe with the results from the RC analysis.\r\n - groupby: name of the column to use for the groups.\r\n - Vmin: minimum value to set the groups.\r\n - Vmax: max value to set the groups.\r\n - b: number of bins.\r\n - logx: use or not logaritmic X axis.\r\n Results:\r\n - Dictionary with the RC by groups, P25, P50, P90, mean value of the variable\r\n for grouping, Variable for groups.'''\r\n #Change if the axis X is logarithm or not\r\n if logx:\r\n x = np.log(D[groupby])\r\n else:\r\n x = D[groupby]\r\n #SEt max y min \r\n if Vmin is None: Vmin = x.min()\r\n if Vmax is None: Vmax = x.max()\r\n #SEt the intervals\r\n if bins is None:\r\n b = np.linspace(Vmin, Vmax, Nb)\r\n else:\r\n b = bins\r\n #Make the groups\r\n DicStats = {'RC':[],'P25':[],'P75':[],'P50':[], 'X': [], groupby: []} \r\n for i,j in zip(b[:-1], b[1:]):\r\n p = np.where((x>=i) & (x<=j))[0]\r\n if p.size > 0:\r\n DicStats['RC'].append(D['RC'][p])\r\n DicStats['P25'].append(np.percentile(D['RC'][p], 25))\r\n DicStats['P50'].append(np.percentile(D['RC'][p], 50))\r\n DicStats['P75'].append(np.percentile(D['RC'][p], 75))\r\n DicStats['X'].append((i+j)/2.)\r\n DicStats[groupby].append(x[p])\r\n return DicStats\r\n#-------------------------------------------------------------------------------------------\r\n## Backgroudn functions.\r\n\r\ndef __Runoff_Get_Events__(Q, Umbral):\r\n '''Obtais the initia and end dates of the events related to \r\n a time series based on the results from the Asynch 190.\r\n Parameters:\r\n - Q: pandas series with the streamflow (simulated from asynch 190 no infiltration).\r\n - perc: percentile used to stablish runoff occurrence.\r\n Returns:\r\n - pos1: initial date of each event.\r\n - pos2: end date of each event''' \r\n #Treshold and positions with values over it\r\n pos = np.where(Q.values > Umbral)[0]\r\n #Positions start and end.\r\n Dpos = pos[1:] - pos[:-1]\r\n Dpos1 = pd.Series(Dpos, Q.index[pos[1:]])\r\n pos1 = Dpos1[Dpos1>1].index\r\n pos1 = pos1.insert(0, Q.index[pos][0])\r\n pos1 = pos1[:-1]\r\n Dpos2 = pd.Series(Dpos, Q.index[pos[:-1]])\r\n pos2 = Dpos2[Dpos2>1].index\r\n #returns results \r\n return pos1, pos2\r\n\r\ndef __Runoff_Get_eventsPeaks__(Q, pos1, pos2):\r\n '''Obtains the peaks of the observed events selected by the \r\n criteria of the asynch 190 model\r\n PArameters:\r\n - Q: Pandas series qwith the observed data.\r\n - pos1: list with the start of the peaks.\r\n - pos2: list with the end of the peaks.\r\n Returns:\r\n - List with the peaks corresponding to the events.'''\r\n #Peak at each event \r\n Peaks = []\r\n for p1, p2 in zip(pos1, pos2):\r\n Peaks.append(np.nanmax(Q[p1:p2].values))\r\n return Peaks\r\n\r\ndef __Runoff_Del_Events__(Q, pos1, pos2, minTime = 2.5, minPeak = None, minConcav = None):\r\n '''Eliminates events from the selected initial peaks based on different \r\n aspects such as min time of the event, min peak and the concativity.\r\n Parameters:\r\n - Q: pandas series with the observed streamflow.\r\n - pos1: Pandas indexes with the start of the events.\r\n - pos2: Pandas indexes with the end of the events.\r\n - minTime: minimum time (days) of the duration of the hydrographs.\r\n - minPeak: minim value of the peak at the hydrographs.\r\n - minConcat: minimum concativity for the hydrograph (suggested: 10).\r\n Returns:\r\n - starts: pandas index with the corrected starts.\r\n - ends: pandas indexes with the corrected ends.'''\r\n #Eliminates events based on their duration\r\n if minTime is not None:\r\n #Obtains the duration\r\n Td = pos2 - pos1\r\n Td = Td.total_seconds()/(3600*24)\r\n Td = Td.values\r\n #Eliminates\r\n p = np.where(Td 0.5:\r\n\t\t\t\t# compute the (x, y)-coordinates of the bounding box for\r\n\t\t\t\t# the object\r\n\t\t\t\tbox = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\r\n\t\t\t\t(startX, startY, endX, endY) = box.astype(\"int\")\r\n\t\t\t\t# ensure the bounding boxes fall within the dimensions of\r\n\t\t\t\t# the frame\r\n\t\t\t\t(startX, startY) = (max(0, startX), max(0, startY))\r\n\t\t\t\t(endX, endY) = (min(w - 1, endX), min(h - 1, endY))\r\n\r\n\r\n\t\t\t\t# extract the face ROI, convert it from BGR to RGB channel\r\n\t\t\t\t# ordering, resize it to 224x224, and preprocess it\r\n\t\t\t\tface = frame[startY:endY, startX:endX]\r\n\t\t\t\tface = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)\r\n\t\t\t\tface = cv2.resize(face, (224, 224))\r\n\t\t\t\tface = img_to_array(face)\r\n\t\t\t\tface = preprocess_input(face)\r\n\t\t\t\t# add the face and bounding boxes to their respective\r\n\t\t\t\t# lists\r\n\t\t\t\tfaces.append(face)\r\n\t\t\t\tlocs.append((startX, startY, endX, endY))\r\n\r\n\r\n\t\t# only make a predictions if at least one face was detected\r\n\t\tif len(faces) > 0:\r\n\t\t\t# for faster inference we'll make batch predictions on *all*\r\n\t\t\t# faces at the same time rather than one-by-one predictions\r\n\t\t\t# in the above `for` loop\r\n\t\t\tfaces = np.array(faces, dtype=\"float32\")\r\n\t\t\tpreds = maskNet.predict(faces, batch_size=32)\r\n\t\t# return a 2-tuple of the face locations and their corresponding\r\n\t\t# locations\r\n\t\treturn (locs, preds)\r\n\r\n\r\n\r\n\tbase_dir=os.getcwd()\r\n\tbase_dir=base_dir.replace('\\\\','/')\r\n\r\n\tprint(base_dir)\r\n\tdataset_path=base_dir+'/dataset'\r\n\taccuracy_plot_dir=base_dir+'/Model'\r\n\tmodel_store_dir=base_dir+'/Model/mask_detector.model'\r\n\texample=base_dir+'/Image/1.jpg'\r\n\r\n\tconfidence=0.4\r\n\r\n\r\n\tface_detector_caffe=base_dir+'/Face Detector/res10_300x300_ssd_iter_140000.caffemodel'\r\n\r\n\t# construct the argument parser and parse the arguments\r\n\t# ap = argparse.ArgumentParser()\r\n\t# ap.add_argument(\"-f\", \"--face\", type=str,\r\n\t# \tdefault=\"face_detector\",\r\n\t# \thelp=\"path to face detector model directory\")\r\n\t# ap.add_argument(\"-m\", \"--model\", type=str,\r\n\t# \tdefault=\"mask_detector.model\",\r\n\t# \thelp=\"path to trained face mask detector model\")\r\n\t# ap.add_argument(\"-c\", \"--confidence\", type=float, default=0.5,\r\n\t# \thelp=\"minimum probability to filter weak detections\")\r\n\t# args = vars(ap.parse_args())\r\n\r\n\r\n\t# load our serialized face detector model from disk\r\n\tprint(\"[INFO] loading face detector model...\")\r\n\tprototxtPath = base_dir+'/Face Detector/deploy.prototxt'\r\n\tweightsPath = face_detector_caffe\r\n\tfaceNet = cv2.dnn.readNet(prototxtPath, weightsPath)\r\n\t# load the face mask detector model from disk\r\n\tprint(\"[INFO] loading face mask detector model...\")\r\n\tmaskNet = load_model(model_store_dir)\r\n\t# initialize the video stream and allow the camera sensor to warm up\r\n\tprint(\"[INFO] starting video stream...\")\r\n\t#vs = VideoStream(src='data.mp4').start()\r\n\t#time.sleep(2.0)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t# loop over the frames from the video stream\r\n\titer=0\r\n\twhile vs.more():\r\n\r\n\t\titer+=1\r\n\r\n\r\n\r\n\t\t# grab the frame from the threaded video stream and resize it\r\n\t\t# to have a maximum width of 400 pixels\r\n\t\tframe = vs.read()\r\n\r\n\t\tframe = imutils.resize(frame, width=1200)\r\n\r\n\t\t#resized = cv2.resize(frame, dim, interpolation=cv2.INTER_AREA)\r\n\r\n\t\t(H, W) = frame.shape[:2]\r\n\t\tprint(H,W)\r\n\t\tln = net.getLayerNames()\r\n\t\tln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]\r\n\t\tblob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (224, 224), swapRB=True, crop=False)\r\n\t\tnet.setInput(blob)\r\n\t\tstart = time.time()\r\n\t\tlayerOutputs = net.forward(ln)\r\n\t\tend = time.time()\r\n\t\t# print(\"Frame Prediction Time : {:.6f} seconds\".format(end - start))\r\n\t\tboxes = []\r\n\t\tconfidences = []\r\n\t\tclassIDs = []\r\n\r\n\t\tfor output in layerOutputs:\r\n\t\t\tfor detection in output:\r\n\t\t\t\tscores = detection[5:]\r\n\t\t\t\tclassID = np.argmax(scores)\r\n\t\t\t\tconfidence = scores[classID]\r\n\t\t\t\tif confidence > 0.1 and classID == 0:\r\n\t\t\t\t\tbox = detection[0:4] * np.array([W, H, W, H])\r\n\t\t\t\t\t(centerX, centerY, width, height) = box.astype(\"int\")\r\n\t\t\t\t\tx = int(centerX - (width / 2))\r\n\t\t\t\t\ty = int(centerY - (height / 2))\r\n\t\t\t\t\tboxes.append([x, y, int(width), int(height)])\r\n\t\t\t\t\tconfidences.append(float(confidence))\r\n\t\t\t\t\tclassIDs.append(classID)\r\n\r\n\t\tif iter % 1 == 0:\r\n\r\n\t\t\tidxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.45, 0.3)\r\n\t\t\tind = []\r\n\t\t\tfor i in range(0, len(classIDs)):\r\n\t\t\t\tif (classIDs[i] == 0):\r\n\t\t\t\t\tind.append(i)\r\n\t\t\ta = []\r\n\t\t\tb = []\r\n\r\n\t\t\tif len(idxs) > 0:\r\n\t\t\t\tfor i in idxs.flatten():\r\n\t\t\t\t\t(x, y) = (boxes[i][0], boxes[i][1])\r\n\t\t\t\t\t(w, h) = (boxes[i][2], boxes[i][3])\r\n\t\t\t\t\ta.append(x)\r\n\t\t\t\t\tb.append(y)\r\n\r\n\t\t\tdistance = []\r\n\t\t\tnsd = []\r\n\t\t\tfor i in range(0, len(a) - 1):\r\n\t\t\t\tfor k in range(1, len(a)):\r\n\t\t\t\t\tif (k == i):\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tx_dist = (a[k] - a[i])\r\n\t\t\t\t\t\ty_dist = (b[k] - b[i])\r\n\t\t\t\t\t\td = math.sqrt(x_dist * x_dist + y_dist * y_dist)\r\n\t\t\t\t\t\tdistance.append(d)\r\n\t\t\t\t\t\tif (d <= 1000):\r\n\t\t\t\t\t\t\tnsd.append(i)\r\n\t\t\t\t\t\t\tnsd.append(k)\r\n\t\t\t\t\t\tnsd = list(dict.fromkeys(nsd))\r\n\t\t\t\t\t# print(nsd)\r\n\r\n\t\t\tsafe_count=0\r\n\r\n\t\t\tcolor = (0, 0, 255)\r\n\t\t\tfor i in nsd:\r\n\t\t\t\t(x, y) = (boxes[i][0], boxes[i][1])\r\n\t\t\t\t(w, h) = (boxes[i][2], boxes[i][3])\r\n\t\t\t\tcv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)\r\n\t\t\t\ttext = \"Alert\"\r\n\t\t\t\tcv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)\r\n\t\t\tcolor = (0, 255, 0)\r\n\t\t\tif len(idxs) > 0:\r\n\t\t\t\tfor i in idxs.flatten():\r\n\t\t\t\t\tif (i in nsd):\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\t(x, y) = (boxes[i][0], boxes[i][1])\r\n\t\t\t\t\t\t(w, h) = (boxes[i][2], boxes[i][3])\r\n\t\t\t\t\t\tcv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)\r\n\t\t\t\t\t\ttext = 'OK'\r\n\t\t\t\t\t\tsafe_count+=1\r\n\t\t\t\t\t\tcv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)\r\n\r\n\t\ttext = \"Social Distancing Violations: {}\".format(len(nsd))\r\n\t\tcv2.putText(frame, text, (660, frame.shape[0] - 45),\r\n\t\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 4)\r\n\r\n\t\tcv2.putText(frame, \"Covid Guard: Team TrojanWave\", (140, 45),\r\n\t\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)\r\n\t\tcv2.rectangle(frame, (20, 60), (1170, 100), (170, 170, 170), 2)\r\n\t\tcv2.putText(frame, \"COLOR CODE: RISK ANALYSIS\", (30, 85),\r\n\t\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1)\r\n\t\tcv2.putText(frame, \"--- GREEN : SAFE\", (500, 85),\r\n\t\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)\r\n\t\tcv2.putText(frame, \"--- RED: UNSAFE\", (1000, 85),\r\n\t\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)\r\n\r\n\r\n\r\n\r\n\t\ttot_str = \"TOTAL: \" + str(len(idxs))\r\n\t\thigh_str = \"HIGH RISK: \" + str(len(nsd))\r\n\t\tlow_str = \"LOW RISK: \" + str(0)\r\n\t\tsafe_str = \"SAFE: \" + str(safe_count)\r\n\r\n\t\tsub_img = frame[H - 270: H , 0:240]\r\n\t\tblack_rect = np.ones(sub_img.shape, dtype=np.uint8) * 0\r\n\r\n\t\tres = cv2.addWeighted(sub_img, 0.8, black_rect, 0.2, 1.0)\r\n\r\n\t\tframe[H - 270:H, 0:240] = res\r\n\r\n\t\tcv2.putText(frame, tot_str, (10, H - 235),\r\n\t\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)\r\n\t\tcv2.putText(frame, safe_str, (10, H - 200),\r\n\t\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)\r\n\t\tcv2.putText(frame, low_str, (10, H - 165),\r\n\t\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 120, 255), 2)\r\n\t\tcv2.putText(frame, high_str, (10, H - 130),\r\n\t\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 150), 2)\r\n\r\n\t\t#cv2.imshow(\"Social Distancing Detector\", frame)\r\n\r\n\t\tcv2.rectangle(frame, (10, H-100 ), (600, H-10), (170, 170, 170), 2)\r\n\t\tcv2.putText(frame, \"COLOR CODE: MASK DETECTION\", (40, H-40),\r\n\t\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 0), 2)\r\n\t\tcv2.putText(frame, \"--- RED : NO MASK\", (420, H-70),\r\n\t\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)\r\n\t\tcv2.putText(frame, \"--- GREEN : MASK\", (420, H-35),\r\n\t\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)\r\n\r\n\t\t# cv2.putText(frame, \"-- GREEN: SAFE\", (565, 150),\r\n\t\t# \t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)\r\n\r\n\t\t# detect faces in the frame and determine if they are wearing a\r\n\t\t# face mask or not\r\n\t\t(locs, preds) = detect_and_predict_mask(frame, faceNet, maskNet)\r\n\r\n\t\t# loop over the detected face locations and their corresponding\r\n\t\t# locations\r\n\t\tfor (box, pred) in zip(locs, preds):\r\n\t\t\t# unpack the bounding box and predictions\r\n\t\t\t(startX, startY, endX, endY) = box\r\n\t\t\t(mask, withoutMask) = pred\r\n\t\t\tprint(\"mask\",mask,withoutMask)\r\n\t\t\t# determine the class label and color we'll use to draw\r\n\t\t\t# the bounding box and text\r\n\t\t\tlabel = \"Mask\" if mask > (withoutMask+0.90) else \"No Mask\"\r\n\t\t\tcolor = (0, 255, 0) if label == \"Mask\" else (0, 0, 255)\r\n\t\t\t# include the probability in the label\r\n\t\t\tlabel = \"{}: {:.2f}%\".format(label, max(mask, withoutMask) * 100)\r\n\t\t\t# display the label and bounding box rectangle on the output\r\n\t\t\t# frame\r\n\t\t\tcv2.putText(frame, label, (startX, startY - 10),\r\n\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)\r\n\t\t\tcv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)\r\n\r\n\r\n\t\t# show the output frame\r\n\t\tcv2.namedWindow('frame', cv2.WINDOW_NORMAL)\r\n\t\tcv2.setWindowProperty('frame', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)\r\n\t\tcv2.imshow('frame', frame)\r\n\t\tfps.update()\r\n\t\tkey = cv2.waitKey(1) & 0xFF\r\n\t\t# if the `q` key was pressed, break from the loop\r\n\r\n\r\n\r\n\r\n\t\tif key == ord(\"q\"):\r\n\t\t\tbreak\r\n\r\n\r\n\r\n\t# do a bit of cleanup\r\n\tcv2.destroyAllWindows()\r\n\tvs.stop()\r\n\r\nmainc()","sub_path":"running_video_file.py","file_name":"running_video_file.py","file_ext":"py","file_size_in_byte":11228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"500788939","text":"import statistics\nimport csv \nimport matplotlib.pyplot as plt\nfrom datetime import datetime\n\nwork=\"vientos.csv\"\nwith open(work) as f:\n read=csv.reader(f)\n cabezera=next(read)\n\n\n dates_v=[]\n vientos=[]\n for row in read:\n current_date_v=datetime.strptime(row[3],'%d/%m/%Y')\n try:\n v=float(row[5])\n \n \n except ValueError:\n print(f\"Missing data for {current_date_v}\")\n \n else:\n dates_v.append(current_date_v)\n vientos.append(v)\n \ncant_v=0\nfor i in dates_v:\n cant_v+=1\n\narreglo_cant_datos_anual_v=[]\npromedio_datos_anual_v=[]\nfor a in range(1998,2019):\n #bucle para añadir informacion al arreglo: \n cant_datos_v=0 \n suma_datos_v=0\n for i in range(0,cant_v):\n if dates_v[i].year==a:\n cant_datos_v+=1\n suma_datos_v+=vientos[i]\n \n \n prom_datos_anual_v=suma_datos_v/cant_datos_v\n \n promedio_datos_anual_v.append(prom_datos_anual_v)\n \n \narreglo_cant_datos_mensuales_v=[] \npromedio_datos_mensuales_v=[] \n \nfor i in range(1,13):\n cant_datos_mensual_v=0\n suma_datos_mensual_v=0 \n for a in range(0,cant_v):\n if dates_v[a].month==i:\n cant_datos_mensual_v+=1\n suma_datos_mensual_v+=vientos[a]\n \n promedio_datos_v=suma_datos_mensual_v/cant_datos_mensual_v\n \n arreglo_cant_datos_mensuales_v.append(cant_datos_mensual_v)\n promedio_datos_mensuales_v.append(promedio_datos_v)\n\n\npromedio_datos_anual_v\nyear=[]\nfor i in range(1998,2019):\n i+=0\n year.append(i)\n\nfig,ax=plt.subplots()\nplt.style.use(\"seaborn\")\nax.plot(year,promedio_datos_anual_v,linewidth=5,c=\"green\")\nax.set_title(\"Promedido anual de la velocidad del viento\",fontsize=20)\nax.set_xlabel(\"Años\",fontsize=15)\nax.set_ylabel(\"velocidad (m/s)\",fontsize=20)\nax.tick_params(axis=\"both\",which=\"major\",labelsize=19)\nax.axis([1998,2018,0,13])\n\nplt.show()\n\npromedio_datos_mensuales_v\nmeses=[\"Ene\",\"Feb\",\"Mar\",\"Abr\",\"May\",\"Jun\",\"Jul\",\"Ago\",\"Sep\",\"Oct\",\"Nov\",\"Dic\"]\nfig,ax=plt.subplots()\nplt.style.use(\"seaborn\")\nax.plot(meses,promedio_datos_mensuales_v,linewidth=5,c=\"black\")\nax.set_title(\"Promedio estacional de la velocidad del viento\",fontsize=20)\nax.set_xlabel(\"Meses\",fontsize=15)\nax.set_ylabel(\"velocidad (m/s)\",fontsize=20)\nax.tick_params(axis=\"both\",which=\"major\",labelsize=15)\nplt.show()\n\n","sub_path":"pi3.py","file_name":"pi3.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"450856048","text":"'''\r\nCreated on Nov 1, 2017\r\n\r\n@author: Bilbo\r\n'''\r\nimport time\r\nfrom random import randint\r\nimport random\r\nimport numpy as np\r\nimport matplotlib\r\nmatplotlib.use('TkAgg')\r\nimport matplotlib.pyplot as plt\r\nimport igraph\r\nfrom igraph import Graph\r\nfrom scipy import stats\r\n\r\nc=1\r\nb=4\r\n\r\nstartTime=time.time()\r\n\r\npopulation=[]\r\npopulationSize=100\r\nnumberOfTimeSteps=2000\r\ncurrTimeStep=0\r\nmutationRate=.001\r\niterations=50\r\n\r\n\r\nstrategies=[\"ALL_C\", \"ALL_D\", \"Tit4Tat\", \"CautiousTit\", \"Alternate\", \"Random\"]\r\nstratsSize=6\r\n\r\ndata=np.zeros((stratsSize,numberOfTimeSteps))\r\n\r\nsimulationRuns=5\r\ndegreeDistributionData=np.zeros((simulationRuns, populationSize))\r\nclusteringCoefData=np.zeros((500, populationSize+1))\r\nhowManyDie=10\r\n\r\nPb=1 #this doesn't really matter rn but it's important to have bc i might end up testing lowered Pb's\r\nPn=.85\r\nPr=.017\r\nrelationships=[[0 for i in range(populationSize)]for j in range(populationSize)] \r\n\r\nclass Individual:\r\n def __init__(self, strat, pay, ind):\r\n if(strat==\"rand\"):\r\n self.strategy=strategies[randint(0, stratsSize-1)]\r\n else: \r\n self.strategy=strat\r\n self.payoff=pay\r\n self.moves=[]\r\n self.alwaysC=False\r\n self.alwaysD=False\r\n self.index=ind\r\n def computeMove(self, opponent, iter):\r\n if(self.alwaysD==True):\r\n return \"D\"\r\n if(self.alwaysC==True):\r\n return \"C\"\r\n \r\n out=\"C\"\r\n \r\n if(self.strategy==\"ALL_D\"):\r\n self.alwaysD=True\r\n out=\"D\"\r\n \r\n if(self.strategy==\"ALL_C\"):\r\n self.alwaysC=True \r\n \r\n if(self.strategy==\"Tit4Tat\"): #starting c \r\n if(iter>0):\r\n out=opponent.moves[iter-1] \r\n \r\n if(self.strategy==\"CautiousTit\"): #starting d\r\n out=\"D\" \r\n if(iter>0):\r\n out=opponent.moves[iter-1] \r\n \r\n if(self.strategy==\"Alternate\"):\r\n if(iter>0):\r\n if(self.moves[iter-1]==\"C\"):\r\n out=\"D\" \r\n \r\n if(self.strategy==\"Random\"):\r\n if(random.random()>.5):\r\n out=\"D\" \r\n return out\r\n def addToPayoff(self, gamePay):\r\n self.payoff+=gamePay\r\n def mutate(self):\r\n self.strategy=strategies[randint(0, stratsSize-1)]\r\n def findFitness(self):\r\n global iterations\r\n return self.payoff \r\n def clearMoves(self):\r\n if(len(self.moves)==iterations):\r\n for i in range(iterations):\r\n self.moves[i]=\"None\"\r\n else:\r\n for i in range(iterations):\r\n self.moves.append(\"None\") \r\n def getPopIndex(self):\r\n return self.index \r\n \r\ndef initSim():\r\n global population\r\n population=[]\r\n relationships=[[0 for i in range(populationSize)]for j in range(populationSize)]\r\n for i in range(populationSize):\r\n guy=Individual(\"rand\", 0, i)\r\n guy.clearMoves()\r\n population.append(guy) \r\n \r\n for i in range(populationSize):\r\n for j in range(i, populationSize):\r\n if(j!=i):\r\n if(random.random()<= Pr):\r\n relationships[i][j]=1\r\n relationships[j][i]=1 \r\n \r\ndef runSim():\r\n initSim()\r\n for i in range(numberOfTimeSteps):\r\n runTimeStep()\r\n return \r\n\r\ndef getOther(individual, selfIndex):\r\n ppl=[]\r\n for i in range(populationSize):\r\n if(relationships[selfIndex][i]==1):\r\n ppl.append(i)\r\n if(random.random()<.1 or len(ppl)==0):\r\n otherIndividual=population[randint(0, populationSize-1)]\r\n while(otherIndividual==individual):\r\n randIndex=randint(0, populationSize-1) \r\n otherIndividual=population[randIndex]\r\n return otherIndividual\r\n else: \r\n other=randint(0, len(ppl)-1)\r\n while(relationships[selfIndex][ppl[other]]==0):\r\n other=randint(0, len(ppl)-1)\r\n return population[ppl[other]] \r\n\r\ndef playGame(ind1, ind2):\r\n if(currTimeStep!=0):\r\n ind1.clearMoves()\r\n ind2.clearMoves()\r\n global iterations\r\n payoff2=0 #this is to keep track of the 2nd person's payoff for relationship purposes bc it isn't being saved here\r\n for i in range(iterations):\r\n move1=ind1.computeMove(ind2, i)\r\n move2=ind2.computeMove(ind1, i)\r\n ind1.moves[i]=move1\r\n ind2.moves[i]=move2\r\n if(move1==\"C\"):\r\n if(move2==\"C\"):\r\n ind1.addToPayoff(b-c)\r\n payoff2+=b-c\r\n else:\r\n ind1.addToPayoff(-c)\r\n payoff2+=b\r\n else:\r\n if(move2==\"C\"):\r\n ind1.addToPayoff(b)\r\n payoff2-=c\r\n else:\r\n ind1.addToPayoff(-c)\r\n payoff2-=c\r\n '''\r\n temporarily disabled to obtain a baseline of whether the math is good on its own \r\n if(ind1.payoff==-50 and payoff2==-50):\r\n relationships[ind1.getPopIndex()][ind2.getPopIndex()]=0\r\n relationships[ind2.getPopIndex()][ind1.getPopIndex()]=0\r\n ''' \r\ndef whoDies():\r\n Deaths=[]\r\n min=1000\r\n for i in range(populationSize):\r\n if(population[i].payoffmax):\r\n max=population[i].payoff\r\n while(len(moms) 0:\n self.recently_done_update = True\n\n","sub_path":"sale_jobs/models/sale_order.py","file_name":"sale_order.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"356821420","text":"import csv\n\ndef main():\n with open('city.csv', 'r', encoding='utf-8') as file:\n reader = csv.DictReader(file)\n cities_list = [row['address'].split('г ')[-1].lower() for row in reader]\n\n \n used_list = []\n trash_letters_list = ['ь', 'ъ', 'ы']\n last_letter = ''\n\n\n while True:\n input_text = input().lower()\n\n if not used_list:\n if input_text not in cities_list:\n print('Введенного города нет в списке')\n else:\n used_list.append(input_text)\n if input_text[-1] in trash_letters_list:\n for letter in input_text[::-1]:\n if letter in trash_letters_list:\n continue\n else:\n last_letter = letter\n break \n else:\n last_letter = input_text[-1]\n else:\n if input_text not in cities_list:\n print('Введенного города нет в списке')\n elif last_letter != input_text[0]:\n print('Первая буква введенного города не соответствует последней букве предыдущего либо город уже игрался')\n else:\n used_list.append(input_text)\n if input_text[-1] in trash_letters_list:\n for letter in input_text[::-1]:\n if letter in trash_letters_list:\n continue\n else:\n last_letter = letter\n break\n else:\n last_letter = input_text[-1]\n \n\n print(used_list, last_letter)\n\n\nif __name__ == '__main__':\n main()","sub_path":"cities_main.py","file_name":"cities_main.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"298349031","text":"from django.db import models\nfrom django.urls import reverse\nfrom django.conf import settings\nfrom django.utils import timezone\n#from accounts.models import User\n\nclass UserLog(models.Model):\n \n passcode = models.CharField(max_length=50, default='')\n \n\n def __str__(self):\n return self.passcode\n\nclass Contact(models.Model):\n first_name = models.CharField(max_length=100, blank=True)\n last_name = models.CharField(max_length=100, blank=True)\n username = models.CharField(max_length=50, default='')\n Email = models.EmailField(blank=True)\n subject = models.CharField(max_length=100)\n feedback = models.TextField()\n\n def __str__(self):\n return self.Email\n\n\nJOB_TYPE = (\n ('Part Time', 'Part Time'),\n ('Full Time', 'Full Time'),\n ('Freelance', 'Freelancer'),\n)\n\nCATEGORY = (\n ('Retail', 'Retail'),\n ('Banking', 'Banking'),\n ('Security', 'Security'),\n ('Transportation', 'Transportation'),\n ('HR', 'HR'),\n ('Marketing', 'Marketing'),\n ('IT', 'IT'),\n)\n\nclass JobListing(models.Model):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)\n title = models.CharField(max_length=100)\n company_name = models.CharField(max_length=200)\n employment_status = models.CharField(choices=JOB_TYPE, max_length=10)\n vacancy = models.CharField(max_length=10, null=True)\n category = models.CharField(choices=CATEGORY, max_length =30)\n description = models.TextField()\n responsibilities = models.TextField()\n experience = models.CharField(max_length=100)\n job_location = models.CharField(max_length=120)\n Salary = models.CharField(max_length=100)\n image = models.ImageField(blank=True, upload_to='media', null=True)\n application_deadline = models.DateTimeField()\n published_on = models.DateTimeField(default=timezone.now)\n\n\n def __str__(self):\n return self.title\n\n def get_absolute_url(self):\n return reverse(\"jobs:job-single\", args=[self.id])\n \nEDUCATION_CHOICES = (\n (40, 'Master Degree'),\n (30, 'Bachelor Degree'),\n (20, 'High School Diploma'),\n (10, 'A Level'),\n)\n\nLOCATION_CHOICES = (\n (70, '5 to 10 miles away'),\n (60, '11 to 20 miles away'),\n (50, '21 to 30 miles away'),\n (40, '31 to 40 miles away'),\n (30, '41 to 50 miles away'),\n (20, '51 to and above miles away'),\n\n)\n\nEXPERIENCE_CHOICES = (\n (60, 'Super experienced 11 years and above'),\n (50, 'Very experienced 9 to 10 years'),\n (40, 'Experienced 6 to 8 years'),\n (30, 'Moderate Experience 3 to 5 years'),\n (20, 'New 1 to 2 years'),\n (10, 'No Experience 0 to 1 year'),\n\n)\n\nNAME_CHOICES = (\n ('E', 'Elly Morrison'),\n ('A', 'Avik Amble'),\n ('B', 'Benson Adebayo'),\n)\n\nclass ApplyJob(models.Model):\n name = models.CharField(max_length=100, choices=NAME_CHOICES, default='')\n education = models.IntegerField(choices=EDUCATION_CHOICES, default='')\n experience = models.IntegerField(choices=EXPERIENCE_CHOICES, default='')\n location = models.IntegerField(choices=LOCATION_CHOICES, default='')\n bio = models.TextField(max_length=200, blank=True, null=True)\n image = models.ImageField(blank=True, upload_to='uploads/', null=True)\n \n \n def __str__(self):\n return str(self.name)\n\n\n\n\n\n\n\n","sub_path":"jobs/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"514187700","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport math\r\nfrom data import countries, meteorites\r\nfrom maps import initDataframe, printDf\r\n\r\n# Renvoie l'année à partir de la date passée en paramètre, -1 si la date n'est pas une chaîne de caractères\r\ndef getYear(date):\r\n if not isinstance(date, str):\r\n return -1\r\n date = date.split(\"/\")[2]\r\n new = date.split(\" \")[0]\r\n if new[0] == \"0\":\r\n return str(eval(new[1:-1]) + 1000)\r\n return new\r\n\r\n\r\n# Renvoie un dictionnaire contenant les statistiques (moyenne, médiane, écart type et variance) des masses des météorites\r\ndef getStatsMasses():\r\n masses = pd.Series([infos['mass'] for infos in meteorites.values() if (not isinstance(infos['mass'], str) and np.isfinite(infos['mass']))])\r\n return getStats(masses)\r\n\r\n\r\n# Renvoie un dictionnaire contenant les statistiques (moyenne, médiane, écart type et variance) du nombre de météorites tombées par pays\r\ndef getStatsAmountPerCountry():\r\n amounts = pd.Series([countries[country]['amount'] for country in countries])\r\n return getStats(amounts)\r\n\r\n# Permet de récupérer les statistiques des données passées en paramètre (données sous forme de pd.Series())\r\ndef getStats(data):\r\n moyenne = data.describe().mean()\r\n mediane = data.describe().median()\r\n ecarttype = data.describe().std()\r\n variance = data.describe().var()\r\n return {\"moyenne\": round(moyenne, 2), \"mediane\": round(mediane, 2), \"écart type\": round(ecarttype, 2), \"variance\": round(variance, 2)}\r\n\r\n\r\n# Affiche les statistiques passées en paramètre\r\ndef printStats(title, stats, unit = \"\"):\r\n print(\"\\n\" + title + \"\\n----------------\")\r\n for name, stat in stats.items():\r\n print(f'{name.capitalize()} = {stat} {unit}')\r\n print()\r\n\r\n\r\n# Permet de crééer le titre à partir des bornes min_year et max_year\r\ndef getTitleFromYear(min_year, max_year):\r\n if min_year is None and max_year is None:\r\n return \"\"\r\n elif min_year is None:\r\n return f' (jusqu\\'en {max_year})'\r\n elif max_year is None:\r\n return f' (depuis {min_year})'\r\n else:\r\n return f' (entre {min_year} et {max_year})'\r\n\r\n\r\n# Créée un histogramme représentant les logs des masses des météorites et leur nombre\r\n# Peut être filtré en indiquant l'année minimale et / ou l'année maximale\r\ndef makeHistoLogMasses(min_year=None, max_year=None):\r\n\r\n title = \"Nombre de météorites en fonction de leur masse\" + getTitleFromYear(min_year, max_year)\r\n\r\n if min_year is None and max_year is None:\r\n masses = np.log10([infos['mass'] for infos in meteorites.values() if(np.isfinite(infos['mass']) and infos['mass'] != 0)])\r\n elif min_year is None:\r\n masses = np.log10([infos['mass'] for infos in meteorites.values() if(np.isfinite(infos['mass']) and infos['mass'] != 0 and getYear(infos['date']) != -1 and eval(getYear(infos['date'])) <= max_year)])\r\n elif max_year is None:\r\n masses = np.log10([infos['mass'] for infos in meteorites.values() if(np.isfinite(infos['mass']) and infos['mass'] != 0 and getYear(infos['date']) != -1 and infos['mass'] != 0 and eval(getYear(infos['date'])) >= min_year)])\r\n else:\r\n masses = np.log10([infos['mass'] for infos in meteorites.values() if(np.isfinite(infos['mass']) and infos['mass'] != 0 and getYear(infos['date']) != -1 and eval(getYear(infos['date'])) >= min_year and eval(getYear(infos['date'])) <= max_year)])\r\n\r\n masses = [mass for mass in masses if (np.isfinite(mass))]\r\n\r\n plt.subplot(221)\r\n makeHisto(masses, title, \"Log de la masse\", \"Nombre de météorites\")\r\n\r\n\r\n# Créée un histogramme représentant le nombre de météorites tombées par nombre de pays\r\n# Peut être filtré en indiquant le nombre minimale et / ou le nombre maximale de météorites tombées sur un pays\r\ndef makeHistoAmountMeteoPerCountry(df, min_amount=None, max_amount=None):\r\n df['amount'] = df['country'].apply(\r\n lambda country: countries[country]['amount'])\r\n\r\n if min_amount is None and max_amount is None:\r\n title = \"\"\r\n data = df\r\n elif min_amount is None:\r\n title = f' (nombre <= {max_amount})'\r\n data = df[(df['amount'] <= max_amount) & (df['amount'] > 0)]\r\n elif max_amount is None:\r\n title = f' (nombre > {min_amount})'\r\n data = df[(df['amount'] > min_amount)]\r\n else:\r\n title = f' ({min_amount} < nombre <= {max_amount})'\r\n data = df[(df['amount'] <= max_amount) & (df['amount'] > min_amount)]\r\n\r\n title = \"Nombre de météorites en fonction du nombre de pays\" + title\r\n\r\n plt.subplot(222)\r\n data = data.sort_values(by=['amount'])\r\n makeHisto(data['amount'], title, \"Nombre de météorites tombées par pays\", \"Nombre de pays\", 25)\r\n\r\n\r\n# Créée un histogramme représentant le nombre de météorites tombées par année\r\n# Peut être filtré en indiquant l'année minimale et / ou l'année maximale\r\ndef makeHistoAmountMeteoPerYear(min_year=None, max_year=None):\r\n l = []\r\n title = \"Nombre de météorites tombées par année\" + getTitleFromYear(min_year, max_year)\r\n for infos in meteorites.values():\r\n year = getYear(infos['date'])\r\n if year == -1:\r\n continue\r\n else:\r\n year = eval(year)\r\n if (min_year is None and max_year is None) or (min_year is None and year <= max_year) or (max_year is None and year >= min_year) or (year >= min_year and year <= max_year):\r\n l.append(year)\r\n \r\n plt.subplot(223)\r\n makeHisto(l, title, \"Années\", \"Nombre de météorites\", 25)\r\n\r\n\r\n# Créée un histogramme représentant la répartition dans le monde des météorites par rapport au point Null Island (0, 0)\r\n# Peut être filtré en indiquant l'année minimale et / ou l'année maximale\r\ndef makeHistoRepartition(min_year=None, max_year=None):\r\n title = \"Repartition des météorites dans le monde, par rapport à Null Island\" + getTitleFromYear(min_year, max_year)\r\n\r\n placement = []\r\n for infos in meteorites.values(): \r\n lat, lon = infos['reclat'], infos['reclong']\r\n year = getYear(infos['date'])\r\n if year != -1:\r\n year = eval(year)\r\n if (min_year is None and max_year is None) or (min_year is None and max_year is not None and year <= max_year) or (min_year is not None and max_year is None and year >= min_year) or (min_year is not None and max_year is not None and year >= min_year and year <= max_year):\r\n if(math.isnan(lat) or math.isnan(lon) or (lat == 0 and lon == 0)): #filtrage des coordonnées non pertinentes\r\n placement.append(\"X\")\r\n elif (lat >= 0 and lon >= 0):\r\n placement.append(\"Nord Est\")\r\n elif (lat < 0 and lon < 0):\r\n placement.append(\"Sud Ouest\")\r\n elif (lat < 0 and lon >= 0):\r\n placement.append(\"Sud Est\")\r\n elif (lat >= 0 and lon < 0):\r\n placement.append(\"Nord Ouest\")\r\n\r\n plt.subplot(224)\r\n makeHisto(placement, title, 'Positionnement', 'Nombre de météorites')\r\n\r\n# Construit un histogramme à partir des arguments\r\ndef makeHisto(data, title, xlabel, ylabel, bins=None):\r\n plt.ylabel(ylabel)\r\n plt.xlabel(xlabel)\r\n plt.title(title)\r\n plt.hist(data, bins=bins)","sub_path":"histos.py","file_name":"histos.py","file_ext":"py","file_size_in_byte":7413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"647078070","text":"import sys\nimport numpy as np\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport keras\n# change to the path where the IMNN git clone is located\nsys.path.insert(-1,'../../information_maximiser')\nimport IMNN # make sure the path to the IMNN is given\nimport tqdm\nsys.path.insert(-1,'../') # change to path where utils_mrp is located\nimport utils_mrp\n# For making corner plots of the posterior\nimport corner # Reference: https://github.com/dfm/corner.py/\n\"\"\"\nSummarizing a 1D gaussian with unkown mean and variance\n\n\"\"\"\n\n\nclass nholder(object):\n\t\"\"\"\n\tClass to hold and store all parameters for an IMNN \n\t\"\"\"\n\tdef __init__(self, input_shape, generate_data, theta_fid, delta_theta, n_s, n_train, \n\t\tderivative_fraction, eta, parameters, num_epochs, keep_rate, verbose, \n\t\tversion):\n\t\t\"\"\"\n\t\tINITIALIZE PARAMETERS\n\t\t#______________________________________________________________\n\t\tinput_shape\t\t\t\t\tlist\tshape of the data that is generated\n\t\tgenerate_data\t\t\t\tlist\tfunction to generate the data\n\t\ttheta_fid\t\t\t\t\tlist\tfiducial parameter values\n\t\tdelta_theta\t\t\t\t\tlist \tperturbation values for fiducial param\n\t\tn_s \t\t\t\t\t\tint \tnumber of simulations\n\t\tn_train\t\t\t\t\t\tint \tnumber of splits, to make more simulations\n\t\tderivative_fraction \t\tfloat\tfraction of n_s to use for derivatives\n\t\teta \t\t\t\t\t\tfloat\tlearning rate\n\t\tparameters \t\t\t\t\tdict \tdict of parameters to feed IMNN\n\t\tnum_epochs \t\t\t\t\tint \tamount of epochs\n\t\tkeep_rate \t\t\t\t\tfloat \t(1-dropout rate), amount of nodes to keep every batch\n\t\tverbose \t\t\t\t\tint \tTODO\n\t\tversion \t\t\t\t\tfloat\tversion ID of this particular network\n\t\t\"\"\"\n\n\t\ttf.reset_default_graph()\n\t\tself.input_shape = input_shape\n\t\tself.generate_data = generate_data\n\t\tself.theta_fid = theta_fid\n\t\tself.delta_theta = delta_theta\n\t\tself.n_s = n_s\n\t\tself.n_train = n_train\n\t\tself.n_p = int(n_s * derivative_fraction)\n\t\tself.derivative_fraction = derivative_fraction\n\t\tself.eta = eta\n\t\tself.num_epochs = num_epochs\n\t\tself.keep_rate = keep_rate\n\t\tself.verbose = verbose\n\t\tself.rescaled = False\n\n\t\tself.data, self.der_den = self.create_data()\n\t\t# Make parameters dictionary of params that are always the same or defined\n\t\t# by other parameters\t\n\t\tself.parameters = { 'number of simulations': self.n_s,\n\t\t\t\t\t\t\t'preload data': self.data,\n\t\t\t\t\t\t\t'derivative denominator': self.der_den,\n\t\t\t\t\t\t\t'number of simulations': self.n_s,\n\t\t\t\t\t\t\t'fiducial θ': self.theta_fid,\n\t\t\t\t\t\t\t'differentiation fraction': self.derivative_fraction,\n\t\t\t\t\t\t\t'input shape': self.input_shape,\n\t\t\t\t\t\t}\n\t\t# Add user parameters to this dictionary\n\t\tfor key, value in parameters.items():\n\t\t\tself.parameters[key] = value\n\n\t\t# For saving the settings\n\t\tself.modelversion = version \n\t\tself.modelloc = 'Models/' #location where the models (networks) are saved\n\t\t\n\t\t#the file in which the network settings will be saved\n\t\tself.modelsettings_name = 'modelsettings2.csv' \n\n\t\tself.modelsettings = {'Version' : str(self.modelversion),\n\t\t\t\t\t\t'Learning rate': str(self.eta),\n\t\t\t\t\t\t'Keep rate': str(self.keep_rate),\n\t\t\t\t\t\t'num_epochs': str(self.num_epochs),\n\t\t\t\t\t\t'n_train': str(self.n_train),\n\t\t\t\t\t\t'delta_theta': str(self.delta_theta)\n\t\t\t\t\t\t}\n\t\t# Add user parameters to modelsettings\n\t\t# except these from the parameters dictionary\n\t\tnot_save = ['preload data', 'derivative denominator', 'verbose']\n\t\tfor key, value in self.parameters.items():\n\t\t\tif key == 'activation':\n\t\t\t\t# e.g., save only the string 'leaky relu'\n\t\t\t\tvalue = str(value).split(' ')[1]\n\t\t\telif key in not_save:\n\t\t\t\tcontinue\n\t\t\tself.modelsettings[key] = str(value) # parse everything to string\n\n\t\t# Holders for the Final F train and Final F test after training network\n\t\tself.modelsettings['Final detF train'] = ''\n\t\tself.modelsettings['Final detF test'] = ''\n\n\t\t# For saving the figures\n\t\tself.figuredir = 'Figures/'\n\n\t\t# For saving the network history\n\t\tself.historydir = 'History/'\n\n\t\t# Check if folders exist, create directory if necessary\n\t\tutils_mrp.checkFolders([self.modelloc, self.figuredir, self.historydir])\n\n\t\t# Check if modelsettings.csv file exists, create if necessary\n\t\tutils_mrp.checkFiles([self.modelsettings_name])\n\n\t\t# Save settings for this model\n\t\tutils_mrp.save_model_settings(self, self.modelsettings)\n\n\tdef create_data(self):\n\t\t\"\"\"\n\t\tGenerate the training and test data for the network\n\n\t\tRETURNS\n\t\t#______________________________________________________________\n\n\t\tdata \t\t\t\t\tdict \tdict containing training and test data\n\t\tder_den\t\t\t\t\tarray\tarray containing the derivative denominator\n\n\t\t\"\"\"\n\n\t\t# Number of upper and lower simulations\n\t\tn_p = int(self.n_s * self.derivative_fraction)\n\n\t\t# set a seed to surpress the sample variance\n\t\tseed = np.random.randint(1e6)\n\t\tnp.random.seed(seed)\n\t\t# Perturb lower \n\t\tt_m = self.generate_data(np.array([self.theta_fid for i in \n\t\t\t\t\trange(self.n_train * self.n_p)]), train = -self.delta_theta)\n\t\tnp.random.seed(seed)\n\t\t# Perturb higher \n\t\tt_p = self.generate_data(np.array([theta_fid for i in \n\t\t\t\t\trange(self.n_train * self.n_p)]), train = self.delta_theta)\n\t\tnp.random.seed()\n\n\t\tt = self.generate_data(np.array([self.theta_fid for i in \n\t\t\t\t\trange(self.n_train * self.n_s)]), train = None)\n\t\tnp.random.seed()\n\n\t\tder_den = 1. / (2. * self.delta_theta)\n\n\t\tdata = {\"x_central\": t, \"x_m\": t_m, \"x_p\":t_p}\n\n\t\t# Repeat the same story to generate training data\n\t\tseed = np.random.randint(1e6)\n\t\tnp.random.seed(seed)\n\t\t# Perturb lower \n\t\ttt_m = self.generate_data(np.array([self.theta_fid for i in \n\t\t\t\t\trange(self.n_train * self.n_p)]), train = -self.delta_theta)\n\t\tnp.random.seed(seed)\n\t\t# Perturb higher \n\t\ttt_p = self.generate_data(np.array([self.theta_fid for i in \n\t\t\t\t\trange(self.n_train * self.n_p)]), train = self.delta_theta)\n\t\tnp.random.seed()\n\n\t\ttt = self.generate_data(np.array([self.theta_fid for i in \n\t\t\t\t\trange(self.n_train * self.n_s)]), train = None)\n\t\tnp.random.seed()\n\t\tdata[\"x_central_test\"] = tt\n\t\tdata[\"x_m_test\"] = tt_m\n\t\tdata[\"x_p_test\"] = tt_p\n\n\t\treturn data, der_den\n\n\tdef rescale_data(self):\n\t\t\"\"\"\n\t\tRescaling the input data. \n\t\t\"\"\"\n\n\t\tself.rescaled = True\n\n\t\t'''\n\t\t# Anti standardization\n\t\tfor key in self.data.keys():\n\t\t\tself.data[key] += 5\n\t\t\tself.data[key] *= 3\n\t\t'''\n\n\t\t# Scale by subtracting the mean and dividing by std\n\t\tmu = np.mean(self.data['x_central'])\n\t\tsigma = np.nanstd(self.data['x_central'])\n\t\tfor key in self.data.keys():\n\t\t\tself.data[key] -= mu\n\t\t\tself.data[key] /= sigma\n\n\n\tdef plot_data(self, show=False):\n\t\t\"\"\" \n\t\tPlot the data as data amplitude\n\n\t\tVARIABLES\n\t\t#______________________________________________________________\n\t\tshow \t\t\t\t\tbool\twhether or not plt.show() is called\n\t\tdata \t\t\t\t\tdict \tdict containing training and test data\n\n\t\t\"\"\"\n\n\t\tfig, ax = plt.subplots(1, 1, figsize = (10, 6))\n\t\t# plot one random row from the simulated data \n\t\tax.plot(self.data['x_central'][np.random.randint(self.n_train * self.n_s)]\n\t\t\t, label = \"training data\")\n\n\t\tax.plot(self.data['x_central_test'][np.random.randint(self.n_s)]\n\t\t\t, label = \"test data\")\n\n\t\tax.legend(frameon = False)\n\t\t# ax.set_xlim([0, 9])\n\t\tax.set_xticks([])\n\t\tax.set_ylabel(\"Data amplitude\")\n\t\tplt.savefig(f'{self.figuredir}data_visualization_{self.modelversion}.png')\n\t\tif show: plt.show()\n\t\tplt.close()\n\n\tdef plot_data_hist(self, show=False):\n\t\t\"\"\" \n\t\tPlot the data as histogram \n\n\t\tINPUTS\n\t\t#______________________________________________________________\n\t\tshow \t\t\t\t\tbool\twhether or not plt.show() is called\n\t\tdata \t\t\t\t\tdict \tdict containing training and test data\n\n\t\t\"\"\"\n\t\tfig, ax = plt.subplots(2, 1 ,figsize= (15,10))\n\n\t\tax[0].hist(self.data['x_central'][np.random.randint(self.n_train*self.n_s)]\n\t\t\t,label='training data',alpha=0.5)\n\n\t\tax[0].legend(frameon = False)\n\t\tax[0].set_xlabel(\"Data amplitude\")\n\t\tax[0].set_ylabel('Counts')\n\t\tax[0].set_title('%i data points'%self.input_shape[0])\n\t\tif not self.rescaled: ax[0].set_xlim(0,6)\n\n\t\tax[1].hist(self.data['x_central_test'][np.random.randint(self.n_s)]\n\t\t\t,label='test data',alpha=0.5)\n\n\t\tax[1].legend(frameon = False)\n\t\tax[0].set_title('%i data points'%self.input_shape[0])\n\t\tax[1].set_xlabel(\"Data amplitude\")\n\t\tax[1].set_ylabel('Counts')\n\t\tif not self.rescaled: ax[1].set_xlim(0,6)\n\t\t\n\t\tplt.savefig(f'{self.figuredir}data_visualization_hist_{self.modelversion}.png')\n\t\tif show: plt.show()\n\t\tplt.close()\n\n\tdef plot_derivatives(self, show=False):\n\t\t\"\"\" \n\t\tPlot the upper and lower perturbed data as data amplitude\n\n\t\tVARIABLES\n\t\t#______________________________________________________________\n\t\tshow \t\t\t\t\tbool\twhether or not plt.show() is called\n\t\tdata \t\t\t\t\tdict \tdict containing training and test data\n\n\t\t\"\"\"\n\n\t\tfig, ax = plt.subplots(2, 2, figsize = (15, 10))\n\t\t# plt.subplots_adjust(wspace = 0, hspace = 0.1)\n\t\ttraining_index = np.random.randint(self.n_train * self.n_p)\n\t\t\n\t\txp_theta1, xp_theta2 = self.data['x_p'][training_index]\n\n\t\t# Theta 1 upper simulation\n\t\tax[0, 0].plot(self.data['x_p'][training_index, 0], label = \"upper training data\"\n\t\t\t, color = 'C0', linestyle='dashed')\n\t\t# Theta 2 upper simulation\n\t\tax[0, 1].plot(self.data['x_p'][training_index, 1], label = \"upper training data\"\n\t\t\t, color = 'C0', linestyle='dashed')\n\n\t\t# Theta 1 lower simulation\n\t\tax[0, 0].plot(self.data['x_m'][training_index, 0], label = \"lower training data\"\n\t\t\t\t\t, color = 'C0')\n\t\t# Theta 2 lower simulation\n\t\tax[0, 1].plot(self.data['x_m'][training_index, 1], label = \"lower training data\"\n\t\t\t\t\t, color = 'C0')\n\n\t\ttest_index = np.random.randint(self.n_p)\n\t\t# Theta1 upper and lower\n\t\tax[0, 0].plot(self.data['x_m_test'][test_index, 0], label = \"lower test data\"\n\t\t\t\t\t, color = 'C1')\n\t\tax[0, 0].plot(self.data['x_p_test'][test_index, 0], label = \"upper test data\"\n\t\t\t\t\t, color = 'C1', linestyle='dashed')\n\n\t\t# Theta2 upper and lower\n\t\tax[0, 1].plot(self.data['x_m_test'][test_index, 1], label = \"lower test data\"\n\t\t\t\t\t, color = 'C1')\n\t\tax[0, 1].plot(self.data['x_p_test'][test_index, 1], label = \"upper test data\"\n\t\t\t\t\t, color = 'C1', linestyle='dashed')\n\n\n\t\tax[0, 0].legend(frameon = False)\n\t\tax[0, 1].legend(frameon = False)\n\t\tax[0, 0].set_xticks([])\n\t\tax[0, 1].set_xticks([])\n\t\tax[0, 0].set_ylabel(\"Data amplitude\")\n\t\tax[0, 1].set_ylabel(\"Data amplitude\")\n\t\tax[0, 0].set_title(\"Theta 1 (the mean)\")\n\t\tax[0, 1].set_title(\"Theta 2 (the std)\")\n\n\t\tfor i in range(2):\n\t\t\tfor j in range(2):\n\t\t\t\tax[i, j].set_xlim(0,9)\n\t\tfig.suptitle('Showing only first 10 datapoints out of %i'%self.data['x_m'].shape[1])\n\n\t\t# Theta 1\n\t\tax[1, 0].axhline(xmin = 0., xmax = 1., y = 0., linestyle = 'dashed'\n\t\t\t\t\t, color = 'black')\n\t\tax[1, 0].plot(self.data['x_p'][training_index, 0] - self.data['x_m'][training_index, 0]\n\t\t\t\t\t, color = 'C0',alpha=0.5)\n\t\tax[1, 0].plot(self.data['x_p_test'][test_index, 0] - self.data['x_m_test'][test_index, 0]\n\t\t\t\t\t, color = 'C1',alpha=0.5)\n\t\tax[1, 0].set_xticks([])\n\t\tax[1, 0].set_ylabel(\"Difference between upper/lower data amplitudes\")\n\n\t\t# Theta 2\n\t\tax[1, 1].axhline(xmin = 0., xmax = 1., y = 0., linestyle = 'dashed'\n\t\t\t\t\t, color = 'black')\n\t\tax[1, 1].plot(self.data['x_p'][training_index, 1] - self.data['x_m'][training_index, 1]\n\t\t\t\t\t, color = 'C0',alpha=0.5)\n\t\tax[1, 1].plot(self.data['x_p_test'][test_index, 1] - self.data['x_m_test'][test_index, 1]\n\t\t\t\t\t, color = 'C1',alpha=0.5)\n\t\tax[1, 1].set_xticks([])\n\t\tax[1, 1].set_ylabel(\"Difference between upper/lower data amplitudes\");\n\n\t\tplt.savefig(f'{self.figuredir}derivatives_visualization_{self.modelversion}.png')\n\t\tif show: plt.show()\n\t\tplt.close()\n\n\tdef create_network(self):\n\t\t\"\"\" \n\t\tCreate the network with the given data and parameters\n\n\t\tINPUTS\n\t\t#______________________________________________________________\n\t\tdata \t\t\t\t\tdict \tdict containing training and test data\n\t\t\n\t\tRETURNS\n\t\t#_____________________________________________________________\n\t\tn \t\t\t\t\t\tclass \tIMNN class as defined in IMNN.py\n\n\t\t\"\"\"\n\t\tn = IMNN.IMNN(parameters=self.parameters)\n\t\ttf.reset_default_graph()\n\t\tn.setup(η = eta)\n\t\t\n\t\treturn n\n\n\tdef train_network(self, n, to_continue=False):\n\t\t\"\"\" \n\t\tTrain the created network with the given data and parameters\n\t\tSaves the history and the determinant of the final fisher info\n\n\t\tINPUTS\n\t\t#______________________________________________________________\n\t\tn \t\t\t\t\t\tclass \tIMNN class as defined in IMNN.py\n\t\t\n\t\t\"\"\"\n\n\t\tn.train(num_epochs = self.num_epochs, n_train = self.n_train\n\t\t\t, keep_rate = self.keep_rate, data = self.data, history = True\n\t\t\t, to_continue= to_continue)\n\n\t\t# save the network history to a file\n\t\tutils_mrp.save_history(self, n)\n\n\t\t# save the det(Final Fisher info) in the modelsettings.csv file\n\t\tutils_mrp.save_final_fisher_info(self, n)\n\n\tdef plot_variables(self, n, show=False):\n\t\t\"\"\" \n\t\tPlot variables vs epochs\n\n\t\tINPUTS\n\t\t#______________________________________________________________\n\t\tn \t\t\t\t\t\tclass \tIMNN class as defined in IMNN.py\n\t\t\n\t\t\"\"\"\n\t\tfig, ax = plt.subplots(6, 1, sharex = True, figsize = (8, 14))\n\t\tplt.subplots_adjust(hspace = 0)\n\t\tend = len(n.history[\"det(F)\"])\n\t\tepochs = np.arange(end)\n\t\ta, = ax[0].plot(epochs, n.history[\"det(F)\"], label = 'Training data')\n\t\tb, = ax[0].plot(epochs, n.history[\"det(test F)\"], label = 'Test data')\n\t\t# ax[0].axhline(y=5,ls='--',color='k')\n\t\tax[0].legend(frameon = False)\n\t\tax[0].set_ylabel(r'$|{\\bf F}_{\\alpha\\beta}|$')\n\t\tax[0].set_title('Final Fisher info on test data: %.3f'%n.history[\"det(test F)\"][-1])\n\t\tax[1].plot(epochs, n.history[\"Λ\"])\n\t\tax[1].plot(epochs, n.history[\"test Λ\"])\n\t\tax[1].set_xlabel('Number of epochs')\n\t\tax[1].set_ylabel(r'$\\Lambda$')\n\t\tax[1].set_xlim([0, len(epochs)]);\n\t\tax[2].plot(epochs, n.history[\"det(C)\"])\n\t\tax[2].plot(epochs, n.history[\"det(test C)\"])\n\t\tax[2].set_xlabel('Number of epochs')\n\t\tax[2].set_ylabel(r'$|{\\bf C}|$')\n\t\tax[2].set_xlim([0, len(epochs)]);\n\t\t\n\t\t\n\t\t# Derivative of first summary wrt to theta1\t\t\t\t theta1 is 3rd dimension index 0\n\t\tax[3].plot(epochs, np.array(n.history[\"dμdθ\"])[:,0,0]\n\t\t\t, color = 'C0', label=r'$\\theta_1$',alpha=0.5)\n\t\t# Test Derivative of first summary wrt to theta1\t\t\t\t theta1 is 3rd dimension index 0\n\t\tax[3].plot(epochs, np.array(n.history[\"test dμdθ\"])[:,0,0]\n\t\t\t, color = 'C1', label=r'$\\theta_1$',alpha=0.5)\n\t\tax[3].set_ylabel(r'$\\partial\\mu/\\partial\\theta_1$')\n\t\tax[3].set_xlabel('Number of epochs')\n\t\tax[3].set_xlim([0, len(epochs)])\n\t\t# ax[3].legend(frameon=False)\n\n\t\t# Derivative of first summary wrt to theta2\t\t\t\t theta2 is 3rd dimension index 1\n\t\tax[4].plot(epochs, np.array(n.history[\"dμdθ\"])[:,0,1]\n\t\t\t, color = 'C0', ls='dashed', label=r'$\\theta_2$',alpha=0.5)\n\t\t# Test Derivative of first summary wrt to theta2\t\t\t\t theta2 is 3rd dimension index 1\n\t\tax[4].plot(epochs, np.array(n.history[\"test dμdθ\"])[:,0,1]\n\t\t\t, color = 'C1', ls='dashed', label=r'$\\theta_2$',alpha=0.5)\n\t\tax[4].set_ylabel(r'$\\partial\\mu/\\partial\\theta_2$')\n\t\tax[4].set_xlabel('Number of epochs')\n\t\tax[4].set_xlim([0, len(epochs)])\n\t\t# ax[4].legend(frameon=False)\n\n\t\t# Mean of network output summary 1\n\t\tax[5].plot(epochs, np.array(n.history[\"μ\"])[:,0],alpha=0.5)\n\t\t# Mean of test output network summary 1\n\t\tax[5].plot(epochs, np.array(n.history[\"test μ\"])[:,0],alpha=0.5)\n\t\tax[5].set_ylabel('μ_1')\n\t\tax[5].set_xlabel('Number of epochs')\n\t\tax[5].set_xlim([0, len(epochs)])\n\t\t\n\n\t\tprint ('Maximum Fisher info on train data:',np.max(n.history[\"det(F)\"]))\n\t\tprint ('Final Fisher info on train data:',(n.history[\"det(F)\"][-1]))\n\t\t\n\t\tprint ('Maximum Fisher info on test data:',np.max(n.history[\"det(test F)\"]))\n\t\tprint ('Final Fisher info on test data:',(n.history[\"det(test F)\"][-1]))\n\n\t\tif np.max(n.history[\"det(test F)\"]) == n.history[\"det(test F)\"][-1]:\n\t\t\tprint ('Promising network found, possibly more epochs needed')\n\n\t\tplt.savefig(f'{self.figuredir}variables_vs_epochs_{self.modelversion}.png')\n\t\tif show: plt.show()\n\t\tplt.close()\n\n\tdef plot_train_output(self, n, show=False, amount=10):\n\t\t\"\"\" \n\t\tPlot network output on training set vs epochs, and show the mean as well\n\n\t\tINPUTS\n\t\t#______________________________________________________________\n\t\tn\t\t\t\t\t class IMNN class as defined in IMNN.py\n\t\tamount\t\t\t\t int\t how many outputs to plot\n\t\t\n\t\t\"\"\"\n\n\t\tfig, axes = plt.subplots(3, 1, sharex = True, figsize = (8, 6))\n\t\tax = axes[0]\n\n\t\t# track 'amount' random outputs of the 1000 input simulations\n\t\trandom_indices = np.random.randint(0,self.n_s, amount)\n\t\toutputs = np.asarray(n.history['train output'])[:,random_indices,0] # of first summary\n\t\tend = len(n.history['train output'])\n\t\tepochs = np.arange(end)\n\n\t\t# plot 'amount' random outputs vs epochs\n\t\tfor i in range(amount):\n\t\t\tax.plot(epochs,outputs[:,i],alpha=0.5,ls='dashed')\n\n\t\t# plot the network mean (of first summary) of all the input simulations\n\t\tax.plot(epochs, np.array(n.history[\"μ\"])[:,0],ls='solid',label='μ')\n\t\tax.set_ylabel('Network output')\n\t\tax.set_title(f'Output of {amount} random input simulations')\n\t\tax.legend()\n\n\t\t# plot the network mean of all the input simulations, in a separate plot\n\t\tax = axes[1]\n\t\tax.plot(epochs, np.array(n.history[\"μ\"])[:,0],ls='solid',label='μ')\n\t\tax.set_title(f'Network mean')\n\t\tax.set_ylabel('Network output')\n\n\t\t# plot the numpy mean of this subset\n\t\tax = axes[2]\n\t\tax.set_title('numpy mean/std of the random subset of simulations')\n\t\tax.errorbar(epochs, np.mean(outputs,axis=1), yerr=np.std(outputs,axis=1),label=r'$1\\sigma$',zorder=1)\n\t\tax.plot(epochs, np.mean(outputs,axis=1),label='mean',zorder=2)\n\t\tax.set_ylabel('Value')\n\t\tax.legend()\n\t\t\n\t\taxes[-1].set_xlabel('Epoch')\n\t\tplt.tight_layout()\n\t\tplt.savefig(f'{self.figuredir}output_vs_epochs_{self.modelversion}.png')\n\t\tif show: plt.show()\n\t\tplt.close()\n\n\tdef ABC(self, n, real_data, prior, draws, show=False, epsilon=None, oneD='both'):\n\t\t\"\"\" \n\t\tPerform ABC\n\t\tOnly a uniform prior is implemented at the moment.\n\n\t\tINPUTS\n\t\t#______________________________________________________________\n\t\tn \t\t\t\t\t\tclass \tIMNN class as defined in IMNN.py\n\t\treal_data \t\t\t\tarray \tarray containing true data\n\t\tprior \t\t\t\t\tlist \tlower and upper bounds for uniform priors\n\t\tdraws \t\t\t\t\tint \tamount of draws from prior\n\t\tshow \t\t\t\t\tbool\twhether or not plt.show() is called\n\t\toneD \t\t\t\t\tbool \twhether to plot one dimensional posteriors\n\t\t\t\t\t\t\t\t\t\tor two dimensional with the corner module\n\n\t\tRETURNS\n\t\t#_____________________________________________________________\n\t\ttheta\t\t\t\t\tlist \tsampled parameter values\t\t\t\n\t\taccept_indices \t\t\tlist \tindices of theta that satisfy (ro < epsilon)\n\t\n\t\t\"\"\"\n\n\t\t# If the data is not preloaded as a tensorflow constant then the data can be\n\t\t# passed to the function as data = data\n\n\t\t# sampled parameter values, summary of real data, summaries of generated data\n\t\t# distances of generated data to real data, Fisher info of real data\n\t\ttheta, summary, s, ro, F = n.ABC(real_data = real_data, prior = prior\n\t\t\t, draws = draws, generate_simulation = self.generate_data\n\t\t\t, at_once = True, data = self.data)\n\t\t#at_once = False will create only one simulation at a time\n\n\t\t# Draws are accepted if the distance between the simulation summary and the \n\t\t# simulation of real data are close (i.e., smaller than some value epsilon)\n\t\tif epsilon is None: epsilon = np.linalg.norm(summary)/5. # chosen quite arbitrarily\n\t\taccept_indices = np.argwhere(ro < epsilon)[:, 0]\n\t\treject_indices = np.argwhere(ro >= epsilon)[:, 0]\n\n\t\ttruths = [np.mean(real_data), np.std(real_data)**2]\n\n\n\t\t# plot output samples and histogram of the accepted samples in 1D\n\t\tdef plot_samples_oneD():\n\t\t\tfig, ax = plt.subplots(2, 2, sharex = 'col', figsize = (10, 10))\n\t\t\tplt.subplots_adjust(hspace = 0)\n\t\t\ttheta1 = theta[:,0]\n\t\t\ttheta2 = theta[:,1]\n\n\t\t\tax[0, 0].set_title('Epsilon is chosen to be %.2f'%epsilon)\n\t\t\tax[0, 0].scatter(theta1[reject_indices], s[reject_indices, 0], s = 1, alpha = 0.1)\n\t\t\t# plot 1 point again for the label\n\t\t\tax[0, 0].scatter(theta1[reject_indices][0], s[reject_indices, 0][0],c='C0' , s = 1, alpha = 1, label='Rejected')\n\n\t\t\tax[0, 0].scatter(theta1[accept_indices] , s[accept_indices, 0], s = 1,label='Accepted')\n\t\t\tax[0, 0].plot(prior[0], [summary[0], summary[0]], color = 'black', linestyle = 'dashed', label='Real data')\n\t\t\tax[0, 0].set_ylabel('Network output', labelpad = 0)\n\t\t\tax[0, 0].set_xlim(prior[0])\n\t\t\tax[0, 0].legend(frameon=False)\n\n\t\t\tax[1, 0].hist(theta1[accept_indices], bins=np.linspace(*prior[0], 100)\n\t\t\t\t, histtype = u'step', density = True, linewidth = 1.5, color = '#9467bd');\n\t\t\tax[1, 0].axvline(truths[0],0,1,linestyle='dashed',c='blue')\n\t\t\tax[1, 0].set_xlabel('$\\\\theta_1$ (mean)')\n\t\t\tax[1, 0].set_ylabel('$\\\\mathcal{P}(\\\\theta|{\\\\bf d})$')\n\t\t\tax[1, 0].set_yticks([])\n\n\t\t\tax[0, 1].scatter(theta2[reject_indices], s[reject_indices, 0], s = 1, alpha = 0.1)\n\t\t\tax[0, 1].scatter(theta2[accept_indices] , s[accept_indices, 0], s = 1)\n\t\t\tax[0, 1].plot(prior[1], [summary[0], summary[0]], color = 'black', linestyle = 'dashed')\n\t\t\tax[0, 1].set_ylabel('Network output', labelpad = 0)\n\t\t\tax[0, 1].set_xlim(prior[1])\n\t\t\tax[1, 1].hist(theta2[accept_indices], np.linspace(*prior[1], 100)\n\t\t\t\t, histtype = u'step', density = True, linewidth = 1.5, color = '#9467bd');\n\t\t\tax[1, 1].axvline(truths[1],0,1,linestyle='dashed',c='blue')\n\t\t\tax[1, 1].set_xlabel('$\\\\theta_2$ (variance)')\n\t\t\tax[1, 1].set_ylabel('$\\\\mathcal{P}(\\\\theta|{\\\\bf d})$')\n\t\t\tax[1, 1].set_yticks([])\n\n\t\t\tfig.suptitle(\"Only showing 1st network output summary out of %i \\n Full network output on real data: %s\"%(s.shape[1],str(summary)))\n\n\t\t\tplt.savefig(f'{self.figuredir}ABC_{self.modelversion}_1D.png')\n\t\t\tif show: plt.show()\n\t\t\tplt.close()\n\n\t\t# plot approximate posterior of the accepted samples in 2D\n\t\tdef plot_samples_twoD():\n\t\t\thist_kwargs = {} # add kwargs to give to matplotlib hist funct\n\t\t\tfig, ax = plt.subplots(2, 2, figsize = (10, 10))\n\t\t\tfig = corner.corner(theta[accept_indices], fig=fig, truths = truths\n\t\t\t\t, labels=['$\\\\theta_1$ (mean)','$\\\\theta_2$ (variance)']\n\t\t\t\t, plot_contours=True, range=prior, hist_kwargs=hist_kwargs)\n\t\t\tfig.suptitle('Approximate posterior after ABC for %i draws'%draws)\n\t\t\tplt.savefig(f'{self.figuredir}ABC_{self.modelversion}_2D.png')\n\t\t\tif show: plt.show()\n\t\t\tplt.close()\n\n\t\tif oneD == 'both':\n\t\t\tplot_samples_oneD()\n\t\t\tplot_samples_twoD()\n\t\telif type(oneD) == bool:\n\t\t\tif oneD: \n\t\t\t\tplot_samples()\n\t\t\telse: \n\t\t\t\tplot_samples_twoD()\n\t\telse: \n\t\t\traise ValueError('Allowed values for oneD are \"both\", True or False')\n\n\t\t# There can be a lot of theta draws which are unconstrained by the network\n\t\t# because no similar structures were seen in the data, which is indicative of\n\t\t# using too small of a small training set\n\n\t\treturn theta, accept_indices\n\n\tdef PMC_ABC(self, n, real_data, prior, draws, num_keep, criterion = 0.1, show=False, oneD='both'):\n\t\t\"\"\" \n\t\tPerform PMC ABC, which is a way of reducing the number of draws\n\t\tThe inputs work in a very similar way to the ABC function above. If we \n\t\twant 1000 samples from the approximate distribution at the end of the\n\t\tPMC we need to set num_keep = 1000. The initial random draw is initialised\n\t\twith num_draws, the larger this is the better proposal distr will be on\n\t\tthe 1st iteration.\n\n\n\t\tOnly a uniform prior is implemented at the moment.\n\n\t\tINPUTS\n\t\t#______________________________________________________________\n\t\tn \t\t\t\t\t\tclass \tIMNN class as defined in IMNN.py\n\t\treal_data \t\t\t\tarray \tarray containing true data\n\t\tprior \t\t\t\t\tlist \tlower and upper bounds for uniform priors\n\t\tdraws \t\t\t\t\tint \tnumber of initial draws from the prior\n\t\tnum_keep\t\t\t\tint \tnumber of samples in the approximate posterior\n\t\tcriterion\t\t\t\tfloat\tratio of number of draws wanted over number of draws needed\n\t\tshow \t\t\t\t\tbool\twhether or not plt.show() is called\n\t\toneD \t\t\t\t\tbool \twhether to plot one dimensional posteriors\n\t\t\t\t\t\t\t\t\t\tor two dimensional with the corner module\t\t\n\n\t\tRETURNS\n\t\t#_____________________________________________________________\n\t\ttheta\t\t\t\t\tlist \tsampled parameter values in the approximate posterior\t\t\t\n\t\tall_epsilon\t\t\t\tlist \tprogression of epsilon during PMC\t\t\n\t\n\t\t\"\"\"\n\n\t\t# W = weighting of samples, total_draws = total num draws so far\n\t\ttheta_, summary_, ro_, s_, W, total_draws, F, all_epsilon = n.PMC(real_data = real_data\n\t\t\t, prior = prior, num_draws = draws, num_keep = num_keep\n\t\t\t, generate_simulation = self.generate_data, criterion = criterion\n\t\t\t, at_once = True, samples = None, data = self.data)\n\n\t\t# plot output samples and histogram of approximate posterior\n\t\tdef plot_samples_oneD():\n\n\t\t\ttheta1 = theta_[:,0]\n\t\t\ttheta2 = theta_[:,1]\n\t\t\t\n\t\t\tfig, ax = plt.subplots(2, 2, sharex = 'col', figsize = (10, 10))\n\t\t\tplt.subplots_adjust(hspace = 0)\n\t\t\tax[0,0].scatter(theta1 , s_[:,0], s = 1)\n\t\t\tax[0,0].plot(prior[0], [summary_[0], summary_[0]], color = 'black', linestyle = 'dashed')\n\t\t\tax[0,0].set_ylabel('Network output', labelpad = 0)\n\t\t\tax[0,0].set_ylim([np.min(s_[:,0]), np.max(s_[:,0])])\n\t\t\tax[0,0].set_xlim(prior[0])\n\t\t\tax[1,0].hist(theta1, bins= np.linspace(*prior[0], 100), histtype = u'step', density = True, linewidth = 1.5, color = '#9467bd');\n\t\t\tax[1,0].set_xlabel('$\\\\theta_1$ (mean)')\n\t\t\tax[1,0].set_ylabel('$\\\\mathcal{P}(\\\\theta|{\\\\bf d})$')\n\t\t\tax[1,0].set_yticks([])\n\n\t\t\tax[0,1].scatter(theta2 , s_[:,0], s = 1)\n\t\t\tax[0,1].plot(prior[1], [summary_[0], summary_[0]], color = 'black', linestyle = 'dashed')\n\t\t\tax[0,1].set_ylabel('Network output', labelpad = 0)\n\t\t\tax[0,1].set_xlim(prior[1])\n\t\t\tax[0,1].set_ylim([np.min(s_[:,0]), np.max(s_[:,0])])\n\t\t\tax[1,1].hist(theta2, bins = np.linspace(*prior[1], 100), histtype = u'step', density = True, linewidth = 1.5, color = '#9467bd');\n\t\t\tax[1,1].set_xlabel('$\\\\theta_2$ (variance)')\n\t\t\tax[1,1].set_ylabel('$\\\\mathcal{P}(\\\\theta|{\\\\bf d})$')\n\t\t\tax[1,1].set_yticks([])\n\n\t\t\tfig.suptitle(\"Only showing 1st network output summary out of %i \\n Full network output on real data: %s\"%(s_.shape[1],str(summary_)))\n\n\t\t\tplt.savefig(f'{self.figuredir}PMC_ABC_{self.modelversion}_1D.png')\n\t\t\tif show: plt.show()\n\t\t\tplt.close()\n\n\t\t# plot output samples and histogram of the accepted samples\n\t\tdef plot_samples_twoD():\n\t\t\thist_kwargs = {} # add kwargs to give to matplotlib hist funct\n\t\t\tfig, ax = plt.subplots(2, 2, figsize = (10, 10))\n\t\t\tfig = corner.corner(theta_, fig=fig, truths = theta_fid\n\t\t\t\t, labels=['$\\\\theta_1$ (mean)','$\\\\theta_2$ (variance)']\n\t\t\t\t, plot_contours=True, range=prior, hist_kwargs=hist_kwargs)\n\t\t\tfig.suptitle(\"Approximate posterior after PMC ABC, num_keep = %i\"%num_keep)\n\t\t\t\n\t\t\tplt.savefig(f'{self.figuredir}PMC_ABC_{self.modelversion}_2D.png')\n\t\t\tif show: plt.show()\n\t\t\tplt.close()\n\n\t\t# Plot epsilon vs iterations\n\t\tdef plot_epsilon():\n\t\t\tfig, ax = plt.subplots()\n\t\t\tax.plot(all_epsilon,color='k',label='$\\epsilon$ values')\n\t\t\tplt.xlabel('Iteration')\n\t\t\tplt.ylabel('$\\epsilon$')\n\t\t\tplt.legend()\n\t\t\t\n\t\t\tplt.savefig(f'{self.figuredir}PMC_ABC_{self.modelversion}_epsilon.png')\n\t\t\tif show: plt.show()\n\t\t\tplt.close()\n\n\t\tif oneD == 'both':\n\t\t\tplot_samples()\n\t\t\tplot_samples_twoD()\n\t\telif type(oneD) == bool:\n\t\t\tif oneD:\n\t\t\t\tplot_samples()\n\t\t\telse:\n\t\t\t\tplot_samples_twoD()\n\t\telse: \n\t\t\traise ValueError('Allowed values for oneD are \"both\", True or False')\n\n\t\tplot_epsilon()\n\n\t\treturn theta_, all_epsilon\n\ndef generate_data(θ, train = None):\n\t'''Train is whether the upper and lower derivatives are calculated '''\n\tif train is not None:\n\t\tholder = np.zeros([θ.shape[0]] + [θ.shape[1]] + input_shape)\n\t\tfor i in range(θ.shape[1]):\n\t\t\tparams = np.copy(θ)\n\t\t\tparams[:, i] += train[i]\n\t\t\tholder[:, i, :] = np.moveaxis(np.random.normal(params[:, 0], np.sqrt(params[:, 1]), input_shape + [θ.shape[0]]), -1, 0)\n\t\treturn holder\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \n\telse:\n\t\treturn np.moveaxis(np.random.normal(θ[:, 0], np.sqrt(θ[:, 1]), input_shape + [θ.shape[0]]), -1, 0)\n\n\n# ALL PARAMETERS\n#_______________________________________________________\ninput_shape = [100]\ntheta_fid = np.array([0.,1.]) # mean and variance\ndelta_theta = np.array([0.10,0.10]) # perturbation values\nn_s = 1000 # number of simulations\nn_train = 1 # splits, for if it doesnt fit into memory\n# use less simulations for numerical derivative\nderivative_fraction = 0.2\neta = 1e-5\nnum_epochs = int(100e3)\nkeep_rate = 0.6\nverbose = 0\nhidden_layers = [256,256,256]\ninitial_version = 1034\n# Version < 1006 erroneously uses np.sqrt(cov) instead of cov in IMNN code\n# Version 1034 uses determinant of cov matrix as added to loss\n\nversion = initial_version\n\nparameters = {\n\t'verbose': False,\n\t'number of summaries': 2,\n\t'calculate MLE': True,\n\t'prebuild': True, # allow IMNN to build network\n\t'save file': \"Models/data/model\"+str(version),\n\t'wv': 0., # the variance with which to initialise the weights\n\t'bb': 0.1, # the constant value with which to initialise the biases\n\t'activation': tf.nn.leaky_relu,\n\t'α': 0.01, # negative gradient parameter \n\t'hidden layers': hidden_layers\n}\n#______________________________________________________\n\n# Network holder\nnholder1 = nholder(input_shape, generate_data, theta_fid, delta_theta, n_s,\n\t\tn_train, derivative_fraction, eta, parameters, num_epochs, keep_rate,\n\t\tverbose, version)\n\n# # Rescale the data \n# ###### DO THIS BEFORE CALLING CREATE_NETWORK\n# nholder1.rescale_data()\n\n# # IMNN network\nn = nholder1.create_network()\n\n# Plot data\nnholder1.plot_data_hist(show=False)\n\n# Plot upper/lower\nnholder1.plot_derivatives(show=False)\n\n# # Train network\nnholder1.train_network(n)\n# # Plot the output\nnholder1.plot_variables(n,show=True)\n# Plot output of 10 random inputs\n# nholder1.plot_train_output(n, show=True, amount=100)\n\n# # Perform ABC\nreal_data = generate_data(np.array([theta_fid]), train = None)\nprior = [[-3, 3], [0,3]] # [ [prior1], [prior2], etc.. ]\ndraws = 100000\n\nprint ('Real data mean, var: ', np.mean(real_data), np.std(real_data)**2)\n\n\ntheta, _ = nholder1.ABC(n, real_data, prior, draws, show=False, epsilon=None,oneD='both')\n\nnp.holdup()\n\nnum_keep = int(1e3)\ninital_draws = int(1e4)\nnholder1.PMC_ABC(n, real_data, prior, inital_draws, num_keep, criterion = 0.1, show=True,oneD=False)\n\n\"\"\"\nnholder1.num_epochs = int(2e3)\nnholder1.train_network(n, to_continue=True)\nnholder1.plot_variables(n,show=True)\n\"\"\"","sub_path":"1Dgaussian_mean_variance/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":29667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"487239784","text":"\"\"\"\n给定一个二叉树,返回它的 前序 遍历。\n\n示例:\n输入: [1,null,2,3]\n 1\n \\\n 2\n /\n 3\n输出: [1,2,3]\n\"\"\"\n\n\n# 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\n\nclass Solution:\n def preorderTraversal(self, root):\n # 递归\n # if root is None:\n # return []\n # return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)\n\n # 迭代\n if root is None:\n return []\n stack = [root]\n res = []\n while stack:\n cur_node = stack.pop()\n res.append(cur_node.val)\n if cur_node.right is not None:\n stack.append(cur_node.right)\n if cur_node.left is not None:\n stack.append(cur_node.left)\n return res\n","sub_path":"LeedCode/栈、队列与优先队列/144. 二叉树的前序遍历.py","file_name":"144. 二叉树的前序遍历.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"646327819","text":"#\n#\n#\n\nfrom __future__ import absolute_import, division, print_function, \\\n unicode_literals\n\n# from mock import Mock, call\nfrom os.path import dirname, join\nfrom requests import HTTPError\nfrom requests_mock import ANY, mock as requests_mock\nfrom six import text_type\nfrom unittest import TestCase\n\nfrom octodns.record import Record\nfrom octodns.provider.edgedns import AkamaiProvider\nfrom octodns.provider.fastdns import AkamaiProvider as LegacyAkamaiProvider\nfrom octodns.provider.yaml import YamlProvider\nfrom octodns.zone import Zone\n\n\nclass TestEdgeDnsProvider(TestCase):\n expected = Zone('unit.tests.', [])\n source = YamlProvider('test', join(dirname(__file__), 'config'))\n source.populate(expected)\n\n # Our test suite differs a bit, add our NS and remove the simple one\n expected.add_record(Record.new(expected, 'under', {\n 'ttl': 3600,\n 'type': 'NS',\n 'values': [\n 'ns1.unit.tests.',\n 'ns2.unit.tests.',\n ]\n }))\n for record in list(expected.records):\n if record.name == 'sub' and record._type == 'NS':\n expected._remove_record(record)\n break\n\n def test_populate(self):\n provider = AkamaiProvider(\"test\", \"secret\", \"akam.com\", \"atok\", \"ctok\")\n\n # Bad Auth\n with requests_mock() as mock:\n mock.get(ANY, status_code=401, text='{\"message\": \"Unauthorized\"}')\n\n with self.assertRaises(Exception) as ctx:\n zone = Zone('unit.tests.', [])\n provider.populate(zone)\n\n self.assertEquals(401, ctx.exception.response.status_code)\n\n # general error\n with requests_mock() as mock:\n mock.get(ANY, status_code=502, text='Things caught fire')\n\n with self.assertRaises(HTTPError) as ctx:\n zone = Zone('unit.tests.', [])\n provider.populate(zone)\n self.assertEquals(502, ctx.exception.response.status_code)\n\n # Non-existant zone doesn't populate anything\n with requests_mock() as mock:\n mock.get(ANY, status_code=404,\n text='{\"message\": \"Domain `foo.bar` not found\"}')\n\n zone = Zone('unit.tests.', [])\n provider.populate(zone)\n self.assertEquals(set(), zone.records)\n\n # No diffs == no changes\n with requests_mock() as mock:\n\n with open('tests/fixtures/edgedns-records.json') as fh:\n mock.get(ANY, text=fh.read())\n\n zone = Zone('unit.tests.', [])\n provider.populate(zone)\n self.assertEquals(18, len(zone.records))\n changes = self.expected.changes(zone, provider)\n self.assertEquals(0, len(changes))\n\n # 2nd populate makes no network calls/all from cache\n again = Zone('unit.tests.', [])\n provider.populate(again)\n self.assertEquals(18, len(again.records))\n\n # bust the cache\n del provider._zone_records[zone.name]\n\n def test_apply(self):\n provider = AkamaiProvider(\"test\", \"s\", \"akam.com\", \"atok\", \"ctok\",\n \"cid\", \"gid\")\n\n # tests create update delete through previous state config json\n with requests_mock() as mock:\n\n with open('tests/fixtures/edgedns-records-prev.json') as fh:\n mock.get(ANY, text=fh.read())\n\n plan = provider.plan(self.expected)\n mock.post(ANY, status_code=201)\n mock.put(ANY, status_code=200)\n mock.delete(ANY, status_code=204)\n\n changes = provider.apply(plan)\n self.assertEquals(31, changes)\n\n # Test against a zone that doesn't exist yet\n with requests_mock() as mock:\n with open('tests/fixtures/edgedns-records-prev-other.json') as fh:\n mock.get(ANY, status_code=404)\n\n plan = provider.plan(self.expected)\n mock.post(ANY, status_code=201)\n mock.put(ANY, status_code=200)\n mock.delete(ANY, status_code=204)\n\n changes = provider.apply(plan)\n self.assertEquals(16, changes)\n\n # Test against a zone that doesn't exist yet, but gid not provided\n with requests_mock() as mock:\n with open('tests/fixtures/edgedns-records-prev-other.json') as fh:\n mock.get(ANY, status_code=404)\n provider = AkamaiProvider(\"test\", \"s\", \"akam.com\", \"atok\", \"ctok\",\n \"cid\")\n plan = provider.plan(self.expected)\n mock.post(ANY, status_code=201)\n mock.put(ANY, status_code=200)\n mock.delete(ANY, status_code=204)\n\n changes = provider.apply(plan)\n self.assertEquals(16, changes)\n\n # Test against a zone that doesn't exist, but cid not provided\n\n with requests_mock() as mock:\n mock.get(ANY, status_code=404)\n\n provider = AkamaiProvider(\"test\", \"s\", \"akam.com\", \"atok\", \"ctok\")\n plan = provider.plan(self.expected)\n mock.post(ANY, status_code=201)\n mock.put(ANY, status_code=200)\n mock.delete(ANY, status_code=204)\n\n try:\n changes = provider.apply(plan)\n except NameError as e:\n expected = \"contractId not specified to create zone\"\n self.assertEquals(text_type(e), expected)\n\n\nclass TestDeprecatedAkamaiProvider(TestCase):\n\n def test_equivilent(self):\n self.assertEquals(LegacyAkamaiProvider, AkamaiProvider)\n","sub_path":"tests/test_octodns_provider_edgedns.py","file_name":"test_octodns_provider_edgedns.py","file_ext":"py","file_size_in_byte":5537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"403786488","text":"import os\nimport cv2\nimport ast\nimport numpy as np\nfrom flax_core.utility import morph, sl\nfrom scipy.ndimage import measurements\nfrom numpy import minimum, amax\nfrom flax_core.utility.convert import convert_to_binary, convert_binary_to_normal_im\nfrom flax_core.base.base_image_processor import BaseImageProcessor\nfrom flax_core.denoise.denoise_border import DenoiseBorder\nfrom flax_core.denoise.denoise_area import DenoiseArea\nfrom flax_core.utility.drawing import draw_rects\n\n\nclass LinecutCheckbox(BaseImageProcessor):\n DASHED_TYPE = 1\n BOXED_TYPE = 2\n img = None\n blank_img = None\n selection_boxes = None\n out = dict()\n config = None\n default_config = dict()\n\n def __init__(self, img=None, blank_bin_img=None, selection_boxes=None, config=None):\n \"\"\"\n Initialize checkbox handling object\n :param img: input\n :param blank_bin_img: blank binary image, white background, black strokes\n :param selection_boxes: position of selection boxes\n :param config: specific config for this step\n \"\"\"\n # print(\"LinecutCheckbox - __init__()\")\n if img is not None:\n self.imread(img)\n if blank_bin_img is not None:\n self.set_blank_img(blank_bin_img)\n if selection_boxes is not None:\n self.set_selection_boxes(selection_boxes)\n self.config = self.default_config\n if config is not None:\n if isinstance(config, str):\n self.config = ast.literal_eval(config)\n else:\n self.config = config\n\n def imread(self, img):\n # print(\"LinecutCheckbox - imread()\")\n if isinstance(img, np.ndarray):\n self.img = img\n elif isinstance(img, str):\n if len(img) > 0:\n try:\n img = cv2.imread(img)\n self.img = img\n except Exception as e:\n print(e)\n else:\n print(\"Error - Empty image path!\")\n return\n if len(self.img.shape) > 2:\n self.img = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)\n\n def process(self):\n # print(\"LinecutCheckbox - process()\")\n if self.blank_img is not None and self.img is not None:\n selected_region, shift = self.__match_image_with_blank(self.img, self.blank_img)\n res_where, shifted_boxes = self.__read_check_mark_position(selected_region, self.selection_boxes, shift)\n selected_ids = [j[0] for j in res_where]\n boxes_filter = [shifted_boxes[index] for index in selected_ids]\n labels = [LinecutCheckbox.get_checkbox_choice(j) for j in range(len(self.selection_boxes))]\n debug_img = cv2.resize(self.img, (self.blank_img.shape[1], self.blank_img.shape[0]))\n debug_img = cv2.cvtColor(debug_img, cv2.COLOR_GRAY2BGR)\n debug_img = draw_rects(debug_img, self.selection_boxes, font_size=1, label=labels, show_rect=False,\n center_label=True)\n debug_img = draw_rects(debug_img, boxes_filter, font_size=1, thickness=4)\n debug_img = cv2.resize(debug_img, (self.img.shape[1], self.img.shape[0]))\n self.out['log'] = debug_img\n self.out['result'] = selected_ids\n return self.out\n\n def save(self, output_dir, prefix):\n # print(\"LinecutCheckbox - save()\")\n is_debug = True\n if self.config is not None:\n is_debug = self.config['is_debug']\n if is_debug:\n cv2.imwrite(os.path.join(output_dir, prefix + \".png\"), self.out['log'])\n if self.out is not None:\n np.savetxt(os.path.join(output_dir, prefix + \".txt\"),\n X=[LinecutCheckbox.get_checkbox_choice(j) for j in self.out['result']],\n delimiter=',', fmt=\"%s\")\n\n @staticmethod\n def get_boxed_checkbox_positions(arr_img):\n \"\"\"\n Get checkbox positions using morphology, contour and area constrains\n :return: positions of checkbox in input images and log image\n \"\"\"\n if len(arr_img.shape) > 2:\n arr_img = cv2.cvtColor(arr_img, cv2.COLOR_BGR2GRAY)\n # arr_img[(arr_img > 150)] = 255\n # arr_img[(arr_img <= 120)] = 0\n try:\n # remove border/table line noise to make sure following algorithm works correctly\n denoise_border_obj = DenoiseBorder(arr_img)\n arr_img = denoise_border_obj.process()\n\n # remove small noise\n denoise_area_obj = DenoiseArea(arr_img)\n gray_img = denoise_area_obj.process()\n binary_img = 1 - convert_to_binary(gray_img)\n # find size of max hor and ver line\n labels, obj_count = morph.label(binary_img)\n objs = morph.find_objects(labels)\n max_hei = 0\n max_wid = 0\n for i, slice in enumerate(objs):\n if sl.height(slice) > max_hei:\n max_hei = sl.height(slice)\n if 40 > sl.width(slice) > max_wid:\n max_wid = sl.width(slice)\n\n # vertical line\n vertical_inv = 255 - convert_binary_to_normal_im(binary_img)\n vertical_inv = morph.perform_morphology(vertical_inv, [2, 2], 'dilate')\n vertical_inv = morph.perform_morphology(vertical_inv, [1, int(max_hei - 5)], 'erode')\n vertical_inv = cv2.medianBlur(vertical_inv, 3)\n vertical_inv = morph.perform_morphology(vertical_inv, [1, max_hei], 'dilate')\n vertical_inv = cv2.medianBlur(vertical_inv, 3)\n # horizontal line\n hor_inv = 255 - convert_binary_to_normal_im(binary_img)\n hor_inv = morph.perform_morphology(hor_inv, [2, 2], 'dilate')\n hor_inv = morph.perform_morphology(hor_inv, [int(0.8 * max_wid), 1], 'erode')\n hor_inv = cv2.medianBlur(hor_inv, 3)\n hor_inv = morph.perform_morphology(hor_inv, [max_wid, 1], 'dilate')\n hor_inv = cv2.medianBlur(hor_inv, 3)\n # end horizontal\n\n # combine hor and ver lines, find contours\n combined_line = vertical_inv | hor_inv\n img_temp = arr_img.copy()\n img_temp[:] = 0\n img2, simple_contours, hierarchy = cv2.findContours(combined_line, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)\n simple_contours = sorted(simple_contours, key=lambda a: cv2.contourArea(a), reverse=True)\n boxes = []\n for index, cnt in enumerate(simple_contours):\n x, y, wid, hei = cv2.boundingRect(cnt)\n # if cv2.isContourConvex(cnt) and cv2.contourArea(cnt) > max_wid * max_hei * 0.7:\n # checkbox tick condition\n if (max_wid + 3) * (max_hei + 3) > wid * hei >= max_wid * max_hei * 0.7 \\\n and wid in range(max_wid - 5, max_wid + 5) and hei in range(max_hei - 5, max_hei + 5):\n boxes.append([int(y), int(x), int(y + hei), int(x + wid)])\n if len(boxes) > 1:\n if len(boxes) > 4:\n boxes = sorted(boxes, key=lambda item: item[0])\n else:\n boxes = sorted(boxes, key=lambda item: (item[1], item[0]))\n\n if len(boxes) > 0:\n trivia_boxes = list()\n replicate_boxes = boxes.copy()\n for i, box in enumerate(boxes):\n for j, box_j in enumerate(replicate_boxes):\n if LinecutCheckbox.is_in_cell(box, box_j) and any(\n box[index] != box_j[index] for index in range(0, 4)):\n trivia_boxes.append(box_j)\n filtered_boxes = boxes.copy()\n for box in trivia_boxes:\n filtered_boxes.remove(box)\n\n for box in filtered_boxes:\n cv2.rectangle(img_temp, (box[1], box[0]), (box[3], box[2]), (255, 0, 0), 2)\n return filtered_boxes, 255 - img_temp\n except Exception as e:\n print(\"Error occured in module linecut checkbox: \", e)\n return [], arr_img\n return [], arr_img\n\n @staticmethod\n def get_dashed_checkbox_positions(blank_im):\n \"\"\"\n Get selection positions of input checkbox images\n :param blank_im: gray scale input image to find selection boxes\n :return: list of selection positions and log image\n \"\"\"\n binary = convert_to_binary(255 - blank_im)\n labels, obj_counts = morph.label(binary)\n h, w = binary.shape\n minsize = 80\n\n # find small dash in img\n sums = measurements.sum(binary, labels, range(obj_counts + 1))\n sums = sums[labels]\n good = minimum(binary, 1 - (sums > 0) * (sums < minsize))\n\n junk_cc = np.bitwise_xor(good, binary)\n # temporary fix: add bottom line\n junk_cc[h - 1:, :] = np.ones((1, w))\n junk_cc = morph.r_dilation(junk_cc, (7, 7))\n junk_cc = morph.r_closing(junk_cc, (9, 9))\n\n # find hole using morphology\n hole = morph.fill_hole(junk_cc)\n hole = hole - junk_cc\n\n # locate holes position\n labels, obj_counts = morph.label(hole)\n objects = morph.find_objects(labels)\n objects = sorted(objects, key=lambda b: sl.center(b))\n area_thres = 0.4 * (amax([sl.area(b) for b in objects]) if len(objects) > 0 else 0)\n boxes = [[b[0].start, b[1].start, b[0].stop, b[1].stop] for b in objects if sl.area(b) > area_thres]\n\n return boxes, convert_binary_to_normal_im(hole)\n\n @staticmethod\n def classify_checkbox(img, min_size=80):\n \"\"\"\n Classify input checkbox image to either dashed type or squared box type\n :param img: gray scale input image to check\n :param min_size: min size to estimate whether an object is dashed object or not\n :return: type of checkbox in input image\n \"\"\"\n boxes, _ = LinecutCheckbox.get_boxed_checkbox_positions(img)\n\n if boxes is None:\n return LinecutCheckbox.DASHED_TYPE\n elif len(boxes) > 0:\n return LinecutCheckbox.BOXED_TYPE\n else:\n return LinecutCheckbox.DASHED_TYPE\n\n def __read_check_mark_position(self, gray_img, boxes, shift):\n # if no boxes in blank template, skip\n if len(boxes) == 0:\n return [], boxes\n\n binary = convert_to_binary(255 - gray_img)\n shift_y, shift_x = shift\n shifted_boxes = [[b[0] + shift_y, b[1] + shift_x, b[2] + shift_y, b[3] + shift_x] for b in boxes]\n h, w = binary.shape\n pad = 5\n expand_boxes = [[max(b[0] - pad, 0), max(b[1] - pad, 0), min(b[2] + pad, h), min(b[3] + pad, w)] for b in\n shifted_boxes]\n counts = np.array([np.sum(binary[b[0]:b[2], b[1]:b[3]]) for b in expand_boxes])\n thres = 20\n result = np.argwhere(counts > thres)\n return result, shifted_boxes\n\n def __match_image_with_blank(self, gray_img, blank_bin, max_shift_ratio=0.2, step=1, expand_thres=5,\n remove_noise=False):\n \"\"\"\n Match input gray image with blank image to find best match position\n :param gray_img: input gray scale image\n :param blank_bin: blank binary image to compute and check match\n :param max_shift_ratio: ratio of width and height to shift\n :param step: step at each shift operation\n :param expand_thres: kernel size to perform dilation so that blank image will cover all checkbox\n :param remove_noise: flag indicating removing noise or not\n :return: binary: area not in blank image (in case of checkbox is the selected ones, in case of mixed line is the\n hand-writing data\n (shift_x, shift_y): shifted range from input image compared to blank image\n \"\"\"\n binary = convert_to_binary(255 - gray_img, thres=0.6)\n h, w = binary.shape\n range_x = int(max_shift_ratio * w)\n range_y = int(max_shift_ratio * h)\n sum_blank = np.sum(blank_bin)\n if sum_blank < 10:\n return gray_img, (0, 0)\n # binary = remove_small_noise(binary)\n thres = 0.2\n max_match = -1\n shift_x, shift_y = 0, 0\n for x in range(-range_x, range_x, step):\n for y in range(-range_y, range_y, step):\n temp_blank = self.__shift_binary(blank_bin, (y, x)) # interpolation.shift(blank_bin, (y, x))\n match = np.sum(temp_blank & binary)\n if 1.0 * match / sum_blank > thres and match > max_match:\n max_match = match\n shift_x, shift_y = x, y\n if max_match != -1:\n # print(shift_x, shift_y)\n temp_blank = self.__shift_binary(blank_bin,\n (shift_y, shift_x)) # interpolation.shift(blank_bin, (shift_y, shift_x))\n temp_blank = morph.r_dilation(temp_blank, (expand_thres, expand_thres))\n binary = binary & (1 - temp_blank) # 0.5 * binary + 0.5 * temp_blank\n\n return convert_binary_to_normal_im(binary), (shift_y, shift_x)\n\n def __shift_binary(self, origin_bin, shift_range):\n \"\"\"\n Shift input image by a shift range in pixel\n :param origin_bin: binary input image\n :param shift_range: tuple, first element is shift range along y-axis, second is shift range along x-axis\n :return: shifted image\n \"\"\"\n binary = origin_bin.copy()\n h, w = binary.shape\n binary = np.roll(binary, shift_range, axis=(0, 1))\n if shift_range[0] > 0:\n y0, y1 = 0, shift_range[0]\n else:\n y0, y1 = h + shift_range[0], h\n\n if shift_range[1] > 0:\n x0, x1 = 0, shift_range[1]\n else:\n x0, x1 = w + shift_range[1], w\n binary[y0:y1, :] = np.zeros((y1 - y0, w))\n binary[:, x0:x1] = np.zeros((h, x1 - x0))\n return binary\n\n @staticmethod\n def get_checkbox_choice(index):\n if index < 26:\n return chr(97 + index)\n else:\n return chr(65 + index - 26)\n\n def set_blank_img(self, blank_img=None):\n if blank_img is not None:\n self.blank_img = blank_img\n\n def set_selection_boxes(self, selection_boxes=None):\n if selection_boxes is not None:\n self.selection_boxes = selection_boxes\n\n @staticmethod\n def overlap_area(a, b):\n \"\"\"\n Calculate overlap area of rect a and rect b\n :param a: co-ordinate of 1st rect\n :param b: co-ordinate of 2nd rect\n :return: return None if a, b don't overlap\n return overlap area otherwise\n \"\"\"\n dx = min(a[2], b[2]) - max(a[0], b[0])\n dy = min(a[3], b[3]) - max(a[1], b[1])\n if (dx >= 0) and (dy >= 0):\n return dx * dy\n\n @staticmethod\n def get_rect_area(rect):\n \"\"\"\n Calculate area of a given rect\n :param rect: co-ordinate of the rect\n :return: Area of given rect\n \"\"\"\n try:\n return (rect[2] - rect[0]) * (rect[3] - rect[1])\n except Exception as e:\n print(e)\n return 0\n\n @staticmethod\n def is_in_cell(cell, rect):\n overlap_part = LinecutCheckbox.overlap_area(cell, rect)\n rect_area = LinecutCheckbox.get_rect_area(rect)\n\n if overlap_part is None:\n return False\n if cell[0] <= rect[0] and rect[2] <= cell[2] and overlap_part > (int)(rect_area * 0.5):\n return True\n if overlap_part > (int)(rect_area * 0.9):\n return True\n else:\n return False\n\n\ndef show_img(img, winname=\"TEST\"):\n from matplotlib import pyplot\n pyplot.figure()\n pyplot.imshow(img)\n pyplot.title(winname)\n pyplot.show()","sub_path":"flax_core/linecut/linecut_checkbox.py","file_name":"linecut_checkbox.py","file_ext":"py","file_size_in_byte":15885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"607177701","text":"from impl.datasets.cora import CORA\nfrom impl.datasets.citeseer import Citeseer\nfrom impl.datasets.dblp import DBLP\nfrom impl.pairs.doc2vec import D2VPairs\nfrom impl.pairs.deepwalk import DWPairs\nfrom impl.model.skipgram import SGNS\nfrom impl.model.jce import JCE\nfrom impl.utils.eval import eval_model, plot_evals\n\nfrom gensim.models import Word2Vec, doc2vec\nimport numpy as np\nimport psutil\nimport os\nimport datetime\nimport pickle\nimport sys\nimport json\nimport copy\n\n\n\n\n\n\nparams = None\ncomplete_dataset = None\ndrop_percentages = []\ntest_cases = [ \"remove_random_edges\"\n , \"remove_iportant_edges_cc\"\n , \"remove_iportant_edges_nd\"\n , \"remove_all_edges_of_random_nodes\"\n , \"remove_all_edges_of_important_nodes\"]\n\nstarting_run_date = datetime.datetime.now().strftime(\"%Y-%m-%d-%H-%M\")\nBASE_CACHE_DIR = \"\"\nTIMESTAMP_CACHE_DIR = \"\"\n\n\n\ndef init(args):\n global params, drop_percentages, BASE_CACHE_DIR, TIMESTAMP_CACHE_DIR, complete_dataset\n\n with open('params.json') as json_file:\n all_params = json.load(json_file)\n\n if 2 > len(args):\n print(\"Please enter the name of the dataset in addition to the list of edges removal percentages.\")\n print(\"Ex: python generate_embeddings cora 5 10 50\")\n return False\n\n if \"cora\" == args[0]:\n params = all_params[\"cora\"]\n complete_dataset = CORA(content_filename='./datasets/cora/cora.content', cites_filename='./datasets/cora/cora.cites')\n elif \"citeseer\" == args[0]:\n params = all_params[\"citeseer\"]\n complete_dataset = Citeseer(content_filename='./datasets/citeseer/citeseer.content', cites_filename='./datasets/citeseer/citeseer.cites')\n elif \"dblp\" == args[0]:\n params = all_params[\"dblp\"]\n complete_dataset = DBLP(content_filename='./datasets/dblp/dblp.content', cites_filename='./datasets/dblp/dblp.cites')\n else:\n print(\"Dataset name should be cora, citeseer or dblp\")\n print(\"Ex: python generate_embeddings cora 5 10 50\")\n return False\n\n params[\"sine\"][\"batch_sizes\"] = [params[\"d2v\"][\"model\"][\"batch_size\"], params[\"dw\"][\"model\"][\"batch_size\"]]\n\n for drop in args[1:]:\n drop_percentages.append(int(drop))\n\n BASE_CACHE_DIR = \"./cache/{}\".format(args[0])\n TIMESTAMP_CACHE_DIR = \"{}/{}\".format(BASE_CACHE_DIR, starting_run_date)\n\n os.system(\"mkdir ./cache 2> /dev/null\")\n os.system(\"mkdir {} 2> /dev/null\".format(BASE_CACHE_DIR))\n os.system(\"mkdir {} 2> /dev/null\".format(TIMESTAMP_CACHE_DIR))\n\n print(\"Parameters are well initialized\")\n return True\n\ndef main():\n\n for drop_percentage in drop_percentages:\n os.system(\"mkdir {}/{} 2> /dev/null\".format(TIMESTAMP_CACHE_DIR, drop_percentage))\n if 0 == drop_percentage:\n # run on Full dataset\n test_to_be_run = [\"full_dataset\"]\n else :\n test_to_be_run = test_cases\n for test in test_to_be_run:\n print(\"Performing test {} with drop_percentage = {}\".format(test, drop_percentage))\n dataset = copy.deepcopy(complete_dataset)\n # do not perform any edge removal when running on full dataset\n if \"full_dataset\" != test:\n print(\"Removing process ...\")\n remove_method = getattr(dataset, test)\n remove_method(drop_percentage)\n\n os.system(\"mkdir {}/{}/{} 2> /dev/null\".format(TIMESTAMP_CACHE_DIR, drop_percentage, test))\n cache_dir = \"{}/{}/{}\".format(TIMESTAMP_CACHE_DIR, drop_percentage, test)\n\n params[\"d2v\"][\"model\"][\"cache_file\"] = cache_dir + \"/d2v\"\n params[\"dw\"][\"model\"][\"cache_file\"] = cache_dir + \"/dw\"\n params[\"sine\"][\"cache_file\"] = cache_dir + \"/sine\"\n\n ################################################################\n # Saving dataset\n ################################################################\n print(\"saving missing dataset in {}/missing_edges_dataset.p\".format(cache_dir))\n pickle.dump(dataset, open(\"{}/missing_edges_dataset.p\".format(cache_dir), \"wb\"))\n\n ################################################################\n # Making pairs\n ################################################################\n d2vpairs = D2VPairs(dataset=dataset, **params[\"d2v\"][\"pairs\"])\n dwpairs = DWPairs(dataset=dataset, **params[\"dw\"][\"pairs\"])\n\n #############################################\n # Doc2Vec\n #############################################\n print(\"Running Doc2Vec ...\")\n d2vmodel = SGNS(d2vpairs, **params[\"d2v\"][\"model\"])\n d2vEmb = d2vmodel.embeddings[str(params[\"d2v\"][\"model\"][\"iterations\"])]\n print(\"Eval D2V: \", eval_model(d2vEmb, dataset=dataset))\n\n #############################################\n # DeepWalk\n #############################################\n print(\"Running DeepWalk ...\")\n dwmodel = SGNS(dwpairs, **params[\"dw\"][\"model\"])\n dwEmb = dwmodel.embeddings[str(params[\"dw\"][\"model\"][\"iterations\"])]\n print(\"Eval DW: \", eval_model(dwEmb, dataset=dataset))\n\n #############################################\n # SINE\n #############################################\n print(\"Running SINE ...\")\n sinemodel = JCE(data=[d2vpairs, dwpairs], disable_grad=False, **params[\"sine\"])\n sineEmb = sinemodel.embeddings[str(params[\"sine\"][\"iterations\"])]\n print(\"Eval JCE (SINE): \", eval_model(sineEmb, dataset=dataset))\n\nif __name__ == '__main__':\n if init(sys.argv[1:]):\n main()\n","sub_path":"generate_embeddings.py","file_name":"generate_embeddings.py","file_ext":"py","file_size_in_byte":5734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"417413267","text":"from doubly_linked_list import DoublyLinkedList\nimport sys\nsys.path.append('./doubly_linked_list.py')\n\n\nclass LRUCache:\n\n def __init__(self, limit=10):\n self.limit = limit\n self.size = 0\n self.storage = {}\n self.order = DoublyLinkedList()\n\n def get(self, key):\n # If key is in storage\n if key in self.storage:\n # Move it to the end\n node = self.storage[key]\n self.order.move_to_end(node)\n # return the value\n return node.value[1]\n # If key is NOT in storage\n else:\n return None\n\n def set(self, key):\n # check and see if the key is in the dict\n if key in self.storage:\n # If it is\n node = self.storage[key]\n # overwrite the value\n node.value = (key, value)\n # move it to the end\n self.order.move_to_end(node)\n # nothing else to do so exit function\n return\n # If it isn't\n # check if the cache is full\n if self.size == self.limit:\n # if cache is full\n # remove the oldest entry from dictionary\n del self.storage[self.order.head.value[0]]\n # and LL\n self.order.remove_from_head()\n # Reduce the size\n self.size -= 1\n # Add to the linked list (key and value)\n self.order.add_to_tail((key, value))\n # Add the key and value to the dictionary\n self.storage[key] = self.order.tail\n # Increment size\n self.size += 1\n","sub_path":"lru_cache/LruReview.py","file_name":"LruReview.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"184386695","text":"import mimicopynet as mcn\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport argparse\nimport os\nimport glob\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--gpu')\nparser.add_argument('--transcript', nargs=3)\nargs = parser.parse_args()\n\n\nprint('loading the model...', end='', flush=True)\ngpu = int(args.gpu) if args.gpu is not None else None\nmodel = mcn.model.BasicCNN(input_cnl=2, gpu=gpu)\nprint('Done.')\n\nif args.transcript is None: # 学習モード\n rd = mcn.data.RandomDataset(\n 10000,\n sound_font='mimicopynet/soundfonts/TimGM6mb.sf2',\n inst=[0,1],\n gpu=gpu,\n score_mode='onset',\n lmb_start_const=30.0\n )\n model.load_dataset(rd, None)\n model.load_cqt_inout(None, '1733_raw.npz')\n print('Start learning...')\n model.learn(iter_num=10000000)\n print('Learning Done.')\nelse: # 推論(耳コピ)モード\n model.load_model(\"result180505/model_130000.npz\")\n print(\"transcripting from\", args.transcript[0], \"to\", args.transcript[1], \"...\", end='', flush=True)\n model.transcript(args.transcript[0], args.transcript[1], mode='raw', imgfile=args.transcript[2])\n print(\"Done.\")\n","sub_path":"snippet2.py","file_name":"snippet2.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"93201311","text":"from jinja2 import Template\nimport lunar\nimport datetime\nimport time\nimport db\nimport os\nimport random\nfrom Person import create_person\nfrom sendmail import send_mail\n\ntemplatePathnameGroup = []\n\ndef init_template_pathname_group():\n\ttemplatePathnameGroup = filter(lambda x:x.endswith('.tpl'), os.listdir('./mail-templates'))\n\ndef main():\n\tnow = time.localtime()\n\tnow = datetime.datetime(now.tm_year, now.tm_mon, now.tm_mday)\n\tlunar_now = lunar.get_lunar_date(now)\n\tnow = (now.year, now.month, now.day)\n\t\n\tlog('now', now)\n\tlog('lunar_now', lunar_now)\n\n\tpersonGroup = []\n\n\tsql1 = 'select name, sex, birthday, calendar, mail from person where birthday=\"%04d-%02d-%02d\" and calendar=\"阳历\"' % (now[0], now[1], now[2])\n\tsql2 = 'select name, sex, birthday, calendar, mail from person where birthday=\"%04d-%02d-%02d\" and calendar=\"阴历\"' % (lunar_now[0], lunar_now[1], lunar_now[2])\n\tfor sql in (sql1, sql2):\n\t\tdb.select(sql, lambda item:personGroup.append({'name':item[0],'sex':item[1],'birthday':item[2],'calendar':item[3],'mail':item[4]}))\n\t\n\tinit_template_pathname_group()\n\n\tfor person in personGroup:\n\t\ttemplatePathname = random.choice(templatePathnameGroup)\n\t\ttemplate = Template(open(templatePathname, 'rt').read())\n\t\ttext = template.render(person = create_person(\n\t\t\t\tperson['name'],\n\t\t\t\tperson['sex'],\n\t\t\t\tperson['birthday'],\n\t\t\t\tperson['calendar'],\n\t\t\t\tperson['mail'],\n\t\t\t\tnow,\n\t\t\t\tlunar_now\n\t\t\t) \n\t\t)\n\t\tsend_mail('niu2x@346-1.com', person['mail'], 'Happy Birthday To You!', text)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"290329199","text":"def timeConversion(s):\n time = s.split(\":\")\n\n pm = False\n if time[-1].endswith(\"PM\"):\n pm = True\n time[-1] = time[-1].rstrip(\"PM\")\n else:\n time[-1] = time[-1].rstrip(\"AM\")\n\n if time[0] == \"12\" and not pm:\n time[0] = \"00\"\n elif time[0] != \"12\" and pm:\n time[0] = str(int(time[0]) + 12)\n\n return \":\".join(time)\n\n","sub_path":"easy/time-conversion-English.py","file_name":"time-conversion-English.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"435136547","text":"\"\"\" This script allows to test alternative releases against each other that are supposed\nto lead to the same results for selected requests.\n\"\"\"\nimport argparse\nimport os\nimport pickle as pkl\nimport random\nimport subprocess\nfrom datetime import datetime\nfrom datetime import timedelta\n\nimport numpy as np\n\nfrom development.modules.auxiliary_release import prepare_release_tests\nfrom development.modules.auxiliary_shared import cleanup\nfrom development.modules.auxiliary_shared import send_notification\nfrom respy import RespyCls\n\nSCRIPT_FNAME = \"../../modules/auxiliary_release.py\"\n\n\ndef run(request, is_create, is_background, old_release, new_release):\n \"\"\" Test the different releases against each other.\n \"\"\"\n cleanup()\n\n # Processing of command line arguments.\n if request[0] == \"investigate\":\n is_investigation, is_run = True, False\n elif request[0] == \"run\":\n is_investigation, is_run = False, True\n else:\n raise AssertionError(\"request in [run, investigate]\")\n\n seed_investigation, hours = None, 0.0\n if is_investigation:\n seed_investigation = int(request[1])\n assert isinstance(seed_investigation, int)\n elif is_run:\n hours = float(request[1])\n assert hours > 0.0\n\n # Set up auxiliary information to construct commands.\n env_dir = os.environ[\"HOME\"] + \"/.envs\"\n old_exec = env_dir + \"/\" + old_release + \"/bin/python\"\n new_exec = env_dir + \"/\" + new_release + \"/bin/python\"\n\n # Create fresh virtual environments if requested.\n if is_create:\n for release in [old_release, new_release]:\n cmd = [\"virtualenv\", env_dir + \"/\" + release, \"--clear\"]\n subprocess.check_call(cmd)\n\n # Set up the virtual environments with the two releases under\n # investigation.\n for which in [\"old\", \"new\"]:\n if which == \"old\":\n release, python_exec = old_release, old_exec\n elif which == \"new\":\n release, python_exec = new_release, new_exec\n else:\n raise AssertionError\n\n cmd = [python_exec, SCRIPT_FNAME, \"upgrade\"]\n subprocess.check_call(cmd)\n\n cmd = [python_exec, SCRIPT_FNAME, \"prepare\", release]\n subprocess.check_call(cmd)\n\n # Evaluation loop.\n start, timeout = datetime.now(), timedelta(hours=hours)\n num_tests, is_failure = 0, False\n\n while True:\n num_tests += 1\n\n # Set seed.\n if is_investigation:\n seed = seed_investigation\n else:\n seed = random.randrange(1, 100000)\n\n np.random.seed(seed)\n\n # The idea is to have all elements that are hand-crafted for the release comparison in\n # the function below.\n constr = {}\n constr[\"flag_estimation\"] = True\n\n prepare_release_tests(constr, old_release, new_release)\n\n # We use the current release for the simulation of the underlying dataset.\n respy_obj = RespyCls(\"test.respy.ini\")\n respy_obj.simulate()\n\n for which in [\"old\", \"new\"]:\n\n if which == \"old\":\n release, python_exec = old_release, old_exec\n elif which == \"new\":\n release, python_exec = old_release, new_exec\n else:\n raise AssertionError\n\n cmd = [python_exec, SCRIPT_FNAME, \"estimate\", which]\n subprocess.check_call(cmd)\n\n # Compare the resulting values of the criterion function.\n crit_val_old = pkl.load(open(\"old/crit_val.respy.pkl\", \"rb\"))\n crit_val_new = pkl.load(open(\"new/crit_val.respy.pkl\", \"rb\"))\n\n if not is_investigation:\n try:\n np.testing.assert_allclose(crit_val_old, crit_val_new)\n except AssertionError:\n is_failure = True\n else:\n np.testing.assert_allclose(crit_val_old, crit_val_new)\n\n is_timeout = timeout < datetime.now() - start\n\n if is_investigation or is_failure or is_timeout:\n break\n\n if not is_background and not is_investigation:\n send_notification(\n \"release\",\n hours=hours,\n is_failed=is_failure,\n seed=seed,\n num_tests=num_tests,\n old_release=old_release,\n new_release=new_release,\n )\n\n\nif __name__ == \"__main__\":\n\n # NOTES:\n #\n # All the versions are available on PYPI. Those marked as development versions are not\n # downloaded by an unsuspecting user. Instead, they need to be explicitly requested. Please\n # also make sure these versions are tagged in GIT.\n #\n # Version Description\n #\n # 1.0.0 Release for risk-only model\n #\n # 2.0.0.dev7 Ambiguity, probably same as v2.0.4\n #\n # 2.0.0.dev8 Ambiguity, now with free variances in worst-case determination\n #\n # 2.0.0.dev9 We added additional output for simulated datasets and included a script to\n # gently terminate an estimation.\n #\n # 2.0.0.dev10 We added additional information to the simulated dataset such as all\n # simulated rewards available for the individual each period. We also added the\n # ability to scale each coefficient simply by their magnitudes.\n #\n # 2.0.0.dev11 We added sheepskin effects and separate reentry cost by level of education.\n #\n # 2.0.0.dev12 We added a first-experience effect and scaled the squared term for the\n # experience variable by 100.\n #\n # 2.0.0.dev13 Flawed submission, simply just ignore.\n #\n # 2.0.0.dev14 We added initial conditions and unobserved type heterogeneity. It needs to be\n # checked against 2.0.0.dev14\n #\n # 2.0.0.dev15 This is a nuisance release as we did some minor work in the develop branch at\n # did not create a new branch right away.\n #\n # 2.0.0.dev16 We added age/period effects to each of the rewards.\n #\n # 2.0.0.dev17 We added state variables that capture last year's occupation.\n #\n # 2.0.0.dev18 We now allow for conditional type probabilities.\n #\n # 2.0.0.dev19 We now have more general rewards, i.e. not income maximizing.\n #\n # 2.0.0.dev19 We just worked on some issues to cleanup the code base. We did not find any\n # errors.\n #\n # The two releases that are tested against each other. These are downloaded from PYPI in\n # their own virtual environments.\n old_release, new_release = \"2.0.0.dev19\", \"2.0.0.dev20\"\n\n parser = argparse.ArgumentParser(description=\"Run release testing.\")\n\n parser.add_argument(\n \"--request\",\n action=\"store\",\n dest=\"request\",\n help=\"task to perform\",\n nargs=2,\n required=True,\n )\n\n parser.add_argument(\n \"--create\",\n action=\"store_true\",\n dest=\"is_create\",\n default=False,\n help=\"create new virtual environments\",\n )\n\n parser.add_argument(\n \"--background\",\n action=\"store_true\",\n dest=\"is_background\",\n default=False,\n help=\"background process\",\n )\n\n # Distribute arguments\n args = parser.parse_args()\n request, is_create = args.request, args.is_create\n is_background = args.is_background\n\n run(request, is_create, is_background, old_release, new_release)\n","sub_path":"development/testing/release/run_release.py","file_name":"run_release.py","file_ext":"py","file_size_in_byte":7393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"219434618","text":"import socket, datetime\nfrom urllib.parse import unquote\nimport requests, json, os\n\nclass server():\n def __init__(self):\n self.host_ip = socket.gethostbyname(socket.gethostname())\n self.host_port = 80\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.data_recv_size = 1024\n\n def get_data(self, conn):\n \"\"\" gets the data from client \"\"\"\n data = b\"\"\n while b\"\\r\\n\\r\\n\" not in data:\n data += conn.recv(self.data_recv_size)\n return data\n\n def print_request(self, request):\n \"\"\" prints the contents of a request \"\"\"\n print()\n for i in request.keys():\n print(i, \"\\t\", str(request[i]))\n\n def format_request(self, conn, do_print=False):\n \"\"\" formats the HTTP request into dict \"\"\"\n request_raw = self.get_data(conn)\n\n # generate dict of data\n request = {}\n request[b\"type\"] = []\n get_part = True\n for instruction in request_raw.split(b'\\r\\n'):\n temp = instruction.split(b': ')\n if len(temp) == 2:\n request[temp[0]] = temp[1]\n else:\n if get_part == True:\n parts = temp[0].split(b' ') + [None, None, None]\n request[b\"header\"] = temp[0]\n request[b\"type\"] = parts[0]\n request[b\"file_name\"] = parts[1]\n request[b\"HTTP_version\"] = parts[2]\n get_part = False\n \n if do_print == True:\n self.print_request(request)\n \n return request\n \n def connection_handler(self, conn, addr):\n \"\"\" accepts multiple requests from client and passes them to request handler \"\"\"\n with conn:\n request = self.format_request(conn)\n http_s = http()\n http_s.serve(conn, request, addr)\n\n def server(self):\n \"\"\" main method starts the server \"\"\"\n print(f\"[+] Server started listening on port {self.host_port}!\")\n print(f\"[+] Server Ip: {self.host_ip}\")\n self.s.bind((self.host_ip, self.host_port))\n self.s.listen()\n\n while True:\n conn, addr = self.s.accept()\n self.connection_handler(conn, addr)\n\nclass http():\n def __init__(self):\n self.current_domain = b\"www.google.co.uk\"\n self.redirect_domain = b\"172.21.0.1\"\n \n def GET(self, conn, request, addr, custom_404=True):\n # check if index was requested\n if request[b\"file_name\"] == b\"/\":\n filename = \"/index.html\"\n else:\n filename = request[b\"file_name\"]\n ext = filename.split(b'/')[-1]\n if ext == b\"\":\n filename += b\"index.html\"\n elif b\".\" not in ext:\n filename += b\"/index.html\"\n\n # check if file exists\n try:\n path = unquote(filename[1:]).replace('//', '/')\n #file_to_sent = open(path, \"rb\").read()\n\n #check for domain\n temp_domain = path.split('/')[0].encode('UTF-8')\n if b'.' in temp_domain:\n self.current_domain = temp_domain\n print(b\"[+] Changed domain! \"+temp_domain+b\"!\")\n\n # proxy download html\n url = f\"http://{path}\"\n print(url)\n proxy_html = download_html(url)\n\n # replace all links with proxy\n proxy_html = proxy_html.replace(b'href=\"https://', b'href=\"http://'+self.current_domain+b'/')\n proxy_html = proxy_html.replace(b'src=\"https://', b'src=\"https://'+self.current_domain+b'/')\n proxy_html = proxy_html.replace(b'href=\"', b'href=\"http://'+self.redirect_domain+b'/'+self.current_domain+b'/')\n proxy_html = proxy_html.replace(b'src=\"', b'src=\"http://'+self.redirect_domain+b'/'+self.current_domain+b'/')\n\n # send the html\n conn.sendall(proxy_html)\n print(f\"[+] Sent file '{filename}' to {addr[0]}!\")\n \n except FileNotFoundError:\n # send 404\n print(f\"[-] 404 not found {filename} sent to {addr[0]}!\")\n if custom_404 == True:\n conn.sendall(open('404.html', 'rb').read())\n else:\n conn.sendall(b\"404 webpage not found '\"+bytes(filename)+b\"' !\")\n \n def POST(self, conn, request, addr):\n pass\n\n def serve(self, conn, request, addr):\n if request[b\"type\"] == b\"GET\":\n http.GET(self, conn, request, addr)\n\ndef download_html(url):\n user_agent = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:38.0) Gecko/20100101 Firefox/38.0\"\n\n head = {\n \"User-Agent\": user_agent,\n }\n\n try:\n req = requests.get(url, headers=head)\n html = req.content\n print(req.status_code)\n return html\n except:\n print(\"[-] Error failed to fetch page!\")\n return b\"404\"\n\ns = server()\ns.server()\n","sub_path":"web server/proxy2/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"155285886","text":"import numpy as np\n\nfrom cs231n.layers import *\nfrom cs231n.layer_utils import *\n\n\nclass TwoLayerNet(object):\n\n def __init__(self, input_dim=3*32*32, hidden_dim=100, num_classes=10,\n weight_scale=1e-3, reg=0.0):\n \n self.params = {}\n self.reg = reg\n self.params['W1'] = weight_scale * np.random.randn(input_dim, hidden_dim)\n self.params['W2'] = weight_scale * np.random.randn(hidden_dim, num_classes)\n \n self.params['b1'] = np.zeros(hidden_dim)\n self.params['b2'] = np.zeros(num_classes)\n\n def loss(self, X, y=None):\n scores = None\n\n out1, cache1 = affine_relu_forward(X, self.params['W1'], self.params['b1'])\n scores, cache2 = affine_relu_forward(out1, self.params['W2'], self.params['b2'])\n \n if y is None:\n return scores\n\n loss, grads = 0, {}\n\n loss, ds = softmax_loss(scores, y) \n loss += (self.reg/2) * (np.sum(self.params['W1']**2, axis=None) + np.sum(self.params['W2']**2, axis=None))\n \n dout1, grads['W2'], grads['b2'] = affine_relu_backward(ds, cache2)\n grads['W2'] += (self.reg * self.params['W2'])\n \n _, grads['W1'], grads['b1'] = affine_relu_backward(dout1, cache1)\n grads['W1'] += (self.reg * self.params['W1'])\n \n return loss, grads\n\n \nclass FullyConnectedNet(object):\n \"\"\"\n A fully-connected neural network with an arbitrary number of hidden layers,\n ReLU nonlinearities, and a softmax loss function. This will also implement\n dropout and batch normalization as options. For a network with L layers,\n the architecture will be\n\n {affine - [batch norm] - relu - [dropout]} x (L - 1) - affine - softmax\n\n where batch normalization and dropout are optional, and the {...} block is\n repeated L - 1 times.\n\n Similar to the TwoLayerNet above, learnable parameters are stored in the\n self.params dictionary and will be learned using the Solver class.\n \"\"\"\n\n def __init__(self, hidden_dims, input_dim=3*32*32, num_classes=10,\n dropout=0, use_batchnorm=False, reg=0.0,\n weight_scale=1e-2, dtype=np.float32, seed=None):\n \"\"\"\n Initialize a new FullyConnectedNet.\n\n Inputs:\n - hidden_dims: A list of integers giving the size of each hidden layer.\n - input_dim: An integer giving the size of the input.\n - num_classes: An integer giving the number of classes to classify.\n - dropout: Scalar between 0 and 1 giving dropout strength. If dropout=0 then\n the network should not use dropout at all.\n - use_batchnorm: Whether or not the network should use batch normalization.\n - reg: Scalar giving L2 regularization strength.\n - weight_scale: Scalar giving the standard deviation for random\n initialization of the weights.\n - dtype: A numpy datatype object; all computations will be performed using\n this datatype. float32 is faster but less accurate, so you should use\n float64 for numeric gradient checking.\n - seed: If not None, then pass this random seed to the dropout layers. This\n will make the dropout layers deteriminstic so we can gradient check the\n model.\n \"\"\"\n self.use_batchnorm = use_batchnorm\n self.use_dropout = dropout > 0\n self.reg = reg\n self.num_layers = 1 + len(hidden_dims)\n self.dtype = dtype\n self.params = {}\n\n ############################################################################\n # TODO: Initialize the parameters of the network, storing all values in #\n # the self.params dictionary. Store weights and biases for the first layer #\n # in W1 and b1; for the second layer use W2 and b2, etc. Weights should be #\n # initialized from a normal distribution with standard deviation equal to #\n # weight_scale and biases should be initialized to zero. #\n # #\n # When using batch normalization, store scale and shift parameters for the #\n # first layer in gamma1 and beta1; for the second layer use gamma2 and #\n # beta2, etc. Scale parameters should be initialized to one and shift #\n # parameters should be initialized to zero. #\n ############################################################################\n pass\n ############################################################################\n # END OF YOUR CODE #\n ############################################################################\n for layer in range(self.num_layers):\n \n if layer == 0:\n self.params['W'+str(layer+1)] = weight_scale * np.random.randn(input_dim, hidden_dims[layer])\n self.params['b'+str(layer+1)] = np.zeros(hidden_dims[layer])\n if self.use_batchnorm:\n self.params['gamma'+str(layer+1)] = np.ones(hidden_dims[layer])\n self.params['beta'+str(layer+1)] = np.zeros(hidden_dims[layer])\n \n elif layer == self.num_layers-1:\n self.params['W'+str(layer+1)] = weight_scale * np.random.randn(hidden_dims[layer-1], num_classes)\n self.params['b'+str(layer+1)] = np.zeros(num_classes)\n \n else:\n self.params['W'+str(layer+1)] = weight_scale * np.random.randn(hidden_dims[layer-1], hidden_dims[layer])\n self.params['b'+str(layer+1)] = np.zeros(hidden_dims[layer])\n if self.use_batchnorm:\n self.params['gamma'+str(layer+1)] = np.ones(hidden_dims[layer])\n self.params['beta'+str(layer+1)] = np.zeros(hidden_dims[layer])\n \n # When using dropout we need to pass a dropout_param dictionary to each\n # dropout layer so that the layer knows the dropout probability and the mode\n # (train / test). You can pass the same dropout_param to each dropout layer.\n self.dropout_param = {}\n if self.use_dropout:\n self.dropout_param = {'mode': 'train', 'p': dropout}\n if seed is not None:\n self.dropout_param['seed'] = seed\n\n # With batch normalization we need to keep track of running means and\n # variances, so we need to pass a special bn_param object to each batch\n # normalization layer. You should pass self.bn_params[0] to the forward pass\n # of the first batch normalization layer, self.bn_params[1] to the forward\n # pass of the second batch normalization layer, etc.\n self.bn_params = []\n if self.use_batchnorm:\n self.bn_params = [{'mode': 'train'} for i in range(self.num_layers+1)]\n\n # Cast all parameters to the correct datatype\n for k, v in self.params.items():\n self.params[k] = v.astype(dtype)\n\n\n def loss(self, X, y=None):\n \"\"\"\n Compute loss and gradient for the fully-connected net.\n\n Input / output: Same as TwoLayerNet above.\n \"\"\"\n X = X.astype(self.dtype)\n mode = 'test' if y is None else 'train'\n\n # Set train/test mode for batchnorm params and dropout param since they\n # behave differently during training and testing.\n if self.use_dropout:\n self.dropout_param['mode'] = mode\n if self.use_batchnorm:\n for bn_param in self.bn_params:\n bn_param['mode'] = mode\n\n scores = None\n ############################################################################\n # TODO: Implement the forward pass for the fully-connected net, computing #\n # the class scores for X and storing them in the scores variable. #\n # #\n # When using dropout, you'll need to pass self.dropout_param to each #\n # dropout forward pass. #\n # #\n # When using batch normalization, you'll need to pass self.bn_params[0] to #\n # the forward pass for the first batch normalization layer, pass #\n # self.bn_params[1] to the forward pass for the second batch normalization #\n # layer, etc. #\n ############################################################################\n pass\n ############################################################################\n # END OF YOUR CODE #\n ############################################################################\n cache = {'relu' : [None for _ in range(self.num_layers+1)], 'dropout': [None for _ in range(self.num_layers+1)], \n 'bn': [None for _ in range(self.num_layers+1)]}\n \n out = [None for _ in range(self.num_layers+1)]\n out[0] = X.copy()\n\n for i in range(1, self.num_layers+1):\n ind = str(i)\n if i == self.num_layers:\n out[i], cache['relu'][i] = affine_forward(out[i-1], self.params['W'+ind], self.params['b'+ind])\n scores = out[i].copy() \n else:\n if self.use_batchnorm:\n out[i], cache['bn'][i] = affine_bn_relu_forward(out[i-1], self.params['W'+ind], self.params['b'+ind], self.params['gamma'+ind], self.params['beta'+ind], self.bn_params[i])\n else:\n out[i], cache['relu'][i] = affine_relu_forward(out[i-1], self.params['W'+ind], self.params['b'+ind])\n \n if self.use_dropout:\n out[i], cache['dropout'][i] = dropout_forward(out[i], self.dropout_param)\n\n # If test mode return early\n \n if mode == 'test':\n return scores\n\n loss, grads = 0.0, {}\n ############################################################################\n # TODO: Implement the backward pass for the fully-connected net. Store the #\n # loss in the loss variable and gradients in the grads dictionary. Compute #\n # data loss using softmax, and make sure that grads[k] holds the gradients #\n # for self.params[k]. Don't forget to add L2 regularization! #\n # #\n # When using batch normalization, you don't need to regularize the scale #\n # and shift parameters. #\n # #\n # NOTE: To ensure that your implementation matches ours and you pass the #\n # automated tests, make sure that your L2 regularization includes a factor #\n # of 0.5 to simplify the expression for the gradient. #\n ############################################################################\n pass\n ############################################################################\n # END OF YOUR CODE #\n ############################################################################\n dout = [None for _ in range(self.num_layers+1)]\n loss, dout[-1] = softmax_loss(scores, y)\n loss += (self.reg/2) * np.sum([(np.sum(self.params['W'+str(i)]**2, axis=None)) for i in range(1, self.num_layers+1)])\n \n for i in range(self.num_layers, 0, -1):\n ind = str(i)\n if i == self.num_layers:\n dout[i-1], grads['W'+ind], grads['b'+ind] = affine_backward(dout[i], cache['relu'][i])\n grads['W'+ind] += self.reg * self.params['W'+ind]\n else:\n if self.use_dropout:\n dout[i] = dropout_backward(dout[i], cache['dropout'][i])\n \n if self.use_batchnorm:\n dout[i-1], grads['W'+ind], grads['b'+ind], grads['gamma'+ind], grads['beta'+ind] =affine_bn_relu_backward(dout[i], cache['bn'][i])\n grads['W'+ind] += self.reg * self.params['W'+ind]\n else:\n dout[i-1], grads['W'+ind], grads['b'+ind] = affine_relu_backward(dout[i], cache['relu'][i])\n grads['W'+ind] += self.reg * self.params['W'+ind]\n \n return loss, grads\n","sub_path":"Assignment2/cs231n/classifiers/fc_net.py","file_name":"fc_net.py","file_ext":"py","file_size_in_byte":12749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"203605505","text":"#===============================================================================\n# Copyright 2012 Jake Ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#===============================================================================\n\n#============= enthought library imports =======================\nfrom traits.api import HasTraits\nimport struct\nfrom src.processing.argon_calculations import calculate_flux\nfrom src.database.records.isotope_record import IsotopeRecord\nfrom uncertainties import ufloat\nfrom src.regression.ols_regressor import MultipleLinearRegressor\n# from src.graph.graph3D import Graph3D\n# from mayavi import mlab\nimport numpy as np\n#============= standard library imports ========================\n#============= local library imports ==========================\n\nclass FluxView(HasTraits):\n def model_flux(self, analyses, monitor_age):\n '''\n analysis: dict of key=holenum, value=(xy, [analyses list])\n '''\n def calc_j(ai):\n ai._calculate_age()\n ar40 = ai.arar_result['rad40']\n ar39 = ai.arar_result['k39']\n return calculate_flux(ar40, ar39, monitor_age)\n\n def mean_j(ans):\n js, wts = zip(*[calc_j(ai) for ai in ans])\n return np.average(js, weights=wts), np.std(js)\n# positions = []\n# ys = []\n# for k, (position, ans) in analyses.iteritems():\n# print k, position, len(analyses)\n# Z = sum([calc_j(ai) for ai in ans]) / len(ans)\n\n# X, Y = position\n# print X, Y, Z\n# positions.append(position)\n# ys.append(Z.nominal_value)\n positions, ys = zip(*[(pos, mean_j(ans)) for (pos, ans) in analyses.itervalues()])\n\n ys, ye = zip(*ys)\n# # print positions\n reg = MultipleLinearRegressor(xs=positions, ys=ys)\n# # p = reg.predict([(0.0, 0.85)]) #0.00484421950062+/-8.3063828332e-06\n# # print p, p - 0.00484421950062\n# g = Graph3D()\n# import numpy as np\n x, y = zip(*positions)\n x = np.array(x)\n y = np.array(y)\n ys = np.array(ys)\n\n w = max(x) - min(x)\n c = len(x)\n r = len(y)\n n = r * 2 - 1\n xx, yy = np.mgrid[0:n + 1, 0:n + 1]\n xx = xx / float(n) * w - w / 2.\n yy = yy / float(n) * w - w / 2.\n\n# xx = xx * r / 2. - w\n# yy = yy * r / 2. - w\n z = np.zeros((r * 2, c * 2))\n\n for i in range(r * 2):\n for j in range(c * 2):\n pt = (xx[i, j],\n yy[i, j])\n z[i, j] = reg.predict([pt])[0]\n\n normalize = False\n if normalize:\n z *= 1 / z.max() # * w - w / 2.\n z *= 100\n z -= z.min() + (z.max() - z.min()) / 2.\n\n # w = ys.max() - ys.min()\n ys *= 1 / ys.max() - ys.min() # * w - w / 2.\n ys *= 100\n ys -= ys.min() + (ys.max() - ys.min()) / 2.\n\n# z = z / abs(z).max() * 100\n# ys *= 1 / ys.max() * 100\n# print pt, z[j, i]\n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D\n from matplotlib import cm\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n ax.plot_surface(xx, yy, z, alpha=0.3,\n rstride=1, cstride=1,\n cmap=cm.coolwarm,\n linewidths=0\n\n )\n# ax.scatter(x, y, zs)\n ax.scatter(x, y, ys)\n for xi, yi, zi, ei in zip(x, y, ys, ye):\n# for i in np.arange(0, len(x)):\n ax.plot([xi, xi], [yi, yi], [zi - ei, zi + ei],\n color='black',\n marker='_'\n )\n plt.show()\n# mlab.surf(z, warp_scale=10000)\n# mlab.axes()\n# mlab.outline()\n# mlab.points3d(x, y, zs * 10000)\n# mlab.show()\n# z = reg.predict([(0, 0)])\n# print z\n#\n# z = z.reshape((r, c))\n# print z\n\n\n# print xx\n# print z\n# g.plot_surf(z, warp_scale='auto')\n# g.plot_surf(np.zeros((r, c)))\n# print ys\n\n# g.plot_lines(x, y, ys)\n# print len(x), len(y), len(zs)\n# g.plot_points(x, y, np.array(zs) * 10000)\n# g.plot_points(x, y, np.array(ys) * 10000)\n# g.configure_traits()\n\nif __name__ == '__main__':\n from src.helpers.logger_setup import logging_setup\n logging_setup('ia')\n from src.database.adapters.isotope_adapter import IsotopeAdapter\n db = IsotopeAdapter(name='isotopedb_dev',\n username='root',\n password='Argon',\n host='localhost',\n kind='mysql')\n db.connect()\n\n fv = FluxView()\n\n irrad = db.get_irradiation('NM-251')\n level = db.get_irradiation_level('NM-251', 'H')\n geom = level.holder.geometry\n irrads = db.get_irradiation_position('NM-251', 'H', [7, 8, 9, 10, 11, 12])\n\n geometry = [struct.unpack('>ff', geom[i:i + 8]) for i in xrange(0, len(geom), 8)]\n\n# positions = dict()\n analyses = dict()\n for ir in irrads:\n xy = geometry[ir.position - 1]\n\n ans = []\n# print ir.labnumber.labnumber\n# for an in ir.labnumber.analyses:\n# if an.status\n# print an.status\n# a = IsotopeRecord(_dbrecord=an)\n# ans.append(a)\n ans = [IsotopeRecord(_dbrecord=an) for an in ir.labnumber.analyses if an.status == 0]\n analyses[ir.position] = (xy, ans)\n\n\n# ans = dict([(ir.position, ir.labnumber.analyses) for ir in irrads])\n# print irrad\n# ans =\n\n fv.model_flux(analyses, ufloat(28.02e6, 0))\n# xs = [[ 0. , 0.85000002 ],\n# [ 0.80000001 , 0.40000001 ],\n# [ 0.80000001 , -0.40000001 ],\n# [ 0. , -0.85000002 ],\n# [-0.80000001 , -0.40000001 ],\n# [-0.80000001 , 0.40000001 ]]\n# ys = [1, 1, 1, 1, 1, 1]\n# xs = [(0, 0), (1, 0), (2, 0)]\n# ys = [0, 1, 2]\n# reg = MultipleLinearRegressor(xs=xs, ys=ys)\n# # p = reg.predict([(0.0, 0.85)]) #0.00484421950062+/-8.3063828332e-06\n# # print p, p - 0.00484421950062\n# g = Graph3D()\n# import numpy as np\n# x, y = zip(*xs)\n# xx, yy = np.meshgrid(x, y)\n# r = len(x)\n# c = len(y)\n# pts = [(xx[j, i], yy[j, i]) for i in range(r)\n# for j in range(c)]\n#\n# z = reg.predict(pts)\n#\n# z = z.reshape((r, c))\n# # z = np.column_stack((xs, ys))\n# # print z\n#\n# # ys = np.ones((3, 3))\n# # zs = ys * z\n# # print x\n# # print y\n# # print zs\n# g.plot_surf(z)\n# # g.plot_surf(x, y, ys)\n# # g.plot_surf(x, y, zs)\n# g.configure_traits()\n#============= EOF =============================================\n","sub_path":"src/processing/flux/flux_test.py","file_name":"flux_test.py","file_ext":"py","file_size_in_byte":7300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"376869194","text":"from __future__ import absolute_import, division, unicode_literals\n\nfrom tqdm import tqdm\n\nimport logging\nfrom math import fsum\nfrom time import time\n\nfrom cachetools import LRUCache\nfrom operator import attrgetter\nfrom cachetools import cachedmethod\n\nfrom numpy import var as variance\nfrom numpy import (abs, all, any, asarray, diagonal, dot, empty, empty_like,\n errstate, inf, isfinite, log, sqrt, sum, zeros, clip,\n zeros_like, resize)\nfrom scipy.linalg import cho_factor\nfrom scipy.optimize import fmin_tnc\nfrom numpy.linalg import LinAlgError\n\nfrom numpy_sugar import is_all_finite\nfrom numpy_sugar.linalg import (cho_solve, ddot, dotd, economic_svd, solve, sum2diag,\n trace2, economic_qs)\n\nfrom ._conditioning import make_sure_reasonable_conditioning\nfrom numpy_sugar import epsilon\n\nfrom ._fixed import FixedEP\n\nMAX_EP_ITER = 30\nEP_EPS = 1e-5\n\n_magic_numbers = dict(xtol=1e-5, rescale=10, pgtol=1e-5, ftol=1e-5, disp=0)\n\n\nclass EP(object):\n r\"\"\"Generic EP implementation.\n\n Let :math:`\\mathrm Q \\mathrm S \\mathrm Q^{\\intercal}` be the economic\n eigendecomposition of the genetic covariance matrix.\n Let :math:`\\mathrm U\\mathrm S\\mathrm V^{\\intercal}` be the singular value\n decomposition of the user-provided covariates :math:`\\mathrm M`. We define\n\n .. math::\n\n \\mathrm K = v ((1-\\delta)\\mathrm Q \\mathrm S \\mathrm Q^{\\intercal} +\n \\delta \\mathrm I)\n\n as the covariance of the prior distribution. As such,\n :math:`v` and :math:`\\delta` refer to :py:attr:`_v` and :py:attr:`_delta`\n class attributes, respectively. We also use the following variables for\n convenience:\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray}\n \\sigma_b^2 & = & v (1-\\delta) \\\\\n \\sigma_{\\epsilon}^2 & = & v \\delta\n \\end{eqnarray}\n\n The covariate effect-sizes is given by :math:`\\boldsymbol\\beta`, which\n implies\n\n .. math::\n\n \\mathbf m = \\mathrm M \\boldsymbol\\beta\n\n The prior is thus defined as\n\n .. math::\n\n \\mathcal N(\\mathbf z ~|~ \\mathbf m; \\mathrm K)\n\n and the marginal likelihood is given by\n\n .. math::\n\n p(\\mathbf y) = \\int \\prod_i p(y_i | g(\\mathrm E[y_i | z_i])=z_i)\n \\mathcal N(\\mathbf z ~|~ \\mathbf m, \\mathrm K) \\mathrm d\\mathbf z\n\n However, the singular value decomposition of the covariates allows us to\n automatically remove dependence between covariates, which would create\n infinitly number of :math:`\\boldsymbol\\beta` that lead to global optima.\n Let us define\n\n .. math::\n\n \\tilde{\\boldsymbol\\beta} = \\mathrm S^{1/2} \\mathrm V^{\\intercal}\n \\boldsymbol\\beta\n\n as the covariate effect-sizes we will effectively work with during the\n optimization process. Let us also define the\n\n .. math::\n\n \\tilde{\\mathrm M} = \\mathrm U \\mathrm S^{1/2}\n\n as the redundance-free covariates. Naturally,\n\n .. math::\n\n \\mathbf m = \\tilde{\\mathrm M} \\tilde{\\boldsymbol\\beta}\n\n In summary, we will optimize :math:`\\tilde{\\boldsymbol{\\beta}}`, even\n though the user will be able to retrieve the corresponding\n :math:`\\boldsymbol{\\beta}`.\n\n\n Let\n\n .. math::\n\n \\mathrm{KL}[p(y_i|z_i) p_{-}(z_i|y_i)_{\\text{EP}} ~|~\n p(y_i|z_i)_{\\text{EP}} p_{-}(z_i|y_i)_{\\text{EP}}]\n\n be the KL divergence we want to minimize at each EP iteration.\n The left-hand side can be described as\n :math:`\\hat c_i \\mathcal N(z_i | \\hat \\mu_i; \\hat \\sigma_i^2)`\n\n\n Args:\n M (array_like): :math:`\\mathrm M` covariates.\n Q (array_like): :math:`\\mathrm Q` of the economic\n eigendecomposition.\n S (array_like): :math:`\\mathrm S` of the economic\n eigendecomposition.\n overdispersion (bool): `True` for :math:`\\sigma_{\\epsilon}^2 \\ge 0`,\n `False` for :math:`\\sigma_{\\epsilon}^2=0`.\n QSQt (array_like): :math:`\\mathrm Q \\mathrm S\n \\mathrm Q^{\\intercal}` in case this has already\n been computed. Defaults to `None`.\n\n\n Attributes:\n _v (float): Total variance :math:`v` from the prior distribution.\n _delta (float): Fraction of the total variance due to the identity\n matrix :math:`\\mathrm I`.\n _loghz (array_like): This is :math:`\\log(\\hat c)` for each site.\n _hmu (array_like): This is :math:`\\hat \\mu` for each site.\n _hvar (array_like): This is :math:`\\hat \\sigma^2` for each site.\n\n \"\"\"\n\n def __init__(self, M, Q, S, overdispersion):\n self._cache_SQt = LRUCache(maxsize=1)\n self._cache_m = LRUCache(maxsize=1)\n self._cache_K = LRUCache(maxsize=1)\n self._cache_diagK = LRUCache(maxsize=1)\n self._cache_update = LRUCache(maxsize=1)\n self._cache_lml_components = LRUCache(maxsize=1)\n self._cache_L = LRUCache(maxsize=1)\n self._cache_A = LRUCache(maxsize=1)\n self._cache_C = LRUCache(maxsize=1)\n self._cache_BiQt = LRUCache(maxsize=1)\n self._cache_QBiQtAm = LRUCache(maxsize=1)\n self._cache_QBiQtCteta = LRUCache(maxsize=1)\n\n self._logger = logging.getLogger(__name__)\n\n if not is_all_finite(Q) or not is_all_finite(isfinite(S)):\n raise ValueError(\"There are non-finite numbers in the provided\" +\n \" eigen decomposition.\")\n\n if S.min() <= 0:\n raise ValueError(\"The provided covariance matrix is not\" +\n \" positive-definite because the minimum\" +\n \" eigvalue is %f.\" % S.min())\n\n make_sure_reasonable_conditioning(S)\n\n self._S = S\n self._Q = Q\n self.__QSQt = None\n\n nsamples = M.shape[0]\n self._previous_sitelik_tau = zeros(nsamples)\n self._previous_sitelik_eta = zeros(nsamples)\n\n self._sitelik_tau = zeros(nsamples)\n self._sitelik_eta = zeros(nsamples)\n\n self._cav_tau = zeros(nsamples)\n self._cav_eta = zeros(nsamples)\n\n self._joint_tau = zeros(nsamples)\n self._joint_eta = zeros(nsamples)\n\n self._v = None\n self._delta = 0\n self._overdispersion = overdispersion\n self._tM = None\n self.__tbeta = None\n self._covariate_setup(M)\n\n self._loghz = empty(nsamples)\n self._hmu = empty(nsamples)\n self._hvar = empty(nsamples)\n self._ep_params_initialized = False\n\n def _copy_to(self, ep):\n ep._cache_SQt = LRUCache(maxsize=1)\n ep._cache_m = LRUCache(maxsize=1)\n ep._cache_K = LRUCache(maxsize=1)\n ep._cache_diagK = LRUCache(maxsize=1)\n ep._cache_update = LRUCache(maxsize=1)\n ep._cache_lml_components = LRUCache(maxsize=1)\n ep._cache_L = LRUCache(maxsize=1)\n ep._cache_A = LRUCache(maxsize=1)\n ep._cache_C = LRUCache(maxsize=1)\n ep._cache_BiQt = LRUCache(maxsize=1)\n ep._cache_QBiQtAm = LRUCache(maxsize=1)\n ep._cache_QBiQtCteta = LRUCache(maxsize=1)\n\n ep._logger = logging.getLogger(__name__)\n\n ep._S = self._S\n ep._Q = self._Q\n ep.__QSQt = self.__QSQt\n\n ep._previous_sitelik_tau = self._previous_sitelik_tau.copy()\n ep._previous_sitelik_eta = self._previous_sitelik_eta.copy()\n\n ep._sitelik_tau = self._sitelik_tau.copy()\n ep._sitelik_eta = self._sitelik_eta.copy()\n\n ep._cav_tau = self._cav_tau.copy()\n ep._cav_eta = self._cav_eta.copy()\n\n ep._joint_tau = self._joint_tau.copy()\n ep._joint_eta = self._joint_eta.copy()\n\n ep._v = self._v\n ep._delta = self._delta\n ep._overdispersion = self._overdispersion\n ep._tM = self._tM\n ep.__tbeta = self.__tbeta.copy()\n ep._M = self._M\n ep._svd_U = self._svd_U\n ep._svd_S12 = self._svd_S12\n ep._svd_V = self._svd_V\n\n ep._loghz = self._loghz.copy()\n ep._hmu = self._hmu.copy()\n ep._hvar = self._hvar.copy()\n ep._ep_params_initialized = self._ep_params_initialized\n\n def _covariate_setup(self, M):\n self._M = M\n SVD = economic_svd(M)\n self._svd_U = SVD[0]\n self._svd_S12 = sqrt(SVD[1])\n self._svd_V = SVD[2]\n self._tM = ddot(self._svd_U, self._svd_S12, left=False)\n if self.__tbeta is not None:\n self.__tbeta = resize(self.__tbeta, self._tM.shape[1])\n\n def _init_ep_params(self):\n self._logger.debug(\"EP parameters initialization.\")\n\n if self._ep_params_initialized:\n self._joint_update()\n else:\n self._joint_initialize()\n self._sitelik_initialize()\n self._ep_params_initialized = True\n\n def fixed_ep(self):\n w1, w2, w3, _, _, w6, w7 = self._lml_components()\n\n lml_const = w1 + w2 + w3 + w6 + w7\n\n beta_nom = self._optimal_beta_nom()\n\n return FixedEP(lml_const,\n self._A(),\n self._C(),\n self._L(), self._Q,\n self._QBiQtCteta(), self._sitelik_eta, beta_nom)\n\n def _joint_initialize(self):\n r\"\"\"Initialize the mean and covariance of the posterior.\n\n Given that :math:`\\tilde{\\mathrm T}` is a matrix of zeros before the\n first EP iteration, we have\n\n .. math::\n :nowrap:\n\n \\begin{eqnarray}\n \\Sigma & = & \\mathrm K \\\\\n \\boldsymbol\\mu & = & \\mathrm K^{-1} \\mathbf m\n \\end{eqnarray}\n \"\"\"\n self._joint_tau[:] = 1 / self._diagK()\n self._joint_eta[:] = self.m()\n self._joint_eta[:] *= self._joint_tau\n\n def _sitelik_initialize(self):\n self._sitelik_tau[:] = 0.\n self._sitelik_eta[:] = 0.\n\n @cachedmethod(attrgetter('_cache_K'))\n def K(self):\n r\"\"\"Covariance matrix of the prior.\n\n Returns:\n :math:`\\sigma_b^2 \\mathrm Q_0 \\mathrm S_0 \\mathrm Q_0^{\\intercal} + \\sigma_{\\epsilon}^2 \\mathrm I`.\n \"\"\"\n return sum2diag(self.sigma2_b * self._QSQt(), self.sigma2_epsilon)\n\n def _Kdot(self, x):\n Q = self._Q\n S = self._S\n out = dot(Q.T, x)\n out *= S\n out = dot(Q, out)\n out *= (1 - self.delta)\n out += self.delta * x\n out *= self.v\n return out\n\n @cachedmethod(attrgetter('_cache_diagK'))\n def _diagK(self):\n r\"\"\"Returns the diagonal of :math:`\\mathrm K`.\"\"\"\n return self.sigma2_b * self._diagQSQt() + self.sigma2_epsilon\n\n def _diagQSQt(self):\n return self._QSQt().diagonal()\n\n @cachedmethod(attrgetter('_cache_m'))\n def m(self):\n r\"\"\"Mean vector of the prior.\n\n Returns:\n :math:`\\mathrm M \\boldsymbol\\beta`.\n \"\"\"\n return dot(self._tM, self._tbeta)\n\n @property\n def covariates_variance(self):\n r\"\"\"Variance explained by the covariates.\n\n It is defined as\n\n .. math::\n\n \\sigma_a^2 = \\sum_{s=1}^p \\left\\{ \\sum_{i=1}^n \\left(\n \\mathrm M_{i,s}\\beta_s - \\sum_{j=1}^n\n \\frac{\\mathrm M_{j,s}\\beta_s}{n} \\right)^2 \\Big/ n\n \\right\\}\n\n where :math:`p` is the number of covariates and :math:`n` is the number\n of individuals. One can show that it amounts to\n :math:`\\sum_s \\beta_s^2` whenever the columns of :math:`\\mathrm M`\n are normalized to have mean and standard deviation equal to zero and\n one, respectively.\n \"\"\"\n return fsum(variance(self.M * self.beta, axis=0))\n\n @property\n def sigma2_b(self):\n r\"\"\"Returns :math:`v (1-\\delta)`.\"\"\"\n return self.v * (1 - self.delta)\n\n @property\n def sigma2_epsilon(self):\n r\"\"\"Returns :math:`v \\delta`.\"\"\"\n return self.v * self.delta\n\n @property\n def delta(self):\n r\"\"\"Returns :math:`\\delta`.\"\"\"\n return self._delta\n\n @delta.setter\n def delta(self, v):\n r\"\"\"Set :math:`\\delta`.\"\"\"\n self._cache_K.clear()\n self._cache_diagK.clear()\n self._cache_update.clear()\n self._cache_lml_components.clear()\n self._cache_L.clear()\n self._cache_A.clear()\n self._cache_C.clear()\n self._cache_BiQt.clear()\n self._cache_QBiQtAm.clear()\n self._cache_QBiQtCteta.clear()\n if not (0 <= v <= 1):\n raise ValueError(\"delta should not be %f.\" % v)\n self._delta = v\n\n @property\n def v(self):\n r\"\"\"Returns :math:`v`.\"\"\"\n return self._v\n\n @v.setter\n def v(self, v):\n r\"\"\"Set :math:`v`.\"\"\"\n self._cache_K.clear()\n self._cache_diagK.clear()\n self._cache_update.clear()\n self._cache_lml_components.clear()\n self._cache_L.clear()\n self._cache_A.clear()\n self._cache_C.clear()\n self._cache_BiQt.clear()\n self._cache_QBiQtAm.clear()\n self._cache_QBiQtCteta.clear()\n if v < 0:\n raise ValueError(\"v should not be %f.\" % v)\n self._v = max(v, epsilon.small)\n\n @property\n def _tbeta(self):\n return self.__tbeta\n\n @_tbeta.setter\n def _tbeta(self, value):\n self._cache_lml_components.clear()\n self._cache_QBiQtAm.clear()\n self._cache_m.clear()\n self._cache_update.clear()\n if not is_all_finite(value):\n raise ValueError(\"tbeta should not be %s.\" % str(value))\n if self.__tbeta is None:\n self.__tbeta = asarray(value, float).copy()\n else:\n self.__tbeta[:] = value\n\n @property\n def beta(self):\n r\"\"\"Returns :math:`\\boldsymbol\\beta`.\"\"\"\n return solve(self._svd_V.T, self._tbeta / self._svd_S12)\n\n @beta.setter\n def beta(self, value):\n if not is_all_finite(value):\n raise ValueError(\"beta should not be %s.\" % str(value))\n self._tbeta = self._svd_S12 * dot(self._svd_V.T, value)\n\n @property\n def M(self):\n r\"\"\"Returns :math:`\\mathrm M`.\"\"\"\n return self._M\n\n @M.setter\n def M(self, value):\n self._covariate_setup(value)\n self._cache_m.clear()\n self._cache_QBiQtAm.clear()\n self._cache_update.clear()\n self._cache_lml_components.clear()\n\n @cachedmethod(attrgetter('_cache_lml_components'))\n def _lml_components(self):\n self._update()\n\n S = self._S\n m = self.m()\n ttau = self._sitelik_tau\n teta = self._sitelik_eta\n ctau = self._cav_tau\n ceta = self._cav_eta\n tctau = ttau + ctau\n A = self._A()\n C = self._C()\n L = self._L()\n Am = A * m\n\n QBiQtCteta = self._QBiQtCteta()\n QBiQtAm = self._QBiQtAm()\n\n gS = self.sigma2_b * S\n eC = self.sigma2_epsilon * C\n\n w1 = -sum(log(diagonal(L))) + (-sum(log(gS)) / 2 + log(A).sum() / 2)\n\n w2 = eC * teta\n w2 += C * QBiQtCteta\n w2 -= teta / tctau\n w2 = dot(teta, w2) / 2\n\n w3 = dot(ceta, (ttau * ceta - 2 * teta * ctau) / (ctau * tctau)) / 2\n\n w4 = dot(m * C, teta) - dot(Am, QBiQtCteta)\n\n w5 = -dot(Am, m) / 2 + dot(Am, QBiQtAm) / 2\n\n w6 = -sum(log(ttau)) + sum(log(tctau)) - sum(log(ctau))\n w6 /= 2\n\n w7 = sum(self._loghz)\n\n return (w1, w2, w3, w4, w5, w6, w7)\n\n def lml(self, fast=False):\n if fast:\n return self._normal_lml()\n else:\n v = fsum(self._lml_components())\n if not isfinite(v):\n raise ValueError(\"LML should not be %f.\" % v)\n return fsum(self._lml_components())\n\n def _normal_lml(self):\n self._update()\n\n m = self.m()\n ttau = self._sitelik_tau\n teta = self._sitelik_eta\n\n # NEW PHENOTYPE\n y = teta.copy()\n\n # NEW MEAN\n m = ttau * m\n\n # NEW COVARIANCE\n K = self.K()\n K = ddot(ttau, ddot(K, ttau, left=False), left=True)\n sum2diag(K, ttau, out=K)\n (Q, S0) = economic_qs(K)\n Q0, Q1 = Q\n\n from ...lmm import FastLMM\n from numpy import newaxis\n\n fastlmm = FastLMM(y, Q0, Q1, S0, covariates=m[:, newaxis])\n fastlmm.learn(progress=False)\n return fastlmm.lml()\n\n def _gradient_over_v(self):\n self._update()\n\n A = self._A()\n Q = self._Q\n S = self._S\n C = self._C()\n m = self.m()\n delta = self.delta\n v = self.v\n teta = self._sitelik_eta\n\n AQ = ddot(A, Q, left=True)\n SQt = ddot(S, Q.T, left=True)\n\n Am = A * m\n Em = Am - A * self._QBiQtAm()\n\n Cteta = C * teta\n Eu = Cteta - A * self._QBiQtCteta()\n\n u = Em - Eu\n\n uBiQtAK0, uBiQtAK1 = self._uBiQtAK()\n\n out = dot(u, self._Kdot(u))\n out /= v\n out -= (1 - delta) * trace2(AQ, SQt)\n out -= delta * A.sum()\n out += (1 - delta) * trace2(AQ, uBiQtAK0)\n out += delta * trace2(AQ, uBiQtAK1)\n out /= 2\n return out\n\n def _gradient_over_delta(self):\n self._update()\n\n v = self.v\n delta = self.delta\n Q = self._Q\n S = self._S\n\n A = self._A()\n C = self._C()\n m = self.m()\n teta = self._sitelik_eta\n\n Am = A * m\n Em = Am - A * self._QBiQtAm()\n\n Cteta = C * teta\n Eu = Cteta - A * self._QBiQtCteta()\n\n u = Em - Eu\n\n AQ = ddot(A, Q, left=True)\n SQt = ddot(S, Q.T, left=True)\n\n BiQt = self._BiQt()\n\n uBiQtAK0, uBiQtAK1 = self._uBiQtAK()\n\n out = -trace2(AQ, uBiQtAK0)\n out -= (delta / (1 - delta)) * trace2(AQ, uBiQtAK1)\n out += trace2(AQ, ddot(BiQt, A, left=False)) * \\\n ((delta / (1 - delta)) + 1)\n out += (1 + delta / (1 - delta)) * dot(u, u)\n out += trace2(AQ, SQt) + (delta / (1 - delta)) * A.sum()\n out -= (1 + delta / (1 - delta)) * A.sum()\n\n out *= v\n\n out -= dot(u, self._Kdot(u)) / (1 - delta)\n\n return out / 2\n\n def _gradient_over_both(self):\n self._update()\n\n v = self.v\n delta = self.delta\n Q = self._Q\n S = self._S\n A = self._A()\n AQ = ddot(A, Q, left=True)\n SQt = ddot(S, Q.T, left=True)\n BiQt = self._BiQt()\n uBiQtAK0, uBiQtAK1 = self._uBiQtAK()\n\n C = self._C()\n m = self.m()\n teta = self._sitelik_eta\n Q = self._Q\n As = A.sum()\n\n Am = A * m\n Em = Am - A * self._QBiQtAm()\n\n Cteta = C * teta\n Eu = Cteta - A * self._QBiQtCteta()\n\n u = Em - Eu\n uKu = dot(u, self._Kdot(u))\n tr1 = trace2(AQ, uBiQtAK0)\n tr2 = trace2(AQ, uBiQtAK1)\n\n dv = uKu / v\n dv -= (1 - delta) * trace2(AQ, SQt)\n dv -= delta * As\n dv += (1 - delta) * tr1\n dv += delta * tr2\n dv /= 2\n\n dd = delta / (1 - delta)\n ddelta = -tr1\n ddelta -= dd * tr2\n ddelta += trace2(AQ, ddot(BiQt, A, left=False)) * (dd + 1)\n ddelta += (dd + 1) * dot(u, u)\n ddelta += trace2(AQ, SQt)\n ddelta -= As\n ddelta *= v\n ddelta -= uKu / (1 - delta)\n ddelta /= 2\n\n v = asarray([dv, ddelta])\n\n if not is_all_finite(v):\n raise ValueError(\"LML gradient should not be %s.\" % str(v))\n\n return v\n\n @cachedmethod(attrgetter('_cache_update'))\n def _update(self):\n self._init_ep_params()\n\n self._logger.debug('EP loop has started.')\n\n pttau = self._previous_sitelik_tau\n pteta = self._previous_sitelik_eta\n\n ttau = self._sitelik_tau\n teta = self._sitelik_eta\n\n jtau = self._joint_tau\n jeta = self._joint_eta\n\n ctau = self._cav_tau\n ceta = self._cav_eta\n\n i = 0\n while i < MAX_EP_ITER:\n pttau[:] = ttau\n pteta[:] = teta\n\n ctau[:] = jtau - ttau\n ceta[:] = jeta - teta\n self._tilted_params()\n\n if not all(isfinite(self._hvar)) or any(self._hvar == 0.):\n raise Exception('Error: not all(isfinite(hsig2))' +\n ' or any(hsig2 == 0.).')\n\n self._sitelik_update()\n self._cache_lml_components.clear()\n self._cache_L.clear()\n self._cache_A.clear()\n self._cache_C.clear()\n self._cache_BiQt.clear()\n self._cache_QBiQtAm.clear()\n self._cache_QBiQtCteta.clear()\n\n self._joint_update()\n\n tdiff = abs(pttau - ttau)\n ediff = abs(pteta - teta)\n aerr = tdiff.max() + ediff.max()\n\n if pttau.min() <= 0. or (0. in pteta):\n rerr = inf\n else:\n rtdiff = tdiff / abs(pttau)\n rediff = ediff / abs(pteta)\n rerr = rtdiff.max() + rediff.max()\n\n i += 1\n if aerr < 2 * EP_EPS or rerr < 2 * EP_EPS:\n break\n\n if i + 1 == MAX_EP_ITER:\n self._logger.warning('Maximum number of EP iterations has' +\n ' been attained.')\n\n self._logger.debug('EP loop has performed %d iterations.', i)\n\n def _joint_update(self):\n A = self._A()\n C = self._C()\n m = self.m()\n Q = self._Q\n v = self.v\n delta = self.delta\n teta = self._sitelik_eta\n jtau = self._joint_tau\n jeta = self._joint_eta\n Kteta = self._Kdot(teta)\n\n BiQt = self._BiQt()\n uBiQtAK0, uBiQtAK1 = self._uBiQtAK()\n\n jtau[:] = -dotd(Q, uBiQtAK0)\n jtau *= 1 - delta\n jtau -= delta * dotd(Q, uBiQtAK1)\n jtau *= v\n jtau += self._diagK()\n\n jtau[:] = 1 / jtau\n\n dot(Q, dot(BiQt, -A * Kteta), out=jeta)\n jeta += Kteta\n jeta += m\n jeta -= self._QBiQtAm()\n jeta *= jtau\n jtau /= C\n\n def _sitelik_update(self):\n hmu = self._hmu\n hvar = self._hvar\n tau = self._cav_tau\n eta = self._cav_eta\n self._sitelik_tau[:] = clip(1.0 / hvar - tau, epsilon.tiny, 1/epsilon.small)\n self._sitelik_eta[:] = hmu / hvar - eta\n\n def _optimal_beta_nom(self):\n A = self._A()\n C = self._C()\n teta = self._sitelik_eta\n Cteta = C * teta\n v = Cteta - A * self._QBiQtCteta()\n if not is_all_finite(v):\n raise ValueError(\"beta_nom should not be %s.\" % str(v))\n return v\n\n def _optimal_tbeta_denom(self):\n L = self._L()\n Q = self._Q\n AM = ddot(self._A(), self._tM, left=True)\n QBiQtAM = dot(Q, cho_solve(L, dot(Q.T, AM)))\n v = dot(self._tM.T, AM) - dot(AM.T, QBiQtAM)\n if not is_all_finite(v):\n raise ValueError(\"tbeta_denom should not be %s.\" % str(v))\n return v\n\n def _optimal_tbeta(self):\n self._update()\n\n if all(abs(self._M) < 1e-15):\n return zeros_like(self._tbeta)\n\n u = dot(self._tM.T, self._optimal_beta_nom())\n Z = self._optimal_tbeta_denom()\n\n try:\n with errstate(all='raise'):\n self._tbeta = solve(Z, u)\n\n except (LinAlgError, FloatingPointError):\n self._logger.warning('Failed to compute the optimal beta.' +\n ' Zeroing it.')\n self.__tbeta[:] = 0.\n\n return self.__tbeta\n\n def _optimize_beta(self):\n ptbeta = empty_like(self._tbeta)\n\n step = inf\n i = 0\n alpha = 1.0\n maxiter = 30\n while step > epsilon.small and i < maxiter:\n ptbeta[:] = self._tbeta\n self._optimal_tbeta()\n self._tbeta = clip(alpha * (self._tbeta - ptbeta) + ptbeta,\n -10, +10)\n nstep = sum((self._tbeta - ptbeta)**2)\n\n if nstep > step:\n alpha /= 10\n step = nstep\n\n i += 1\n\n if i == maxiter:\n self._logger.warning('Maximum number of beta iterations has' +\n ' been attained.')\n\n @property\n def bounds(self):\n bounds = dict(v=(1e-3, 1/epsilon.large),\n delta=(0, 1 - epsilon.small))\n return bounds\n\n def _start_optimizer(self):\n bound = self.bounds\n x0 = [self.v]\n bounds = [bound['v']]\n\n if self._overdispersion:\n klass = FunCostOverdispersion\n x0 += [self.delta]\n bounds += [bound['delta']]\n else:\n klass = FunCost\n\n return (klass, x0, bounds)\n\n def _finish_optimizer(self, x):\n self.v = x[0]\n if self._overdispersion:\n self.delta = x[1]\n\n self._optimize_beta()\n\n def learn(self, progress=True):\n self._logger.debug(\"Start of optimization.\")\n progress = tqdm(desc='EP', disable=not progress)\n\n (klass, x0, bounds) = self._start_optimizer()\n\n start = time()\n with progress as pbar:\n func = klass(self, pbar)\n x = fmin_tnc(func, x0, bounds=bounds, **_magic_numbers)[0]\n\n self._finish_optimizer(x)\n\n msg = \"End of optimization (%.3f seconds, %d function calls).\"\n self._logger.debug(msg, time() - start, func.nfev)\n\n @cachedmethod(attrgetter('_cache_A'))\n def _A(self):\n r\"\"\"Returns :math:`\\mathcal A = \\tilde{\\mathrm T} \\mathcal C^{-1}`.\"\"\"\n ttau = self._sitelik_tau\n s2 = self.sigma2_epsilon\n return ttau / (ttau * s2 + 1)\n\n @cachedmethod(attrgetter('_cache_C'))\n def _C(self):\n r\"\"\"Returns :math:`\\mathcal C = \\sigma_{\\epsilon}^2 \\tilde{\\mathrm T} +\n \\mathrm I`.\"\"\"\n ttau = self._sitelik_tau\n s2 = self.sigma2_epsilon\n return 1 / (ttau * s2 + 1)\n\n @cachedmethod(attrgetter('_cache_SQt'))\n def _SQt(self):\n r\"\"\"Returns :math:`\\mathrm S \\mathrm Q^\\intercal`.\"\"\"\n return ddot(self._S, self._Q.T, left=True)\n\n def _QSQt(self):\n r\"\"\"Returns :math:`\\mathrm Q \\mathrm S \\mathrm Q^\\intercal`.\"\"\"\n if self.__QSQt is None:\n Q = self._Q\n self.__QSQt = dot(Q, self._SQt())\n return self.__QSQt\n\n @cachedmethod(attrgetter('_cache_BiQt'))\n def _BiQt(self):\n Q = self._Q\n return cho_solve(self._L(), Q.T)\n\n @cachedmethod(attrgetter('_cache_L'))\n def _L(self):\n r\"\"\"Returns the Cholesky factorization of :math:`\\mathcal B`.\n\n .. math::\n\n \\mathcal B = \\mathrm Q^{\\intercal}\\mathcal A\\mathrm Q\n (\\sigma_b^2 \\mathrm S)^{-1}\n \"\"\"\n Q = self._Q\n A = self._A()\n B = dot(Q.T, ddot(A, Q, left=True))\n sum2diag(B, 1. / (self.sigma2_b * self._S), out=B)\n return cho_factor(B, lower=True)[0]\n\n @cachedmethod(attrgetter('_cache_QBiQtCteta'))\n def _QBiQtCteta(self):\n Q = self._Q\n L = self._L()\n C = self._C()\n teta = self._sitelik_eta\n return dot(Q, cho_solve(L, dot(Q.T, C * teta)))\n\n @cachedmethod(attrgetter('_cache_QBiQtAm'))\n def _QBiQtAm(self):\n Q = self._Q\n L = self._L()\n A = self._A()\n m = self.m()\n\n return dot(Q, cho_solve(L, dot(Q.T, A * m)))\n\n def _uBiQtAK(self):\n BiQt = self._BiQt()\n S = self._S\n Q = self._Q\n BiQtA = ddot(BiQt, self._A(), left=False)\n BiQtAQS = dot(BiQtA, Q)\n ddot(BiQtAQS, S, left=False, out=BiQtAQS)\n\n return dot(BiQtAQS, Q.T), BiQtA\n\n def covariance(self):\n K = self.K()\n return sum2diag(K, 1/self._sitelik_tau)\n\n def get_normal_likelihood_trick(self):\n # Covariance: nK = K + \\tilde\\Sigma = K + 1/self._sitelik_tau\n # via (K + 1/self._sitelik_tau)^{-1} = A1 - A1QB1^-1QTA1\n # Mean: \\mathbf m\n # New phenotype: \\tilde\\mu\n #\n # I.e.: \\tilde\\mu \\sim N(\\mathbf m, K + \\tilde\\Sigma)\n #\n #\n # We transform the above Normal in an equivalent but more robust\n # one: \\tilde\\y \\sim N(\\tilde\\m, \\tilde\\nK + \\Sigma^{-1})\n #\n # \\tilde\\y = \\tilde\\Sigma^{-1} \\tilde\\mu\n # \\tilde\\m = \\tilde\\Sigma^{-1} \\tilde\\m\n # \\tilde\\nK = \\tilde\\Sigma^{-1} \\nK \\tilde\\Sigma^{-1}\n\n m = self.m()\n ttau = self._sitelik_tau\n teta = self._sitelik_eta\n\n # NEW PHENOTYPE\n y = teta.copy()\n\n # NEW MEAN\n m = ttau * m\n\n # NEW COVARIANCE\n K = self.K()\n K = ddot(ttau, ddot(K, ttau, left=False), left=True)\n sum2diag(K, ttau, out=K)\n (Q, S0) = economic_qs(K)\n Q0, Q1 = Q\n\n from ...lmm import FastLMM\n from numpy import newaxis\n\n fastlmm = FastLMM(y, Q0, Q1, S0, covariates=m[:, newaxis])\n fastlmm.learn(progress=False)\n return fastlmm.get_normal_likelihood_trick()\n\n def _paolo(self):\n tK = self.covariance()\n tmu = self._sitelik_eta / self._sitelik_tau\n tS = 1 / self._sitelik_tau\n sigg2 = self.sigma2_b\n sige2 = self.sigma2_epsilon\n return dict(tK=tK, tmu=tmu, tS=tS, sigg2=sigg2, sige2=sige2)\n\nclass FunCostOverdispersion(object):\n def __init__(self, ep, pbar):\n super(FunCostOverdispersion, self).__init__()\n self._ep = ep\n self._pbar = pbar\n self.nfev = 0\n\n def __call__(self, x):\n self._ep.v = x[0]\n self._ep.delta = x[1]\n self._ep._optimize_beta()\n self._pbar.update()\n self.nfev += 1\n nlml = -self._ep.lml()\n ngrad = -self._ep._gradient_over_both()\n return (nlml, ngrad)\n\n\nclass FunCost(object):\n def __init__(self, ep, pbar):\n super(FunCost, self).__init__()\n self._ep = ep\n self._pbar = pbar\n self.nfev = 0\n\n def __call__(self, x):\n self._ep.v = x[0]\n self._ep._optimize_beta()\n self._pbar.update()\n self.nfev += 1\n return (-self._ep.lml(), -self._ep._gradient_over_v())\n","sub_path":"limix_inference/glmm/_ep/_ep.py","file_name":"_ep.py","file_ext":"py","file_size_in_byte":29957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"69940555","text":"import re\nfrom bs4 import BeautifulSoup # 파싱을 편리하게 해주는 라이브러리\nfrom urllib.request import urlopen\n\nsinger_name=\"ADOY\"\ntarget_melon_url = \"https://ticket.melon.com/search/index.htm?q=\"+ singer_name\ntarget_interpark_url=\"http://isearch.interpark.com/isearch?q=\"+ singer_name #This contains ticket URL\ntarget_interpark_ticket_url= \"http://ticket.interpark.com/search/ticket.asp?search=%uC544%uB3C4%uC774\" #This is the target url\n\n\nartist_number=698776\nartist_id=str(artist_number)\nmelon_ticket_url=\"https://ticket.melon.com/artist/index.htm?artistId=\"+artist_id\n\nhtml=urlopen(melon_ticket_url)\nsoup = BeautifulSoup(html, 'lxml')\ntype(soup)\nprint(soup)\ndummy = soup.find_all('div',{'class':{'show_infor'}})\nprint(dummy)\n\n#on_sale = soup.find_all('div',{'class':{'result_Ticket'}})\n#print(on_sale)\n#target_interpark_url 백예린 Ticket search result\n#레인보우 뮤직&캠핑 페스티벌 2019\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"358174375","text":"from ops_alex import *\nfrom ops_coordconv import *\n\nclass Deep_PatchGAN_Discrminator(object):\n\n def __init__(self, hidden_activation=tf.nn.leaky_relu, normalizer_fn=tf.contrib.layers.batch_norm, addCoordConv=False, isTraining=True, flags=None):\n self.hidden_activation = hidden_activation\n self.flags = flags\n self.normalizer_fn = normalizer_fn\n self.addCoordConv = addCoordConv\n self.isTraining = isTraining\n\n def __call__(self, x, **kwargs):\n df_dim = 42\n\n if self.addCoordConv:\n h0 = tf.nn.leaky_relu(conv2d(coord_conv(x), df_dim, k_h=4, k_w=4, d_h=2, d_w=2, use_spectral_norm=False, name='d_1_h0_conv')) # 42\n\n h1 = tf.nn.leaky_relu(conv2d(coord_conv(h0), df_dim * 2, k_h=4, k_w=4, d_h=2, d_w=2, use_spectral_norm=True, name='d_1_h1_conv')) # 84\n\n h2 = tf.nn.leaky_relu(conv2d(coord_conv(h1), df_dim * 4, k_h=4, k_w=4, d_h=2, d_w=2, use_spectral_norm=True, name='d_1_h2_conv')) # 168\n\n h3 = tf.nn.leaky_relu(conv2d(coord_conv(h2), df_dim * 8, k_h=4, k_w=4, d_h=2, d_w=2, use_spectral_norm=True, name='d_1_h3_conv')) # 336\n\n h4 = h3\n # h4 = tf.nn.leaky_relu(conv2d(coord_conv(h3), df_dim * 8, k_h=4, k_w=4, d_h=2, d_w=2, use_spectral_norm=True, name='d_1_h4_conv')) # 336\n\n else:\n h0 = tf.nn.leaky_relu(conv2d(x, df_dim * 1, k_h=4, k_w=4, d_h=2, d_w=2, use_spectral_norm=False, name='d_1_h0_conv'))\n\n h1 = tf.nn.leaky_relu(conv2d(h0, df_dim * 2, k_h=4, k_w=4, d_h=2, d_w=2, use_spectral_norm=True, name='d_1_h1_conv'))\n\n h2 = tf.nn.leaky_relu(conv2d(h1, df_dim * 4, k_h=4, k_w=4, d_h=2, d_w=2, use_spectral_norm=True, name='d_1_h2_conv'))\n\n h3 = tf.nn.leaky_relu(conv2d(h2, df_dim * 8, k_h=4, k_w=4, d_h=2, d_w=2, use_spectral_norm=True, name='d_1_h3_conv'))\n\n h4 = h3\n # h4 = tf.nn.leaky_relu(conv2d(h3, df_dim * 8, k_h=4, k_w=4, d_h=2, d_w=2, use_spectral_norm=True, name='d_1_h4_conv'))\n\n\n h5 = conv2d(h4, 1, k_h=1, k_w=1, d_h=1, d_w=1, use_spectral_norm=False, name='d_1_h5_conv')\n\n return h4, h5\n\n # with tf.variable_scope(scope, reuse=tf.AUTO_REUSE) as _:\n # h0 = tf.contrib.layers.conv2d(inputs=x,\n # activation_fn=self.hidden_activation,\n # num_outputs=df_dim,\n # kernel_size=4,\n # stride=2,\n # normalizer_fn=None)\n #\n # h1 = tf.contrib.layers.conv2d(inputs=h0,\n # activation_fn=self.hidden_activation,\n # num_outputs=df_dim * 2,\n # kernel_size=4,\n # stride=2,\n # normalizer_fn=self.normalizer_fn,\n # normalizer_params={'is_training': self.isTraining})\n #\n # h2 = tf.contrib.layers.conv2d(inputs=h1,\n # activation_fn=self.hidden_activation,\n # num_outputs=df_dim * 4,\n # kernel_size=4,\n # stride=2,\n # normalizer_fn=self.normalizer_fn,\n # normalizer_params={'is_training': self.isTraining})\n #\n # h3 = tf.contrib.layers.conv2d(inputs=h2,\n # activation_fn=self.hidden_activation,\n # num_outputs=df_dim * 8,\n # kernel_size=4,\n # stride=2,\n # normalizer_fn=self.normalizer_fn,\n # normalizer_params={'is_training': self.isTraining})\n #\n # h4 = tf.contrib.layers.conv2d(inputs=h3,\n # activation_fn=self.hidden_activation,\n # num_outputs=df_dim * 16,\n # kernel_size=4,\n # stride=2,\n # normalizer_fn=self.normalizer_fn,\n # normalizer_params={'is_training': self.isTraining})\n #\n # h5 = tf.contrib.layers.conv2d(inputs=h4,\n # activation_fn=None,\n # num_outputs=1,\n # kernel_size=1,\n # stride=1,\n # normalizer_fn=None)\n\n\n \"\"\"\n # average pooling h4 from (8 x 8 x 1) to 1\n h5 = tf.layers.average_pooling2d(inputs=h4, pool_size=h4.get_shape()[1:3], strides=h4.get_shape()[1:3])\n\n output = patch_gan_linear(tf.reshape(h5, [self.flags.blur_batch_size, -1]), 1, scope=scope,\n batch_size=self.flags.blur_batch_size)\n \"\"\"\n\n #return tf.nn.sigmoid(h5), h5\n","sub_path":"src/evaluation/patch_gan_discriminator_linearcls.py","file_name":"patch_gan_discriminator_linearcls.py","file_ext":"py","file_size_in_byte":5188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"157078475","text":"n1=34\nn2=100\nn3=-67\n\nprint('三個整數分別為 {0}, {1}, {2}'.format(n1, n2, n3))\nif (n1>n2) :\t\t #判斷 n1 是否大於 n2\n if(n1>n3) : #判斷 n1 是否大於 n3\n max=n1\n else :\n max=n3\nelse :\t\t\t\t\n if(n2>n3) :\t\t #判斷 n2 是否大於 n3\n max=n2\n else :\n max=n3 \nprint()\nprint('比較結果:最大數為 {0}'.format(max))\n","sub_path":"ex03/max.py","file_name":"max.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"171267034","text":"# -*- coding: utf-8 -*-\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\n\nfrom zcore.views import *\nimport app.settings as settings\n\n\nurlpatterns = [\n url(r'^zcore/', include('zcore.urls', namespace='zcore')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^syscheck/', include('syscheck.urls', namespace='syscheck')),\n]\n\nurlpatterns += [\n url(r'^static/(?P.*)$', 'django.views.static.serve',{'document_root': settings.URL_STATIC_ROOT}),\n\n url(r'^$', 'zcore.views.index', name='index'),\n #url(r'^timeline/(?P[-\\w]+)/$', 'zcore.views.view_timeline', name='viewTimeline'),\n\n url(r'^news/(?P[0-9]+)/$', NewsDetail.as_view()),\n url(r'^news/$', NewsList.as_view()),\n url(r'^forms/(?P[0-9]+)/$', FormsDetail.as_view()),\n url(r'^forms/$', FormsList.as_view()),\n]\n\n\n","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"488489676","text":"from django.urls import path\nfrom django.urls.resolvers import URLPattern\nfrom . import views\n\nurlpatterns = [\n path('man', views.man),\n path('woman', views.woman),\n path('example', views.example),\n path('second', views.second_page),\n path('', views.landing_page),\n]\n","sub_path":"mainapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"360822941","text":"#%%\nfrom utils import *\nfrom models import *\n\n#%%\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation\nimport pandas as pd\nimport numpy as np\nimport math\nimport pandas as pd\n\nfrom keras.layers import LSTM\nfrom sklearn.metrics import mean_squared_error\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n#%%\ninit_df, date = readFile(\"WIG20.csv\");\ndf = normalizeToRatios(init_df)\ndate = pd.to_datetime(date)\n\n#%%\nlayers = 10;\nn_epochs = 50;\n\n#%%\n#plt.plot(date, init_df)\n#plt.show()\n\n#%%\n\ndef predictWithRegression(df = df, look_back = 10, look_in_future = 1):\n trainX, trainY, validationX, validationY, testX, testY = createSets(df, look_back, look_in_future)\n\n model = getPerceptronRegression(layers, look_back);\n model.fit(trainX, trainY, epochs = n_epochs, validation_data=(validationX, validationY));\n prediction = model.predict(testX)\n\n prediction = np.array(flatten(prediction))\n\n accuracy = float(sum(prediction * np.array(testY) > 0)) / len(prediction)\n\n return prediction, accuracy\n\n\n\ndef countAccuracyClassification(df = df, look_back = 10, look_in_future = 1):\n trainX, trainY, validationX, validationY, testX, testY = createSets(df, look_back, look_in_future)\n\n trainY[trainY >= 0] = 1\n trainY[trainY < 0] = 0\n trainY = keras.utils.to_categorical(trainY)\n\n validationY[validationY >= 0] = 1\n validationY[validationY < 0] = 0\n validationY = keras.utils.to_categorical(validationY)\n\n testY[testY >= 0] = 1\n testY[testY < 0] = 0\n testY = keras.utils.to_categorical(testY)\n\n model = getPerceptronClassification(layers, look_back);\n model.fit(trainX, trainY, epochs = n_epochs, validation_data=(validationX, validationY));\n\n prediction = np.argmax(model.predict(testX), axis=1)\n testY = np.argmax(testY, axis=1)\n\n\n results = pd.DataFrame({'prediction': prediction, 'value': testY})\n\n return float(sum(results['prediction'] == results['value']))/len(results)\n\n\n\n\n\n\nlookBacks = [5, 10, 15, 20, 30, 40, 50]\n\n'''\ndflen = len(df)\nsetlen = math.ceil(0.1 * dflen)\n\n\naccuracies = []\nfor i in range(10):\n randStart = np.random.randint(dflen - setlen)\n accuracies.append(countAccuracyClassification(df[randStart: randStart + setlen].reset_index(drop=True), look_back=20))\n'''","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"581004662","text":"import numpy as np\nimport math\nimport itertools\nimport collections\nfrom copy import copy\nimport cv2\nimport seaborn as sns\n\n\nclass DynamicProgramming:\n def __init__(self, map_image, widths, goal, time_interval, sampling_num, value=None,\n nu=0.1, omega=0.5):\n # マップ牙城のy軸を反転\n self.map_image = map_image.T[:, ::-1]\n # ピクセル数\n x_pixel, y_pixel = map_image.shape\n nt = int(math.pi*2/widths[2])\n self.index_nums = np.array([x_pixel, y_pixel, nt])\n self.indexes = list(itertools.product(range(x_pixel), range(y_pixel), range(nt)))\n\n self.pose_min = np.array([0, 0, 0])\n self.pose_max = np.array([x_pixel*widths[0], y_pixel*widths[1], math.pi*2])\n\n self.widths = widths\n self.goal = goal\n\n self.value_function, self.final_state_flags, self.obstacle_state_flags =\\\n self.init_value_function()\n self.policy = self.init_policy()\n self.actions = [(0.0, omega), (nu, 0.0), (0.0, -omega)]\n\n self.state_transition_probs = self.init_state_transition_probs(time_interval, sampling_num)\n\n self.time_interval = time_interval\n\n if value is not None:\n self.value_function = value\n\n def value_iteration_sweep(self):\n max_delta = 0.0\n for index in self.indexes:\n if self.final_state_flags[index]:\n self.value_function[index] = 0.0\n else:\n max_q = -1e100\n qs = [self.action_value(a, index) for a in self.actions]\n max_q = max(qs)\n max_a = self.actions[np.argmax(qs)]\n\n delta = abs(self.value_function[index] - max_q)\n max_delta = delta if delta > max_delta else max_delta\n\n self.value_function[index] = max_q\n self.policy[index] = np.array(max_a).T\n\n return max_delta\n\n def action_value(self, action, index): #はみ出しペナルティー追加\n value_n = 0.0\n reward = 0.0\n for delta, prob in self.state_transition_probs[(action, index[2])]:\n after, edge_reward = self.edge_correction(np.array(index).T + delta)\n after = tuple(after)\n reward += -(self.time_interval\\\n +(self.map_image[after[0], after[1]]<10)*100*self.time_interval\\\n -edge_reward) * prob\n value_n += self.value_function[after] * prob\n\n action_value = value_n + reward\n\n return action_value, value_n, reward\n\n def edge_correction(self, index): #変更\n edge_reward = 0.0\n index[2] = (index[2] + self.index_nums[2])%self.index_nums[2] #方角の処理\n\n for i in range(2):\n if index[i] < 0:\n index[i] = 0\n edge_reward = -1e100\n elif index[i] >= self.index_nums[i]:\n index[i] = self.index_nums[i]-1\n edge_reward = -1e100\n\n return index, edge_reward\n\n def init_policy(self):\n tmp = np.zeros(np.r_[self.index_nums, 2])\n return tmp\n\n def init_state_transition_probs(self, time_interval, sampling_num):\n ###セルの中の座標を均等にsampling_num**3点サンプリング###\n dx = np.linspace(0.00001, self.widths[0]*0.99999, sampling_num)\n dy = np.linspace(0.00001, self.widths[1]*0.99999, sampling_num)\n dt = np.linspace(0.00001, self.widths[2]*0.99999, sampling_num)\n samples = list(itertools.product(dx, dy, dt))\n\n ###各行動、各方角でサンプリングした点を移動��てインデックスの増分を記録###\n tmp = {}\n for a in self.actions:\n for i_t in range(self.index_nums[2]):\n transitions = []\n for s in samples:\n before = np.array([s[0], s[1], s[2] + i_t*self.widths[2]]).T + self.pose_min\n before_index = np.array([0, 0, i_t]).T #遷移前のインデックス\n\n after = self.transition_state(a[0], a[1], time_interval, before)\n after_index = np.floor((after - self.pose_min)/self.widths).astype(int)\n\n transitions.append(after_index - before_index)\n\n unique, count = np.unique(transitions, axis=0, return_counts=True)\n probs = [c/sampling_num**3 for c in count]\n tmp[a, i_t] = list(zip(unique, probs))\n\n return tmp\n\n def init_value_function(self):\n v = np.empty(self.index_nums)\n f = np.zeros(self.index_nums)\n o = np.empty(self.index_nums)\n\n for index in self.indexes:\n f[index] = self.final_state(np.array(index).T)\n o[index] = True if self.map_image[index[0], index[1]] < 255 else False\n v[index] = 0.0 if f[index] else - 1000.0\n\n return v, f, o\n\n def final_state(self, index):\n x_min, y_min, _ = self.pose_min + self.widths*index\n x_max, y_max, _ = self.pose_min + self.widths*(index + 1)\n\n corners = [[x_min, y_min, _], [x_min, y_max, _], [x_max, y_min, _], [x_max, y_max, _] ] #4隅の座標\n return all([self.goal.inside(np.array(c).T) for c in corners ])\n\n def transition_state(self, nu, omega, time, pose):\n t0 = pose[2]\n if math.fabs(omega) < 1e-10:\n return pose + np.array( [nu*math.cos(t0),\n nu*math.sin(t0),\n omega ] ) * time\n else:\n return pose + np.array( [nu/omega*(math.sin(t0 + omega*time) - math.sin(t0)),\n nu/omega*(-math.cos(t0 + omega*time) + math.cos(t0)),\n omega*time ] )\n","sub_path":"modules/dynamic_programming.py","file_name":"dynamic_programming.py","file_ext":"py","file_size_in_byte":5792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"371983557","text":"from django.urls import path\r\nfrom .views import HomePageView, CreatePostView, HomePage2View, HomePage3View, HomePage4View, HomePage1View, HomePage5View, CreatePost1View\r\n\r\nurlpatterns = [\r\n path('', HomePageView.as_view(), name='home'),\r\n path('doctors/', CreatePostView.as_view(), name='add_post'),\r\n path('doctors/', CreatePost1View.as_view(), name='add_post'),\r\n path('services.html/', HomePage2View.as_view(), name='add_post'),\r\n path('news.html/', HomePage3View.as_view(), name='add_post'),\r\n path('contact.html/', HomePage4View.as_view(), name='add_post'),\r\n path('doctors/doctors_diagnosis.html/', HomePage1View.as_view(), name='doctors_diagnosis'),\r\n path('doctors/doctors_todolist.html/', HomePage5View.as_view(), name='doctors_todolist'),\r\n path('doctors/todolist.html/', CreatePost1View.as_view(), name='todolist.html')\r\n]\r\n\r\n","sub_path":"wellnymedicalservices/doctors/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"92868595","text":"#!/usr/bin/env python\n#coding: utf-8\n\nDEBUG = True\n\nPORT = 8080\n\nAPP = '天气预报'\nAPP_CN = ''\nSLOGAN = ''\n\n# HOST = 'http://xrkmedia.com'\n# STATIC_HOST = 'http://static.xrkmedia.com'\n\nHOST_ = 'b.bb:8088'\nHOST = 'http://%s' % HOST_\nSTATIC_HOST = 'http://static.b.bb:8088'\n\nDB = 'weather'\n\nMONGO_CONFIG = dict(\n host = \"mongodb://127.0.0.1:27017\",\n)\n\nREDIS_CONFIG = dict(\n host='127.0.0.1',\n port=6379,\n db=0\n)\n\nclass QINIU(object):\n ACCESS_KEY = 'tZ1uxKB0hRo7bIOlHP0DkYDcNjFYAnW1LqzDsK_A'\n SECRET_KEY = 'v9G34Fy78Z5JRN26l7czcBJM1zNuG8CXgB5h491m'\n BUCKET = 'sunflower-website'\n HOST = 'http://7xk1xj.com1.z0.glb.clouddn.com'\n\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"169847918","text":"import sys\ninput = sys.stdin.readline\n\nn = int(input())\na_lst = list(map(int, input().split()))\nb_lst = [0]*n\n\ndef multiple_i(i, n):\n lst = []\n j = 2\n while(1):\n if i*j <= n:\n lst += [i*j]\n j += 1\n else:\n break\n return lst\n\nfor i in range(1, n+1):\n r = a_lst[-i]\n if not n+1-i > n / 2:\n mul_lst = multiple_i(n+1-i, n)\n ball = 0\n for mul in mul_lst:\n if b_lst[mul - 1] == 1:\n ball += 1\n if not ball % 2 == r:\n b_lst[-i] = 1\n else:\n if r == 1:\n b_lst[-i] = 1\n\nm = 0\nans_lst = []\nfor i in range(n):\n if b_lst[i] == 1:\n m += 1\n ans_lst += [i + 1]\n\nprint(m)\nfor i in range(m):\n print(ans_lst[i], end=\" \")\n","sub_path":"ABC/ABC134/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"384234535","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: D:\\Documents\\GitHub\\luxpy\\luxpy\\color\\cct\\cct.py\n# Compiled at: 2020-02-06 15:50:22\n# Size of source mod 2**32: 36149 bytes\n\"\"\"\ncct: Module with functions related to correlated color temperature calculations\n===============================================================================\n\n :_CCT_LUT_PATH: Folder with Look-Up-Tables (LUT) for correlated color \n temperature calculation followings Ohno's method.\n\n :_CCT_LUT: Dict with LUTs.\n \n :_CCT_LUT_CALC: Boolean determining whether to force LUT calculation, even if\n the LUT can be fuond in ./data/cctluts/.\n\n :calculate_lut(): Function that calculates the LUT for the ccts stored in \n ./data/cctluts/cct_lut_cctlist.dat or given as input \n argument. Calculation is performed for CMF set specified in\n cieobs. Adds a new (temprorary) field to the _CCT_LUT dict.\n\n :calculate_luts(): Function that recalculates (and overwrites) LUTs in \n ./data/cctluts/ for the ccts stored in \n ./data/cctluts/cct_lut_cctlist.dat or given as input \n argument. Calculation is performed for all CMF sets listed \n in _CMF['types'].\n\n :xyz_to_cct(): | Calculates CCT, Duv from XYZ \n | wrapper for xyz_to_cct_ohno() & xyz_to_cct_search()\n\n :xyz_to_duv(): Calculates Duv, (CCT) from XYZ\n wrapper for xyz_to_cct_ohno() & xyz_to_cct_search()\n\n :cct_to_xyz(): Calculates xyz from CCT, Duv [100 K < CCT < 10**20]\n\n :xyz_to_cct_mcamy(): | Calculates CCT from XYZ using Mcamy model:\n | `McCamy, Calvin S. (April 1992). \n Correlated color temperature as an explicit function of \n chromaticity coordinates. \n Color Research & Application. 17 (2): 142–144. \n `_\n\n :xyz_to_cct_HA(): | Calculate CCT from XYZ using Hernández-Andrés et al. model.\n | `Hernández-Andrés, Javier; Lee, RL; Romero, J (September 20, 1999). \n Calculating Correlated Color Temperatures Across the \n Entire Gamut of Daylight and Skylight Chromaticities. \n Applied Optics. 38 (27): 5703–5709. PMID 18324081. \n `_\n\n :xyz_to_cct_ohno(): | Calculates CCT, Duv from XYZ using a LUT following:\n | `Ohno Y. (2014)\n Practical use and calculation of CCT and Duv. \n Leukos. 2014 Jan 2;10(1):47-55.\n `_\n\n :xyz_to_cct_search(): Calculates CCT, Duv from XYZ using brute-force search \n algorithm (between 1e2 K - 1e20 K on a log scale)\n\n :cct_to_mired(): Converts from CCT to Mired scale (or back).\n\n===============================================================================\n\"\"\"\nfrom luxpy import np, pd, _PKG_PATH, _SEP, _EPS, _CMF, _CIEOBS, minimize, np2d, np2dT, getdata, dictkv, spd_to_xyz, cri_ref, blackbody, xyz_to_Yxy, xyz_to_Yuv, Yuv_to_xyz\n_CCT_LUT_CALC = False\n__all__ = ['_CCT_LUT_CALC']\n__all__ += ['_CCT_LUT', '_CCT_LUT_PATH', 'calculate_luts', 'xyz_to_cct', 'xyz_to_duv', 'cct_to_xyz', 'cct_to_mired', 'xyz_to_cct_ohno', 'xyz_to_cct_search', 'xyz_to_cct_HA', 'xyz_to_cct_mcamy']\n_CCT_LUT_PATH = _PKG_PATH + _SEP + 'data' + _SEP + 'cctluts' + _SEP\n_CCT_LUT = {}\n\ndef calculate_lut(ccts=None, cieobs=None, add_to_lut=True):\n \"\"\"\n Function that calculates LUT for the ccts stored in \n ./data/cctluts/cct_lut_cctlist.dat or given as input argument.\n Calculation is performed for CMF set specified in cieobs. \n Adds a new (temprorary) field to the _CCT_LUT dict.\n \n Args:\n :ccts: \n | ndarray or str, optional\n | list of ccts for which to (re-)calculate the LUTs.\n | If str, ccts contains path/filename.dat to list.\n :cieobs: \n | None or str, optional\n | str specifying cmf set.\n \n Returns:\n :returns: \n | ndarray with cct and duv.\n \n Note:\n Function changes the global variable: _CCT_LUT!\n \"\"\"\n if ccts is None:\n ccts = getdata('{}cct_lut_cctlist.dat'.format(_CCT_LUT_PATH))\n else:\n if isinstance(ccts, str):\n ccts = getdata(ccts)\n Yuv = np.ones((ccts.shape[0], 2)) * np.nan\n for i, cct in enumerate(ccts):\n Yuv[i, :] = xyz_to_Yuv(spd_to_xyz(blackbody(cct, wl3=[360, 830, 1]), cieobs=cieobs))[:, 1:3]\n\n u = Yuv[:, 0, None]\n v = 0.6666666666666666 * Yuv[:, 1, None]\n cctuv = np.hstack((ccts, u, v))\n if add_to_lut == True:\n _CCT_LUT[cieobs] = cctuv\n return cctuv\n\n\ndef calculate_luts(ccts=None):\n \"\"\"\n Function that recalculates (and overwrites) LUTs in ./data/cctluts/ \n for the ccts stored in ./data/cctluts/cct_lut_cctlist.dat or given as \n input argument. Calculation is performed for all CMF sets listed \n in _CMF['types'].\n \n Args:\n :ccts: \n | ndarray or str, optional\n | List of ccts for which to (re-)calculate the LUTs.\n | If str, ccts contains path/filename.dat to list.\n \n Returns:\n | None\n \n Note:\n Function writes LUTs to ./data/cctluts/ folder!\n \"\"\"\n for ii, cieobs in enumerate(sorted(_CMF['types'])):\n print('Calculating CCT LUT for CMF set: {}'.format(cieobs))\n cctuv = calculate_lut(ccts=ccts, cieobs=cieobs, add_to_lut=False)\n pd.DataFrame(cctuv).to_csv(('{}cct_lut_{}.dat'.format(_CCT_LUT_PATH, cieobs)), header=None, index=None, float_format='%1.9e')\n\n\nif _CCT_LUT_CALC == True:\n calculate_luts()\ntry:\n _CCT_LUT = dictkv(keys=(sorted(_CMF['types'])), values=[getdata(('{}cct_lut_{}.dat'.format(_CCT_LUT_PATH, sorted(_CMF['types'])[i])), kind='np') for i in range(len(_CMF['types']))], ordered=False)\nexcept:\n calculate_luts()\n _CCT_LUT = dictkv(keys=(sorted(_CMF['types'])), values=[getdata(('{}cct_lut_{}.dat'.format(_CCT_LUT_PATH, sorted(_CMF['types'])[i])), kind='np') for i in range(len(_CMF['types']))], ordered=False)\n\ndef xyz_to_cct_mcamy(xyzw):\n \"\"\"\n Convert XYZ tristimulus values to correlated color temperature (CCT) using \n the mccamy approximation.\n \n | Only valid for approx. 3000 < T < 9000, if < 6500, error < 2 K.\n \n Args:\n :xyzw: \n | ndarray of tristimulus values\n \n Returns:\n :cct: \n | ndarray of correlated color temperatures estimates\n \n References:\n 1. `McCamy, Calvin S. (April 1992). \n \"Correlated color temperature as an explicit function of \n chromaticity coordinates\".\n Color Research & Application. 17 (2): 142–144.\n `_\n \"\"\"\n Yxy = xyz_to_Yxy(xyzw)\n n = (Yxy[:, 1] - 0.332) / (Yxy[:, 2] - 0.1858)\n return np2d(-449.0 * n ** 3 + 3525.0 * n ** 2 - 6823.3 * n + 5520.33).T\n\n\ndef xyz_to_cct_HA(xyzw):\n \"\"\"\n Convert XYZ tristimulus values to correlated color temperature (CCT). \n \n Args:\n :xyzw: \n | ndarray of tristimulus values\n \n Returns:\n :cct: \n | ndarray of correlated color temperatures estimates\n \n References:\n 1. `Hernández-Andrés, Javier; Lee, RL; Romero, J (September 20, 1999). \n Calculating Correlated Color Temperatures Across the Entire Gamut \n of Daylight and Skylight Chromaticities.\n Applied Optics. 38 (27), 5703–5709. P\n `_\n \n Notes: \n According to paper small error from 3000 - 800 000 K, but a test with \n Planckians showed errors up to 20% around 500 000 K; \n e>0.05 for T>200 000, e>0.1 for T>300 000, ...\n \"\"\"\n if len(xyzw.shape) > 2:\n raise Exception('xyz_to_cct_HA(): Input xyzw.ndim must be <= 2 !')\n out_of_range_code = np.nan\n xe = [0.3366, 0.3356]\n ye = [0.1735, 0.1691]\n A0 = [-949.86315, 36284.48953]\n A1 = [6253.80338, 0.00228]\n t1 = [0.92159, 0.07861]\n A2 = [28.70599, 5.4535e-36]\n t2 = [0.20039, 0.01543]\n A3 = [4e-05, 0.0]\n t3 = [0.07125, 1.0]\n cct_ranges = np.array([[3000.0, 50000.0], [50000.0, 800000.0]])\n Yxy = xyz_to_Yxy(xyzw)\n CCT = np.ones((1, Yxy.shape[0])) * out_of_range_code\n for i in range(2):\n n = (Yxy[:, 1] - xe[i]) / (Yxy[:, 2] - ye[i])\n CCT_i = np2d(np.array(A0[i] + A1[i] * np.exp(np.divide(-n, t1[i])) + A2[i] * np.exp(np.divide(-n, t2[i])) + A3[i] * np.exp(np.divide(-n, t3[i]))))\n p = (CCT_i >= (1.0 - 0.05 * (i == 0)) * cct_ranges[i][0]) & (CCT_i < (1.0 + 0.05 * (i == 0)) * cct_ranges[i][1])\n CCT[p] = CCT_i[p]\n p = CCT_i < 0.95 * cct_ranges[0][0]\n CCT[p] = -1\n\n if (np.isnan(CCT.sum()) == True) | np.any(CCT == -1):\n print(\"Warning: xyz_to_cct_HA(): one or more CCTs out of range! --> (CCT < 3 kK, CCT >800 kK) coded as (-1, NaN) 's\")\n return CCT.T\n\n\ndef xyz_to_cct_search(xyzw, cieobs=_CIEOBS, out='cct', wl=None, accuracy=0.1, upper_cct_max=1e+20, approx_cct_temp=True):\n \"\"\"\n Convert XYZ tristimulus values to correlated color temperature (CCT) and \n Duv(distance above (> 0) or below ( < 0) the Planckian locus) by a \n brute-force search. \n\n | The algorithm uses an approximate cct_temp (HA approx., see xyz_to_cct_HA) \n as starting point or uses the middle of the allowed cct-range \n (1e2 K - 1e20 K, higher causes overflow) on a log-scale, then constructs \n a 4-step section of the blackbody (Planckian) locus on which to find the\n minimum distance to the 1960 uv chromaticity of the test source.\n\n Args:\n :xyzw: \n | ndarray of tristimulus values\n :cieobs: \n | luxpy._CIEOBS, optional\n | CMF set used to calculated xyzw.\n :out: \n | 'cct' (or 1), optional\n | Determines what to return.\n | Other options: 'duv' (or -1), 'cct,duv'(or 2), \"[cct,duv]\" (or -2)\n :wl: \n | None, optional\n | Wavelengths used when calculating Planckian radiators.\n :accuracy: \n | float, optional\n | Stop brute-force search when cct :accuracy: is reached.\n :upper_cct_max: \n | 10.0**20, optional\n | Limit brute-force search to this cct.\n :approx_cct_temp: \n | True, optional\n | If True: use xyz_to_cct_HA() to get a first estimate of cct to \n speed up search.\n\n Returns:\n :returns: \n | ndarray with:\n | cct: out == 'cct' (or 1)\n | duv: out == 'duv' (or -1)\n | cct, duv: out == 'cct,duv' (or 2)\n | [cct,duv]: out == \"[cct,duv]\" (or -2) \n \n Notes:\n This program is more accurate, but slower than xyz_to_cct_ohno!\n Note that cct must be between 1e3 K - 1e20 K \n (very large cct take a long time!!!)\n \"\"\"\n xyzw = np2d(xyzw)\n if len(xyzw.shape) > 2:\n raise Exception('xyz_to_cct_search(): Input xyzw.shape must be <= 2 !')\n else:\n Yuvt = xyz_to_Yuv(np.squeeze(xyzw))\n ut = Yuvt[:, 1, None]\n vt = 0.6666666666666666 * Yuvt[:, 2, None]\n ccts = np.ones((xyzw.shape[0], 1)) * np.nan\n duvs = ccts.copy()\n if approx_cct_temp == True:\n ccts_est = xyz_to_cct_HA(xyzw)\n procent_estimates = np.array([[3000.0, 100000.0, 0.05], [100000.0, 200000.0, 0.1], [200000.0, 300000.0, 0.25], [300000.0, 400000.0, 0.4], [400000.0, 600000.0, 0.4], [600000.0, 800000.0, 0.4], [800000.0, np.inf, 0.25]])\n else:\n upper_cct = np.array(upper_cct_max)\n lower_cct = np.array(100.0)\n cct_scale_fun = lambda x: np.log10(x)\n cct_scale_ifun = lambda x: np.power(10.0, x)\n dT = (cct_scale_fun(upper_cct) - cct_scale_fun(lower_cct)) / 2\n ccttemp = np.array([cct_scale_ifun(cct_scale_fun(lower_cct) + dT)])\n ccts_est = np2d(ccttemp * np.ones((xyzw.shape[0], 1)))\n dT_approx_cct_False = dT.copy()\n for i in range(xyzw.shape[0]):\n cct = np.nan\n duv = np.nan\n ccttemp = ccts_est[i].copy()\n approx_cct_temp_temp = approx_cct_temp\n if approx_cct_temp == True:\n cct_scale_fun = lambda x: x\n cct_scale_ifun = lambda x: x\n if (ccttemp != -1) & (np.isnan(ccttemp) == False):\n for ii in range(procent_estimates.shape[0]):\n if (ccttemp >= (1.0 - 0.05 * (ii == 0)) * procent_estimates[(ii, 0)]) & (ccttemp < (1.0 + 0.05 * (ii == 0)) * procent_estimates[(ii, 1)]):\n procent_estimate = procent_estimates[(ii, 2)]\n break\n\n dT = np.multiply(ccttemp, procent_estimate)\n else:\n if (ccttemp == -1) & (np.isnan(ccttemp) == False):\n ccttemp = np.array([procent_estimates[(0, 0)] / 2])\n procent_estimate = 1\n dT = np.multiply(ccttemp, procent_estimate)\n else:\n if np.isnan(ccttemp) == True:\n upper_cct = np.array(upper_cct_max)\n lower_cct = np.array(100.0)\n cct_scale_fun = lambda x: np.log10(x)\n cct_scale_ifun = lambda x: np.power(10.0, x)\n dT = (cct_scale_fun(upper_cct) - cct_scale_fun(lower_cct)) / 2\n ccttemp = np.array([cct_scale_ifun(cct_scale_fun(lower_cct) + dT)])\n approx_cct_temp = False\n else:\n dT = dT_approx_cct_False\n nsteps = 3\n signduv = 1.0\n ccttemp = ccttemp[0]\n delta_cct = dT\n while delta_cct > accuracy:\n ccts_i = cct_scale_ifun(np.linspace(cct_scale_fun(ccttemp) - dT, cct_scale_fun(ccttemp) + dT, nsteps + 1))\n ccts_i[ccts_i < 100.0] = 100.0\n BB = cri_ref(ccts_i, wl3=wl, ref_type=['BB'], cieobs=cieobs)\n xyz = spd_to_xyz(BB, cieobs=cieobs)\n Yuv = xyz_to_Yuv(np.squeeze(xyz))\n u = Yuv[:, 1, None]\n v = 0.6666666666666666 * Yuv[:, 2, None]\n dc = ((ut[i] - u) ** 2 + (vt[i] - v) ** 2) ** 0.5\n if np.isnan(dc.min()) == False:\n q = dc.argmin()\n if np.size(q) > 1:\n cct = np.median(ccts[q])\n duv = np.median(dc[q])\n q = np.median(q)\n q = int(q)\n else:\n cct = ccts_i[q]\n duv = dc[q]\n if q == 0:\n ccttemp = cct_scale_ifun(np.array(cct_scale_fun([cct])) + 2 * dT / nsteps)\n continue\n if q == np.size(ccts_i):\n ccttemp = cct_scale_ifun(np.array(cct_scale_fun([cct])) - 2 * dT / nsteps)\n else:\n if (q > 0) & (q < np.size(ccts_i) - 1):\n dT = 2 * dT / nsteps\n d_p1m1 = ((u[(q + 1)] - u[(q - 1)]) ** 2.0 + (v[(q + 1)] - v[(q - 1)]) ** 2.0) ** 0.5\n x = (dc[(q - 1)] ** 2.0 - dc[(q + 1)] ** 2.0 + d_p1m1 ** 2.0) / 2.0 * d_p1m1\n vBB = v[(q - 1)] + (v[(q + 1)] - v[(q - 1)]) * (x / d_p1m1)\n signduv = np.sign(vt[i] - vBB)\n delta_cct = abs(cct - ccttemp)\n ccttemp = np.array(cct)\n approx_cct_temp = approx_cct_temp_temp\n else:\n ccttemp = np.nan\n cct = np.nan\n duv = np.nan\n\n duvs[i] = signduv * abs(duv)\n ccts[i] = cct\n\n if (out == 'cct') | (out == 1):\n return np2d(ccts)\n if (out == 'duv') | (out == -1):\n return np2d(duvs)\n if (out == 'cct,duv') | (out == 2):\n return (\n np2d(ccts), np2d(duvs))\n if (out == '[cct,duv]') | (out == -2):\n return np.vstack((ccts, duvs)).T\n\n\ndef xyz_to_cct_ohno(xyzw, cieobs=_CIEOBS, out='cct', wl=None, accuracy=0.1, force_out_of_lut=True, upper_cct_max=1e+20, approx_cct_temp=True):\n \"\"\"\n Convert XYZ tristimulus values to correlated color temperature (CCT) and \n Duv (distance above (>0) or below (<0) the Planckian locus) \n using Ohno's method. \n \n Args:\n :xyzw: \n | ndarray of tristimulus values\n :cieobs: \n | luxpy._CIEOBS, optional\n | CMF set used to calculated xyzw.\n :out: \n | 'cct' (or 1), optional\n | Determines what to return.\n | Other options: 'duv' (or -1), 'cct,duv'(or 2), \"[cct,duv]\" (or -2)\n :wl: \n | None, optional\n | Wavelengths used when calculating Planckian radiators.\n :accuracy: \n | float, optional\n | Stop brute-force search when cct :accuracy: is reached.\n :upper_cct_max: \n | 10.0**20, optional\n | Limit brute-force search to this cct.\n :approx_cct_temp: \n | True, optional\n | If True: use xyz_to_cct_HA() to get a first estimate of cct \n to speed up search.\n :force_out_of_lut: \n | True, optional\n | If True and cct is out of range of the LUT, then switch to \n brute-force search method, else return numpy.nan values.\n \n Returns:\n :returns: \n | ndarray with:\n | cct: out == 'cct' (or 1)\n | duv: out == 'duv' (or -1)\n | cct, duv: out == 'cct,duv' (or 2)\n | [cct,duv]: out == \"[cct,duv]\" (or -2) \n \n Note:\n LUTs are stored in ./data/cctluts/\n \n Reference:\n 1. `Ohno Y. Practical use and calculation of CCT and Duv. \n Leukos. 2014 Jan 2;10(1):47-55.\n `_\n \"\"\"\n xyzw = np2d(xyzw)\n if len(xyzw.shape) > 2:\n raise Exception('xyz_to_cct_ohno(): Input xyzwa.ndim must be <= 2 !')\n Yuv = xyz_to_Yuv(xyzw)\n axis_of_v3 = len(Yuv.shape) - 1\n u = Yuv[:, 1, None]\n v = 0.6666666666666666 * Yuv[:, 2, None]\n uv = np2d(np.concatenate((u, v), axis=axis_of_v3))\n if cieobs not in _CCT_LUT:\n _CCT_LUT[cieobs] = calculate_lut(ccts=None, cieobs=cieobs, add_to_lut=False)\n cct_LUT = _CCT_LUT[cieobs][:, 0, None]\n uv_LUT = _CCT_LUT[cieobs][:, 1:3]\n CCT = np.ones(uv.shape[0]) * np.nan\n Duv = CCT.copy()\n idx_m = 0\n idx_M = uv_LUT.shape[0] - 1\n for i in range(uv.shape[0]):\n out_of_lut = False\n delta_uv = ((uv_LUT - uv[i]) ** 2.0).sum(axis=1) ** 0.5\n idx_min = delta_uv.argmin()\n if idx_min == idx_m:\n idx_min_m1 = idx_min\n out_of_lut = True\n else:\n idx_min_m1 = idx_min - 1\n if idx_min == idx_M:\n idx_min_p1 = idx_min\n out_of_lut = True\n else:\n idx_min_p1 = idx_min + 1\n if (out_of_lut == True) & (force_out_of_lut == True):\n cct_i, Duv_i = xyz_to_cct_search((xyzw[i]), cieobs=cieobs, wl=wl, accuracy=accuracy, out='cct,duv', upper_cct_max=upper_cct_max, approx_cct_temp=approx_cct_temp)\n CCT[i] = cct_i\n Duv[i] = Duv_i\n continue\n else:\n if (out_of_lut == True) & (force_out_of_lut == False):\n CCT[i] = np.nan\n Duv[i] = np.nan\n cct_m1 = cct_LUT[idx_min_m1]\n delta_uv_m1 = delta_uv[idx_min_m1]\n uv_m1 = uv_LUT[idx_min_m1]\n cct_p1 = cct_LUT[idx_min_p1]\n delta_uv_p1 = delta_uv[idx_min_p1]\n uv_p1 = uv_LUT[idx_min_p1]\n cct_0 = cct_LUT[idx_min]\n delta_uv_0 = delta_uv[idx_min]\n delta_uv_p1m1 = ((uv_p1[0] - uv_m1[0]) ** 2.0 + (uv_p1[1] - uv_m1[1]) ** 2.0) ** 0.5\n x = (delta_uv_m1 ** 2 - delta_uv_p1 ** 2 + delta_uv_p1m1 ** 2) / (2 * delta_uv_p1m1)\n Tx = cct_m1 + (cct_p1 - cct_m1) * (x / delta_uv_p1m1)\n vBB = uv_m1[1] + (uv_p1[1] - uv_m1[1]) * (x / delta_uv_p1m1)\n Tx_corrected_triangular = Tx * 0.99991\n signDuv = np.sign(uv[i][1] - vBB)\n Duv_triangular = signDuv * np.atleast_1d((delta_uv_m1 ** 2.0 - x ** 2.0) ** 0.5)\n a = delta_uv_m1 / (cct_m1 - cct_0 + _EPS) / (cct_m1 - cct_p1 + _EPS)\n b = delta_uv_0 / (cct_0 - cct_m1 + _EPS) / (cct_0 - cct_p1 + _EPS)\n c = delta_uv_p1 / (cct_p1 - cct_0 + _EPS) / (cct_p1 - cct_m1 + _EPS)\n A = a + b + c\n B = -(a * (cct_p1 + cct_0) + b * (cct_p1 + cct_m1) + c * (cct_0 + cct_m1))\n C = a * cct_p1 * cct_0 + b * cct_p1 * cct_m1 + c * cct_0 * cct_m1\n Tx = -B / (2 * A + _EPS)\n Tx_corrected_parabolic = Tx * 0.99991\n Duv_parabolic = signDuv * (A * np.power(Tx_corrected_parabolic, 2) + B * Tx_corrected_parabolic + C)\n Threshold = 0.002\n if Duv_triangular < Threshold:\n CCT[i] = Tx_corrected_triangular\n Duv[i] = Duv_triangular\n else:\n CCT[i] = Tx_corrected_parabolic\n Duv[i] = Duv_parabolic\n\n if (out == 'cct') | (out == 1):\n return np2dT(CCT)\n if (out == 'duv') | (out == -1):\n return np2dT(Duv)\n if (out == 'cct,duv') | (out == 2):\n return (\n np2dT(CCT), np2dT(Duv))\n if (out == '[cct,duv]') | (out == -2):\n return np.vstack((CCT, Duv)).T\n\n\ndef cct_to_xyz(ccts, duv=None, cieobs=_CIEOBS, wl=None, mode='lut', out=None, accuracy=0.1, force_out_of_lut=True, upper_cct_max=200.0, approx_cct_temp=True):\n \"\"\"\n Convert correlated color temperature (CCT) and Duv (distance above (>0) or \n below (<0) the Planckian locus) to XYZ tristimulus values.\n \n | Finds xyzw_estimated by minimization of:\n | \n | F = numpy.sqrt(((100.0*(cct_min - cct)/(cct))**2.0) \n | + (((duv_min - duv)/(duv))**2.0))\n | \n | with cct,duv the input values and cct_min, duv_min calculated using \n | luxpy.xyz_to_cct(xyzw_estimated,...).\n \n Args:\n :ccts: \n | ndarray of cct values\n :duv: \n | None or ndarray of duv values, optional\n | Note that duv can be supplied together with cct values in :ccts: \n as ndarray with shape (N,2)\n :cieobs: \n | luxpy._CIEOBS, optional\n | CMF set used to calculated xyzw.\n :mode: \n | 'lut' or 'search', optional\n | Determines what method to use.\n :out: \n | None (or 1), optional\n | If not None or 1: output a ndarray that contains estimated \n xyz and minimization results: \n | (cct_min, duv_min, F_min (objective fcn value))\n :wl: \n | None, optional\n | Wavelengths used when calculating Planckian radiators.\n :accuracy: \n | float, optional\n | Stop brute-force search when cct :accuracy: is reached.\n :upper_cct_max: \n | 10.0**20, optional\n | Limit brute-force search to this cct.\n :approx_cct_temp: \n | True, optional\n | If True: use xyz_to_cct_HA() to get a first estimate of cct to \n speed up search.\n :force_out_of_lut: \n | True, optional\n | If True and cct is out of range of the LUT, then switch to \n brute-force search method, else return numpy.nan values.\n \n Returns:\n :returns: \n | ndarray with estimated XYZ tristimulus values\n \n Note:\n If duv is not supplied (:ccts:.shape is (N,1) and :duv: is None), \n source is assumed to be on the Planckian locus.\n \"\"\"\n if isinstance(ccts, list):\n ccts = np2dT(np.array(ccts))\n else:\n ccts = np2d(ccts)\n if len(ccts.shape) > 2:\n raise Exception('cct_to_xyz(): Input ccts.shape must be <= 2 !')\n cct = np2d(ccts[:, 0, None])\n if (duv is None) & (ccts.shape[1] == 2):\n duv = np2d(ccts[:, 1, None])\n else:\n if duv is not None:\n duv = np2d(duv)\n BB = cri_ref(ccts=cct, wl3=wl, ref_type=['BB'])\n xyz_est = spd_to_xyz(data=BB, cieobs=cieobs, out=1)\n results = np.ones([ccts.shape[0], 3]) * np.nan\n if duv is not None:\n\n def objfcn(uv_offset, uv0, cct, duv, out=1):\n uv0 = np2d(uv0 + uv_offset)\n Yuv0 = np.concatenate((np2d([100.0]), uv0), axis=1)\n cct_min, duv_min = xyz_to_cct((Yuv_to_xyz(Yuv0)), cieobs=cieobs, out='cct,duv', wl=wl, mode=mode, accuracy=accuracy, force_out_of_lut=force_out_of_lut, upper_cct_max=upper_cct_max, approx_cct_temp=approx_cct_temp)\n F = np.sqrt((100.0 * (cct_min[0] - cct[0]) / cct[0]) ** 2.0 + ((duv_min[0] - duv[0]) / duv[0]) ** 2.0)\n if out == 'F':\n return F\n else:\n return np.concatenate((cct_min, duv_min, np2d(F)), axis=1)\n\n for i in range(xyz_est.shape[0]):\n xyz0 = xyz_est[i]\n cct_i = cct[i]\n duv_i = duv[i]\n cct_min, duv_min = xyz_to_cct(xyz0, cieobs=cieobs, out='cct,duv', wl=wl, mode=mode, accuracy=accuracy, force_out_of_lut=force_out_of_lut, upper_cct_max=upper_cct_max, approx_cct_temp=approx_cct_temp)\n if np.abs(duv[i]) > _EPS:\n Yuv0 = xyz_to_Yuv(xyz0)\n uv0 = Yuv0[0][1:3]\n OptimizeResult = minimize(fun=objfcn, x0=(np.zeros((1, 2))), args=(uv0, cct_i, duv_i, 'F'), method='Nelder-Mead', options={'maxiter':np.inf, 'maxfev':np.inf, 'xatol':1e-06, 'fatol':1e-06})\n betas = OptimizeResult['x']\n if out is not None:\n results[i] = objfcn(betas, uv0, cct_i, duv_i, out=3)\n uv0 = np2d(uv0 + betas)\n Yuv0 = np.concatenate((np2d([100.0]), uv0), axis=1)\n xyz_est[i] = Yuv_to_xyz(Yuv0)\n else:\n xyz_est[i] = xyz0\n\n if (out is None) | (out == 1):\n return xyz_est\n else:\n return np.concatenate((xyz_est, results), axis=1)\n\n\ndef xyz_to_cct(xyzw, cieobs=_CIEOBS, out='cct', mode='lut', wl=None, accuracy=0.1, force_out_of_lut=True, upper_cct_max=1e+20, approx_cct_temp=True):\n \"\"\"\n Convert XYZ tristimulus values to correlated color temperature (CCT) and\n Duv (distance above (>0) or below (<0) the Planckian locus)\n using either the brute-force search method or Ohno's method. \n \n | Wrapper function for use with luxpy.colortf().\n \n Args:\n :xyzw:\n | ndarray of tristimulus values\n :cieobs:\n | luxpy._CIEOBS, optional\n | CMF set used to calculated xyzw.\n :mode: \n | 'lut' or 'search', optional\n | Determines what method to use.\n :out: \n | 'cct' (or 1), optional\n | Determines what to return.\n | Other options: 'duv' (or -1), 'cct,duv'(or 2), \"[cct,duv]\" (or -2)\n :wl: \n | None, optional\n | Wavelengths used when calculating Planckian radiators.\n :accuracy:\n | float, optional\n | Stop brute-force search when cct :accuracy: is reached.\n :upper_cct_max: \n | 10.0**20, optional\n | Limit brute-force search to this cct.\n :approx_cct_temp: \n | True, optional\n | If True: use xyz_to_cct_HA() to get a first estimate of cct to \n speed up search.\n :force_out_of_lut: \n | True, optional\n | If True and cct is out of range of the LUT, then switch to \n brute-force search method, else return numpy.nan values.\n \n Returns:\n :returns: \n | ndarray with:\n | cct: out == 'cct' (or 1)\n | Optional: \n | duv: out == 'duv' (or -1), \n | cct, duv: out == 'cct,duv' (or 2), \n | [cct,duv]: out == \"[cct,duv]\" (or -2)\n \"\"\"\n if (mode == 'lut') | (mode == 'ohno'):\n return xyz_to_cct_ohno(xyzw=xyzw, cieobs=cieobs, out=out, accuracy=accuracy, force_out_of_lut=force_out_of_lut)\n if mode == 'search':\n return xyz_to_cct_search(xyzw=xyzw, cieobs=cieobs, out=out, wl=wl, accuracy=accuracy, upper_cct_max=upper_cct_max, approx_cct_temp=approx_cct_temp)\n\n\ndef xyz_to_duv(xyzw, cieobs=_CIEOBS, out='duv', mode='lut', wl=None, accuracy=0.1, force_out_of_lut=True, upper_cct_max=1e+20, approx_cct_temp=True):\n \"\"\"\n Convert XYZ tristimulus values to Duv (distance above (>0) or below (<0) \n the Planckian locus) and correlated color temperature (CCT) values\n using either the brute-force search method or Ohno's method. \n \n | Wrapper function for use with luxpy.colortf().\n \n Args:\n :xyzw: \n | ndarray of tristimulus values\n :cieobs:\n | luxpy._CIEOBS, optional\n | CMF set used to calculated xyzw.\n :mode: \n | 'lut' or 'search', optional\n | Determines what method to use.\n :out: \n | 'duv' (or 1), optional\n | Determines what to return.\n | Other options: 'duv' (or -1), 'cct,duv'(or 2), \"[cct,duv]\" (or -2)\n :wl: \n | None, optional\n | Wavelengths used when calculating Planckian radiators.\n :accuracy: \n | float, optional\n | Stop brute-force search when cct :accuracy: is reached.\n :upper_cct_max: \n | 10.0**20, optional\n | Limit brute-force search to this cct.\n :approx_cct_temp:\n | True, optional\n | If True: use xyz_to_cct_HA() to get a first estimate of cct \n to speed up search.\n :force_out_of_lut: \n | True, optional\n | If True and cct is out of range of the LUT, then switch to \n brute-force search method, else return numpy.nan values.\n \n Returns:\n :returns:\n | ndarray with:\n | duv: out == 'duv' (or -1)\n | Optional: \n | duv: out == 'duv' (or -1), \n | cct, duv: out == 'cct,duv' (or 2), \n | [cct,duv]: out == \"[cct,duv]\" (or -2)\n \"\"\"\n if (mode == 'lut') | (mode == 'ohno'):\n return xyz_to_cct_ohno(xyzw=xyzw, cieobs=cieobs, out=out, accuracy=accuracy, force_out_of_lut=force_out_of_lut)\n if mode == 'search':\n return xyz_to_cct_search(xyzw=xyzw, cieobs=cieobs, out=out, wl=wl, accuracy=accuracy, upper_cct_max=upper_cct_max, approx_cct_temp=approx_cct_temp)\n\n\ndef cct_to_mired(data):\n \"\"\"\n Convert cct to Mired scale (or back). \n\n Args:\n :data: \n | ndarray with cct or Mired values.\n\n Returns:\n :returns: \n | ndarray ((10**6) / data)\n \"\"\"\n return np.divide(1000000, data)","sub_path":"pycfiles/luxpy-1.4.18-py3-none-any/cct.cpython-36.py","file_name":"cct.cpython-36.py","file_ext":"py","file_size_in_byte":31279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"28732852","text":"# _*_ coding:utf-8 _*_\n# @time: 2020/11/23 上午9:21\n# @author: 张新新\n# @email: 1262981714@qq.com\nimport os\nimport cv2\nimport transforms3d\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom auto import utils\nfrom pylab import mpl\nimport pandas as pd\nimport seaborn as sns\ncolorMap ={\n \"no_Local\":\"black\",\n \"std\":\"blue\",\n \"no_local_std\":\"gray\",\n \"rme\":\"green\",\n \"no_lock_rme\":\"red\",\n \"random\":\"yellow\",\n 'ias':\"pink\"\n }\ncali_type = 0\nif cali_type==0:\n Hx = \"Hcamera2end\"\n Hy = \"Hobj2base\"\nelse:\n Hx = \"Hcamera2base\"\n Hy = \"Hobj2end\"\n\n\ndef getErrorList(fileList,euler_hx_gt,t_hx_gt,euler_hy_gt,t_hy_gt):\n euler_hx_error_mutlti = np.array([])\n t_hx_error_mutlti = np.array([])\n euler_hy_error_mutlti = np.array([])\n t_hy_error_mutlti = np.array([])\n for file in fileList:\n result = utils.json_load(file)\n if not result[0][\"simu\"]==0.002:\n continue\n euler_hx_error = np.array([])\n t_hx_error = np.array([])\n euler_hy_error = np.array([])\n t_hy_error = np.array([])\n for i in range(5,26):\n for dict in result:\n if dict[\"image_number\"]==i:\n Hx_temp = dict[Hx]\n Hy_temp = dict[Hy]\n euler_hx_temp = transforms3d.euler.mat2euler(Hx_temp[:3, :3])\n t_hx_temp = Hx_temp[:3, 3]\n euler_hx_error_rx = min(abs(euler_hx_temp[0]-euler_hx_gt[0]),\n abs(euler_hx_temp[0]-euler_hx_gt[0]+2*3.1415926),\n abs(euler_hx_temp[0] - euler_hx_gt[0] - 2 * 3.1415926))\n euler_hx_error_ry = min(abs(euler_hx_temp[1] - euler_hx_gt[1]),\n abs(euler_hx_temp[1] - euler_hx_gt[1] + 2 * 3.1415926),\n abs(euler_hx_temp[1] - euler_hx_gt[1] - 2 * 3.1415926))\n euler_hx_error_rz = min(abs(euler_hx_temp[2] - euler_hx_gt[2]),\n abs(euler_hx_temp[2] - euler_hx_gt[2] + 2 * 3.1415926),\n abs(euler_hx_temp[2] - euler_hx_gt[2] - 2 * 3.1415926))\n if max(euler_hx_error_rx,euler_hx_error_ry,euler_hx_error_rz)>0.08 :\n print(file)\n euler_hx_error = np.append(euler_hx_error,np.mean(np.array([euler_hx_error_rx,euler_hx_error_ry,euler_hx_error_rz])))\n t_hx_error = np.append(t_hx_error, np.mean(np.abs(t_hx_temp - t_hx_gt)))\n\n euler_hy_temp = transforms3d.euler.mat2euler(Hy_temp[:3, :3])\n # if np.linalg.norm(euler_hy_temp - euler_hy_gt) > np.linalg.norm(euler_hy_temp + euler_hy_gt):\n # euler_hy_temp = -euler_hy_temp\n t_hy_temp = Hy_temp[:3, 3]\n #euler_hy_error = np.append(euler_hy_error, np.abs(euler_hy_temp - euler_hy_gt))\n euler_hy_error_rx = min(abs(euler_hy_temp[0]-euler_hy_gt[0]),\n abs(euler_hy_temp[0]-euler_hy_gt[0]+2*3.1415926),\n abs(euler_hy_temp[0] - euler_hy_gt[0] - 2 * 3.1415926))\n euler_hy_error_ry = min(abs(euler_hy_temp[1] - euler_hy_gt[1]),\n abs(euler_hy_temp[1] - euler_hy_gt[1] + 2 * 3.1415926),\n abs(euler_hy_temp[1] - euler_hy_gt[1] - 2 * 3.1415926))\n euler_hy_error_rz = min(abs(euler_hy_temp[2] - euler_hy_gt[2]),\n abs(euler_hy_temp[2] - euler_hy_gt[2] + 2 * 3.1415926),\n abs(euler_hy_temp[2] - euler_hy_gt[2] - 2 * 3.1415926))\n\n euler_hy_error = np.append(euler_hy_error, np.mean(np.array([euler_hy_error_rx,euler_hy_error_ry,euler_hy_error_rz])))\n t_hy_error = np.append(t_hy_error, np.mean(np.abs(t_hy_temp - t_hy_gt)))\n euler_hx_error_mutlti = np.append(euler_hx_error_mutlti, euler_hx_error)\n t_hx_error_mutlti = np.append(t_hx_error_mutlti, t_hx_error)\n euler_hy_error_mutlti = np.append(euler_hy_error_mutlti, euler_hy_error)\n t_hy_error_mutlti = np.append(t_hy_error_mutlti, t_hy_error)\n euler_hx_error_mutlti = euler_hx_error_mutlti.reshape([-1, np.size(x_range)])\n t_hx_error_mutlti = t_hx_error_mutlti.reshape([-1, np.size(x_range)])\n euler_hy_error_mutlti = euler_hy_error_mutlti.reshape([-1, np.size(x_range)])\n t_hy_error_mutlti = t_hy_error_mutlti.reshape([-1, np.size(x_range)])\n return euler_hx_error_mutlti,t_hx_error_mutlti,euler_hy_error_mutlti,t_hy_error_mutlti\n\ndef draw_error(ax_list,euler_error,t_error,label,x_range):\n rx_error = euler_error[:,0]\n ry_error = euler_error[:,1]\n rz_error = euler_error[:,2]\n\n tx_error = t_error[:, 0]\n ty_error = t_error[:, 1]\n tz_error = t_error[:, 2]\n\n ax_list[0].plot(x_range, rx_error,color=colorMap[label], label=label)\n ax_list[0].set_title(\"rx\")\n ax_list[1].plot(x_range, ry_error,color=colorMap[label], label=label)\n ax_list[1].set_title(\"ry\")\n ax_list[2].plot(x_range, rz_error,color=colorMap[label], label=label)\n ax_list[2].set_title(\"rz\")\n ax_list[3].plot(x_range, tx_error,color=colorMap[label], label=label)\n ax_list[3].set_title(\"tx\")\n ax_list[4].plot(x_range, ty_error,color=colorMap[label], label=label)\n ax_list[4].set_title(\"ty\")\n ax_list[5].plot(x_range, tz_error,color=colorMap[label], label=label)\n ax_list[5].set_title(\"tz\")\n\n\ndef init_set():\n plt.rcParams['figure.figsize'] = (8.0, 4.0)\n fig1, f1_axes = plt.subplots(ncols=2, nrows=1, constrained_layout=True)\n # spec2 = gridspec.GridSpec(ncols=4, nrows=2, figure=fig1)\n ax_list = []\n\n ax_list.append(f1_axes[0])\n ax_list.append(f1_axes[1])\n # ax_list[0].set_ylabel(\"Absulute Rotation error(rad)\")\n # ax_list[1].set_ylabel(\"Absulute Position error(m)\")\n # label_ax = fig1.add_subplot(f1_axes[0, 3])\n # plain_ax = fig1.add_subplot(f1_axes[1, 3])\n # plain_ax.get_xaxis().set_visible(False)\n # plain_ax.get_yaxis().set_visible(False)\n # plain_ax.set_frame_on(False)\n\n # 设置label\n\n # label_ax.set_frame_on(False)\n # label_ax.get_xaxis().set_visible(False)\n # label_ax.get_yaxis().set_visible(False)\n # lns = []\n # for label in method_list:\n # lns = lns + plt.plot([], [], color=colorMap[label], label=label)\n # labs = [l.get_label() for l in lns]\n # label_ax.legend(lns, labs, loc=\"upper right\")\n return ax_list\n\n\n\ndef draw_error_seaborn_ax(ax,error_dic,x_range,fileName=None):\n df = pd.DataFrame(error_dic, index=x_range)\n if not (fileName is None):\n df.to_csv(fileName)\n sns.lineplot(data=df, ax=ax)\n\n# def draw_error_seaborn(ax,error_dic,x_range,file_suffix):\n# error_dic_x = {}\n# error_dic_y = {}\n# error_dic_z = {}\n# for method in error_dic:\n# error_dic_x[method]= error_dic[method][:,0]\n# error_dic_y[method]= error_dic[method][:,1]\n# error_dic_z[method]= error_dic[method][:,2]\n# draw_error_seaborn_ax(ax_list[0],error_dic_x,x_range,file_suffix+\"x_error.csv\")\n# draw_error_seaborn_ax(ax_list[1],error_dic_y,x_range,file_suffix+\"y_error.csv\")\n# draw_error_seaborn_ax(ax_list[2],error_dic_z,x_range,file_suffix+\"z_error.csv\")\n\n\nif __name__ == '__main__':\n method_list = [ 'std','no_Local','no_local_std', \"random\",'ias']\n name_list = ['std','no_Local','no_local_std', \"random\",'ias']\n #文件划分\n method_file_list = []\n sns.set_style(\"whitegrid\")\n for i in range(len(method_list)):\n method_file_list.append([])\n root_dir = \"../result/11_33\"\n files = os.listdir(root_dir)\n for file in files:\n for i in range(len(method_list)):\n if file.startswith(method_list[i]):\n # if len(method_file_list[i])>20:\n # continue\n method_file_list[i].append(os.path.join(root_dir,file))\n if cali_type==0:\n fs = cv2.FileStorage(\"../config/handineye_gt.yml\", cv2.FileStorage_READ)\n else:\n fs = cv2.FileStorage(\"../config/handtoeye_gt.yml\", cv2.FileStorage_READ)\n Hx_gt = fs.getNode(Hx).mat()\n Hy_gt = fs.getNode(Hy).mat()\n fs.release()\n euler_hx_gt = transforms3d.euler.mat2euler(Hx_gt[:3, :3])\n t_hx_gt = Hx_gt[:3, 3]\n euler_hy_gt = transforms3d.euler.mat2euler(Hy_gt[:3, :3])\n t_hy_gt = Hy_gt[:3, 3]\n x_range = np.arange(5, 26, 1)\n #error 统计\n method_error = []\n method_std = []\n ## test\n\n # method_file_list = [\"../result/11_8/random_11_12_20_16.json\"]\n # euler_hx_error, t_hx_error, euler_hy_error, t_hy_error = \\\n # getErrorList(method_file_list, euler_hx_gt, t_hx_gt, euler_hy_gt, t_hy_gt)\n hx_euler_mean = []\n hx_euler_std= []\n hx_t_mean = []\n hx_t_std = []\n hy_euler_mean = []\n hy_euler_std = []\n hy_t_mean = []\n hy_t_std = []\n number = []\n methods = []\n\n euler_error_camera2end_mean_dict = {}\n t_error_camera2end_mean_dict = {}\n euler_error_obj2base_mean_dict = {}\n t_error_obj2base_mean_dict = {}\n euler_error_camera2end_std_dict = {}\n t_error_camera2end_std_dict = {}\n euler_error_obj2base_std_dict = {}\n t_error_obj2base_std_dict = {}\n for i in range(len(method_list)):\n euler_hx_error, t_hx_error, euler_hy_error, t_hy_error = \\\n getErrorList(method_file_list[i],euler_hx_gt,t_hx_gt,euler_hy_gt,t_hy_gt)\n\n hx_euler_mean_temp = np.mean(euler_hx_error,axis=0)\n hx_t_mean_temp=np.mean(t_hx_error,axis=0)\n hy_euler_mean_temp=np.mean(euler_hy_error,axis=0)\n hy_t_mean_temp=np.mean(t_hy_error,axis=0)\n hx_euler_std_temp=np.std(euler_hx_error,axis=0)\n hx_t_std_temp=np.std(t_hx_error,axis=0)\n hy_euler_std_temp=np.std(euler_hy_error,axis=0)\n hy_t_std_temp=np.std(t_hy_error,axis=0)\n for j in range(21):\n number.append(j+5)\n methods.append(method_list[i])\n hx_euler_mean.append(hx_euler_mean_temp[j])\n hx_t_mean.append(hx_t_mean_temp[j])\n hy_euler_mean.append(hy_euler_mean_temp[j])\n hy_t_mean.append(hy_t_mean_temp[j])\n hx_euler_std.append(hx_euler_std_temp[j])\n hx_t_std.append(hx_t_std_temp[j])\n hy_euler_std.append(hy_euler_std_temp[j])\n hy_t_std.append(hy_t_std_temp[j])\n hx_euler_error_df = pd.DataFrame({\"number\":number,\"mean\":hx_euler_mean,\"std\":hx_euler_std,\"method\":methods})\n hx_t_error_df = pd.DataFrame({\"number\":number,\"mean\":hx_t_mean,\"std\":hx_t_std,\"method\":methods})\n hy_euler_error_df = pd.DataFrame({\"number\":number,\"mean\":hy_euler_mean,\"std\":hy_euler_std,\"method\":methods})\n hy_t_error_df = pd.DataFrame({\"number\":number,\"mean\":hy_t_mean,\"std\":hy_t_std,\"method\":methods})\n #ax_list = init_set()\n # sns.lineplot(x=\"number\",y=\"mean\",hue=\"method\",data=hx_euler_error_df,ax=ax_list[0])\n # ax2 = ax_list[0].twinx()\n ax = sns.lineplot(x=\"number\", y=\"std\",hue=\"method\",data=hx_euler_error_df, dashes=[(2, 2), (2, 2)])\n plt.show()\n #\n # t_error_obj2base_std_dict[name_list[i]]=np.std(t_hy_error,axis=0)\n # hx_euler = pd.DataFrame({})\n # ax_list = init_set()\n # draw_error_seaborn_ax(ax_list[0], euler_error_camera2end_mean_dict, x_range,os.path.join(root_dir, \"{0}_mean_r.csv\".format(Hx)))\n # draw_error_seaborn_ax(ax_list[1], t_error_camera2end_mean_dict, x_range,os.path.join(root_dir, \"{0}_mean_t.csv\".format(Hx)))\n # for i in range(5):\n # ax_list[i+1].legend_.remove()\n # ax_list[0].set_ylabel(\"error(rad)\")\n # ax_list[3].set_ylabel(\"error(m)\")\n # ax_list[3].set_xlabel(\"iter\")\n # ax_list[4].set_xlabel(\"iter\")\n # ax_list[5].set_xlabel(\"iter\")\n # plt.savefig(os.path.join(root_dir, \"E{0}_mean_two.png\").format(Hx))\n # plt.show()\n # ax_list = init_set()\n # draw_error_seaborn_ax(ax_list[0], euler_error_camera2end_std_dict, x_range,os.path.join(root_dir, \"{0}_std_r.csv\".format(Hx)))\n # draw_error_seaborn_ax(ax_list[1], t_error_camera2end_std_dict, x_range,os.path.join(root_dir, \"{0}_std_t.csv\".format(Hx)))\n # # for i in range(5):\n # # ax_list[i+1].legend_.remove()\n # plt.savefig(os.path.join(root_dir, \"E{0}_std_two.png\").format(Hx))\n # plt.show()\n # ax_list = init_set()\n # draw_error_seaborn_ax(ax_list[0], euler_error_obj2base_mean_dict, x_range,os.path.join(root_dir, \"{0}_mean_r.csv\".format(Hy)))\n # draw_error_seaborn_ax(ax_list[1], t_error_obj2base_mean_dict, x_range,os.path.join(root_dir, \"{0}_mean_t.csv\".format(Hy)))\n # # for i in range(5):\n # # ax_list[i+1].legend_.remove()\n # plt.savefig(os.path.join(root_dir, \"E{0}_mean_two.png\").format(Hy))\n # plt.show()\n # ax_list = init_set()\n # draw_error_seaborn_ax(ax_list[0], euler_error_obj2base_std_dict, x_range,os.path.join(root_dir, \"{0}_std_r.csv\".format(Hy)))\n # draw_error_seaborn_ax(ax_list[1], t_error_obj2base_std_dict, x_range,os.path.join(root_dir, \"{0}_std_r.csv\".format(Hy)))\n # # for i in range(5):\n # # ax_list[i+1].legend_.remove()\n # plt.savefig(os.path.join(root_dir, \"E{0}_std_two.png\").format(Hy))\n # plt.show()","sub_path":"experiment/report_two_part.py","file_name":"report_two_part.py","file_ext":"py","file_size_in_byte":13212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"49143136","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('cardrankings/', views.CardRankingListView.as_view(), name='cardrankings'),\n path('cardrankings/', views.CardRankingDetailView.as_view(), name='cardranking-detail'),\n path('comparecards/', views.CompareCards, name='comparecards'),\n path('allcards/', views.CardListView.as_view(), name='allcards'),\n path('allcards/', views.CardDetailView.as_view(), name='card-detail'),\n]","sub_path":"mtg_compare/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"358768739","text":"import time\n#Function time()\nprint(\"Seconds since epoch = \" + str(time.time()))\n\ncountdown = 3\nwhile(countdown >= 0):\n print(countdown)\n countdown -= 1\n time.sleep(1)\nprint(\"HAPPY NEW YEAR!\")\n\nstartTime = time.time()\nuserName = input(\"Type your name: \")\nendTime = time.time()\nprint(\"Elapse time: \" + str(endTime-startTime))","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"140270799","text":"# Создать текстовый файл (не программно), сохранить в нем несколько строк,\n# выполнить подсчет количества строк, количества слов в каждой строке.\n\n\ncurrent_line = 0\nfile_info = {}\nwith open('lesson5_task2.txt', 'r', encoding='utf-8') as user_file:\n for current_string in user_file:\n current_line += 1\n words_in_line = len(current_string.split())\n file_info.update({current_line: words_in_line})\nprint(file_info)\nprint('Количество строк:', current_line)","sub_path":"lesson-5/lesson5_task2.py","file_name":"lesson5_task2.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"337573032","text":"from tokenizer import Tokenizer\nfrom parser import Parser\nfrom interpreter import Interpreter\n\n\nclass Calculator:\n def __init__(self):\n self.interpreter = Interpreter(\"\")\n\n def start(self):\n user_input = input(\"Hello! Welcome to The Calculator 4000!\\nEnter Whatever you want to calculate, press 'h' for Help, or press 'q':\\n\")\n while user_input != 'q' and user_input != 'Q':\n if user_input == 'h' or user_input == 'H':\n print( \"& : Minimum - (Usage: 6 & 2 = 2)\\n$ : Maximum\\n@ : Average - (Usage: 5 @ 7 = 6)\\n\"\n \"! : Factorial - (Usage: 3! = 6)\\n% : Modulo\\n~ : Sign Flip - (Usage: ~7 = -7)\\n\"\n \"^ : Exponentiation\\n/ : Division\\n* : Multiplication\\n- : Subtraction\\n+ : Addition\\n\"\n \"Parenthesis or done with SQUARE BRACKETS '[' and ']'\\n\")\n elif user_input == 'q' or user_input == 'Q':\n break\n else:\n self.interpreter.parser.set_program(user_input)\n calculated_val = self.interpreter.interpret()\n print(\"Value of {} = {}\".format(user_input, calculated_val))\n\n user_input = input(\"Enter Whatever you want to calculate, press 'h' for Help, or press 'q':\\n\")\n print(\"Thank You for using The Calculator 4000!. Goodbye!\")\n\n\nif __name__ == \"__main__\":\n program = \"[1! + 5 * 7 & [7!]] $ 8\"\n\n #Test the tokenizer by printing all the tokens\n t = Tokenizer(program)\n while t.has_more_tokens():\n print(t.get_next_token())\n\n #Test the parser by generating and printing the whole ast tree\n p = Parser(program)\n # print(\"AST Tree:\\n{}\".format(p.parse()))\n root = p.parse()\n root.bfs_pretty_print()\n print(\"\\n\")\n\n #Test the interpreter program\n i = Interpreter(program)\n print(\"Value of {} = {}\".format(program, i.interpret()))\n\n #Test the Calculator\n calc = Calculator()\n calc.start()\n\n","sub_path":"calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"174189702","text":"#!/usr/bin/env python3\n# --- Day 1: The Tyranny of the Rocket Equation ---\n# Part Two\n\nimport sys, math \n\n# Should we debug or not.\ndebug = False\n\n# Total Fuel required and also what we should calculate\ntotalFuel = 0\n\n# Function to calculate the fuel for a mass\ndef CalcFuel(mass):\n return int(math.floor(mass / 3)) -2\n\n# Open input file as read-only and calculate fuel for each module\n# Input file has the mass och each module on each row\ntry: \n file = open('day01_input.txt', 'r') \nexcept IOError:\n print(\"Can't open file!!\")\n sys.exit(0)\n\n# Loop each line in file\nfor line in file:\n moduleMass = int(line.strip())\n if debug: print(\"Module mass: \" + str(moduleMass))\n fuelRequired = CalcFuel(moduleMass)\n # Calculate the fuel for the fuel until zero.\n while fuelRequired > 0:\n totalFuel += fuelRequired\n if debug: print(\"Fuel required: \" + str(fuelRequired) + '\\n')\n fuelRequired = CalcFuel(fuelRequired)\nfile.close()\n\nprint(\"The total amount of fuel required is: \" + str(totalFuel) + '\\n')","sub_path":"day01/day01_2.py","file_name":"day01_2.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"155965083","text":"# coding=utf-8\nfrom flask import Flask, request, jsonify, make_response, session\n\napp = Flask(__name__,\n static_folder='static', # 配置静态文件目录\n )\napp.secret_key = 'secret string'\n\n\n@app.route('/hello')\n@app.route('/')\ndef index():\n # 获取输入的参数\n arg_name = request.args.get('name', 'admin')\n authorization = '未认证'\n username = ''\n if session.get('logged_ind') == arg_name:\n authorization = '已认证'\n username = request.cookies.get('name')\n return f'

Hello {arg_name}! {authorization} {username}

'\n\n\n@app.route('/greet/')\ndef greet(name):\n\n return f'hello {name}'\n\n\n@app.route('/go_back/')\ndef go_back(year):\n # 302 重定向\n return f'欢迎来到 {2019 - year}', 302, {'Location': '/'}\n\n\n@app.route('/foo/')\ndef foo(name):\n response = make_response(jsonify({'name': name, 'age': 17}))\n response.set_cookie('name', value=name, max_age=5)\n return response\n\n\n@app.route('/login')\ndef login():\n name = request.args.get('name')\n password = request.args.get('pass')\n if password == '123456':\n session['logged_ind'] = name\n response = make_response('')\n response.set_cookie('name', name)\n return response, 302, {'Location': f'/hello?name={name}'}\n else:\n return '账号密码错误'\n\n\n@app.route('/logout')\ndef logout():\n del session['logged_ind']\n return '欢迎下次再来'\n\n\nif __name__ == '__main__':\n # 跑在 5000 端口, host 设为这可以让其他ip访问\n app.run(port=5000, debug=True, host='0.0.0.0')","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"441517149","text":"\"\"\"\nBoggle board\nAuthor: Michal Young\nRevisions: Initial version 26 Oct 2012 for CIS 210 at U. Oregon\n Feb 2013, reorganized as a class BoggleBoard\n October 2014, minor clean up of documentation\n\nThe BoggleBoard is a 4x4 matrix of tiles\nwhere each tile represents a character\n(except \"qu\" is a single tile). In addition\nto the character(s), each tile can be in\navailable or not.\n\nThe BoggleBoard also maintains a graphical depiction,\nincluding color to show which tiles are currently\nin use. \n\nLimitations:\n Standard 4x4 board assumed throughout; 4 and 16 are\n used as 'magic numbers', making this difficult to\n adapt to non-standard boards.\n\n The graphics code is tangled into maintenance of the\n board (\"model\" mixed with \"view\"); we will learn how\n to factor it out in a later project. \n\"\"\"\nimport grid\n\nclass BoggleBoard(object):\n \"\"\"\n The BoggleBoard is a 4x4 matrix of tiles\n where each tile represents a character\n (except \"qu\" is a single tile). In addition\n to the character(s), each tile can be in\n available or not.\n \"\"\"\n\n def __init__(self, tiles):\n \"\"\"\n Create a boggle board and its graphical depiction\n from a string of 16 characters.\n Args:\n self: the board (to be initialized)\n tiles: A string of exactly 16 characters, each\n representing one tile. Most characters\n represent a tile containing that character,\n but 'q' represents the pair 'qu' on a tile.\n Returns: Nothing. The board is encapsulated in this module.\n \"\"\"\n assert(len(tiles) == 16)\n self.content = [ ]\n self.in_use = [ ]\n grid.make(4,4,500,500) # Hack alert! \n for row in range(4):\n self.content.append([ ])\n self.in_use.append([ ])\n for col in range(4):\n char = tiles[4*row + col]\n if char == \"q\" :\n char = \"qu\"\n self.content[row].append(char)\n self.in_use[row].append( False )\n grid.fill_cell(row,col,grid.white) # Hack alert! \n grid.label_cell(row,col,char) # Hack alert! \n\n def get_char(self, row, col):\n \"\"\"\n Returns the character at (row,col)\n Args:\n self: this board\n row: row of board, 0..3\n col: col of board, 0..3\n Returns:\n the string labeling the tile at board[row,col]\n Requires:\n the position (row, col) should not be in use when get_char is called.\n (Proper order is to get_char(row,col), then mark_taken(row,col), then\n unmark_taken(row,col) )\n \"\"\"\n assert row >= 0 and row < len(self.content)\n assert col >= 0 and col < len(self.content[0])\n assert not self.in_use[row][col] \n return self.content[row][col]\n\n def available(self, row, col):\n \"\"\"Check whether we can take a tile at row, col.\n Args:\n self: this board\n row: row of board (may be outside board)\n col: col of board (may be outside board)\n Returns:\n boolean True iff (row,col) is a tile position on\n the board and that tile is not currently marked as\n in use.\n \"\"\"\n if row < 0 or row >= len(self.content):\n return False\n if col < 0 or col >= len(self.content[0]):\n return False\n return not self.in_use[row][col]\n\n def mark_taken(self, row, col):\n \"\"\"\n Marks the tile at row,col as currently in use\n Args:\n self: this board\n row: row of board, 0..3\n col: col of board, 0..3\n Returns:\n nothing\n Requires:\n Tile must not already be in use. mark_taken and unmark_taken must\n strictly alternate. Proper sequence is\n - check position for availability\n - get character\n - mark taken\n - further exploration from this position\n - unmark taken\n \"\"\"\n assert row >= 0 and row < len(self.content)\n assert col >= 0 and col < len(self.content[0])\n assert not self.in_use[row][col] \n self.in_use[row][col] = True\n grid.fill_cell(row,col,grid.green)\n grid.label_cell(row,col,self.content[row][col])\n\n def unmark_taken(self, row, col):\n \"\"\"\n Marks the tile at row,col as no longer in use. \n Tile at row,col must be in use when this function is called.\n Args:\n self: this board\n row: row of board, 0..3\n col: col of board, 0..3\n Returns:\n nothing\n Requires:\n Tile must be marked in use. mark_taken and unmark_taken must\n strictly alternate. Proper sequence is\n - check position for availability\n - get character\n - mark taken\n - further exploration from this position\n - unmark taken\n \n \"\"\"\n assert row >= 0 and row < len(self.content)\n assert col >= 0 and col < len(self.content[0])\n assert self.in_use[row][col] \n self.in_use[row][col] = False\n grid.fill_cell(row,col,grid.white) # Hack alert! \n grid.label_cell(row,col,self.content[row][col]) # Hack alert! \n\n\n def dump(self):\n \"\"\"For debugging: Print representation of board\n Args: \n self: this board \n Returns: nothing\n \"\"\"\n print(self.content)\n\n def __str__(self):\n \"\"\"For debugging: Return string representation of board.\n The __str__ method is called implicitly when the board is \n printed or when it is coerced into a string. \n \n Args: \n self: this board\n \"\"\"\n rep = \"\"\n for row in self.content :\n rep += \"\".join( row ) + \"\\n\"\n return rep\n \n\n \n\n\n\n \n","sub_path":"CIS210 Computer Science I/Projects/p6/boggle_board.py","file_name":"boggle_board.py","file_ext":"py","file_size_in_byte":5922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"492257040","text":"import matplotlib.pyplot as plt\n\nx_values = list(range(1,1001))\ny_values = [x**2 for x in x_values]\n\nplt.scatter(x_values, y_values, c = y_values, cmap=plt.cm.Blues, edgecolor = 'none')\nplt.title(\"Squared values\")\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.savefig('squares_plot.png', bbox_inches='tight')","sub_path":"data_visualization/scatter_squares.py","file_name":"scatter_squares.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"84982626","text":"# Formations AI for Mount & Blade by Motomataru\r\n# rel. 01/03/11\r\n\r\n# This function attaches AI_triggers only to mission \"lead_charge\"\r\n# For other missions, add to end of triggers list like so: \" ] + AI_triggers \"\r\n\r\n# Make sure to comment out competing AI triggers in the mission templates modified\r\n# For example, for M&B 1.011 \"lead_charge\"\r\n\r\n # #AI Tiggers\r\n # (0, 0, ti_once, [\r\n # (store_mission_timer_a,\":mission_time\"),(ge,\":mission_time\",2),\r\n # ],\r\n # [(call_script, \"script_select_battle_tactic\"),\r\n # (call_script, \"script_battle_tactic_init\")]),\r\n \r\n # (5, 0, 0, [\r\n # (store_mission_timer_a,\":mission_time\"),(ge,\":mission_time\",3),\r\n # (call_script, \"script_battle_tactic_apply\"),\r\n # ], []),\r\n\r\nfrom header_common import *\r\nfrom header_operations import *\r\nfrom module_constants import *\r\nfrom header_mission_templates import *\r\n\r\n#AI triggers v3 by motomataru\r\nAI_triggers = [ \r\n\t(ti_before_mission_start, 0, 0, [], [\r\n\t\t(assign, \"$cur_casualties\", 0),\r\n\t\t(assign, \"$prev_casualties\", 0),\r\n\t\t(assign, \"$ranged_clock\", 1),\r\n\t\t(assign, \"$battle_phase\", BP_Setup),\r\n\t\t(assign, \"$clock_reset\", 0),\r\n\t\t(assign, \"$team0_default_formation\", formation_default),\r\n\t\t(assign, \"$team1_default_formation\", formation_default),\r\n\t\t(assign, \"$team2_default_formation\", formation_default),\r\n\t\t(assign, \"$team3_default_formation\", formation_default),\r\n\t\t(init_position, Team0_Cavalry_Destination),\r\n\t\t(init_position, Team1_Cavalry_Destination),\r\n\t\t(init_position, Team2_Cavalry_Destination),\r\n\t\t(init_position, Team3_Cavalry_Destination),\r\n\t\t(assign, \"$team0_reinforcement_stage\", 0),\r\n\t\t(assign, \"$team1_reinforcement_stage\", 0),\r\n\t]),\r\n\r\n\t(0, AI_Delay_For_Spawn, ti_once, [], [\r\n\t\t(set_fixed_point_multiplier, 100),\r\n\t\t(call_script, \"script_battlegroup_get_position\", Team0_Starting_Point, 0, grc_everyone),\r\n\t\t(call_script, \"script_battlegroup_get_position\", Team1_Starting_Point, 1, grc_everyone),\r\n\t\t(call_script, \"script_battlegroup_get_position\", Team2_Starting_Point, 2, grc_everyone),\r\n\t\t(call_script, \"script_battlegroup_get_position\", Team3_Starting_Point, 3, grc_everyone),\r\n\t\t(call_script, \"script_field_tactics\", 1)\r\n\t]),\r\n\r\n\t(1, .5, 0, [], [\t#delay to offset half a second from formations trigger\r\n\t\t(try_begin),\r\n\t\t\t(call_script, \"script_cf_count_casualties\"),\r\n\t\t\t(assign, \"$cur_casualties\", reg0),\r\n\t\t\t(assign, \"$battle_phase\", BP_Fight),\r\n\t\t(try_end),\r\n\t\t\r\n\t\t(set_fixed_point_multiplier, 100),\r\n\t\t(call_script, \"script_store_battlegroup_data\"),\r\n\t\t(try_begin),\t#reassess ranged position when fighting starts\r\n\t\t\t(ge, \"$battle_phase\", BP_Fight),\r\n\t\t\t(eq, \"$clock_reset\", 0),\r\n\t\t\t(call_script, \"script_field_tactics\", 1),\r\n\t\t\t(assign, \"$ranged_clock\", 0),\r\n\t\t\t(assign, \"$clock_reset\", 1),\r\n\t\t(else_try),\t#reassess ranged position every five seconds after setup\r\n\t\t\t(ge, \"$battle_phase\", BP_Jockey),\r\n\t\t\t(store_mod, reg0, \"$ranged_clock\", 5),\t\t\r\n\t\t\t(eq, reg0, 0),\r\n\t\t\t(call_script, \"script_field_tactics\", 1),\r\n\t\t\t(assign, \"$team0_reinforcement_stage\", \"$defender_reinforcement_stage\"),\r\n\t\t\t(assign, \"$team1_reinforcement_stage\", \"$attacker_reinforcement_stage\"),\r\n\t\t(else_try),\r\n\t\t\t(call_script, \"script_field_tactics\", 0),\r\n\t\t(try_end),\r\n\r\n\t\t(try_begin),\r\n\t\t\t(eq, \"$battle_phase\", BP_Setup),\r\n\t\t\t(assign, \":not_in_setup_position\", 0),\r\n\t\t\t(try_for_range, \":bgteam\", 0, 4),\r\n\t\t\t\t(neq, \":bgteam\", \"$fplayer_team_no\"),\r\n\t\t\t\t(call_script, \"script_battlegroup_get_size\", \":bgteam\", grc_everyone),\r\n\t\t\t\t(gt, reg0, 0),\r\n\t\t\t\t(call_script, \"script_battlegroup_get_position\", pos1, \":bgteam\", grc_archers),\r\n\t\t\t\t(team_get_order_position, pos0, \":bgteam\", grc_archers),\r\n\t\t\t\t(get_distance_between_positions, reg0, pos0, pos1),\r\n\t\t\t\t(gt, reg0, 500),\r\n\t\t\t\t(assign, \":not_in_setup_position\", 1),\r\n\t\t\t(try_end),\r\n\t\t\t(eq, \":not_in_setup_position\", 0),\t#all AI reached setup position?\r\n\t\t\t(assign, \"$battle_phase\", BP_Jockey),\r\n\t\t(try_end),\r\n\t\t\r\n\t\t(val_add, \"$ranged_clock\", 1),\r\n\t]),\r\n]\r\n\r\ndef modmerge_formAI_mission_templates(orig_mission_templates):\r\n\tfind_i = find_object( orig_mission_templates, \"lead_charge\" )\r\n\torig_mission_templates[find_i][5].extend(AI_triggers)\r\n","sub_path":"src/formAI_mission_templates_mb.py","file_name":"formAI_mission_templates_mb.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"200328050","text":"import urllib.request\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport numpy as np\nimport re\nimport urllib.parse\n\n# Tạo headers cho request\nmy_headers = {}\nmy_headers['User-Agent'] = \"Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:48.0) Gecko/20100101 Firefox/48.0\"\n\ndef clog(t):\n with open(\"console.txt\", 'a', encoding=\"utf-8\") as console_log:\n console_log.write(str(t) + \"\\n\")\n\nchevrolet_hompage = \"http://www.chevrolet.com.vn\" \n\n# Create request for Chevrolet homepage\nmain_request = urllib.request.Request(chevrolet_hompage, headers=my_headers)\nmain_page_bs = BeautifulSoup(urllib.request.urlopen(main_request), \"html5lib\")\n\noverview_pattern = re.compile(\".+model-overview\\.html$\")\nmodel_overview_list = main_page_bs.find_all(\"a\", attrs={'href':overview_pattern})\n\noverview_set = set()\nfor i in model_overview_list:\n overview_set.add(i['href'])\n\nmodel_overview_list = sorted(list(overview_set))\n\n# print(model_overview_list)\n\nspecs_pattern = re.compile(\".+specs\\.html$\")\nfor this_overview in model_overview_list:\n model_url = chevrolet_hompage + this_overview\n model_request = urllib.request.Request(model_url, headers=my_headers)\n model_bs = BeautifulSoup(urllib.request.urlopen(model_request), \"html5lib\")\n specs_url = model_bs.find(\"a\", attrs={\"href\":specs_pattern})[\"href\"]\n specs_url = urllib.parse.quote(specs_url)\n specs_request = urllib.request.Request(chevrolet_hompage + specs_url)\n specs_bs = BeautifulSoup(urllib.request.urlopen(specs_request), \"html5lib\")\n # ids = specs_bs.find(id=\"fs_1_1\")\n # b = specs_bs.find(\"title\", recursive=True)\n i = specs_bs.find(\"tbody\", attrs={\"id\":\"fs_1_1\"})\n if not i:\n clog(\"OK\")\n t = specs_bs.find(\"title\")\n clog(t)\n else:\n clog(\"NG\")\n t = specs_bs.find(\"title\")\n clog(t)\n clog(chevrolet_hompage + specs_url)\n\n\n# # Find all anchor links correspond to models\n# model_tags = main_page_bs.find(\"div\", {\"class\":\"fck_authorsinput\"}).findAll(\"a\")\n\n# # Create a list to hold model page urls\n# model_spec_pages = []\n# for i in model_tags:\n# this_model_request = urllib.request.Request(chevrolet_hompage + i['href'], headers=my_headers)\n# model_bs = BeautifulSoup(urllib.request.urlopen(this_model_request), \"html5lib\")\n# specs_url = model_bs.find(\"li\", {\"class\":\"active\"}).findNext('li')\n# clog(specs_url.get_text())\n# # model_overview_bs = BeautifulSoup(urllib.request.urlopen(model_overview_pages))\n\n\n# this is just for test\n\n# for m in model_overview_pages:\n# print(m + \"\\n\")\n# function which get a model url and return information about that model (version name, price etc)\n# the clog() function should be replace in production\n# def get_gm__model_price(model_url):\n# req = urllib.request.Request(model_url, headers=headers)\n# model_bs = BeautifulSoup(urllib.request.urlopen(req), \"html5lib\")\n\n# model_name = model_bs.find(\"a\", {\"class\":\"modelTitle\"}).get_text()\n\n# versions = model_bs.find(\"tr\", {\"class\":\"thead\"}).findAll(\"th\")\n# for i in range(1, len(versions)):\n# clog(model_name + \"\\t\" + versions[i].get_text().strip())\n\n# testing\n# for page in model_pages:\n# get_gm__model_price(page)","sub_path":"jatoscrap/gm.py","file_name":"gm.py","file_ext":"py","file_size_in_byte":3190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"85239922","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n#\n# SPDX-License-Identifier: GPL-3.0\n#\n# GNU Radio Python Flow Graph\n# Title: Your First Flowgraph\n# GNU Radio version: 3.10.2.0\n\nfrom packaging.version import Version as StrictVersion\n\nif __name__ == '__main__':\n import ctypes\n import sys\n if sys.platform.startswith('linux'):\n try:\n x11 = ctypes.cdll.LoadLibrary('libX11.so')\n x11.XInitThreads()\n except:\n print(\"Warning: failed to XInitThreads()\")\n\nfrom PyQt5 import Qt\nfrom PyQt5.QtCore import QObject, pyqtSlot\nfrom gnuradio import qtgui\nfrom gnuradio.filter import firdes\nimport sip\nfrom gnuradio import blocks\nimport numpy\nfrom gnuradio import gr\nfrom gnuradio.fft import window\nimport sys\nimport signal\nfrom argparse import ArgumentParser\nfrom gnuradio.eng_arg import eng_float, intx\nfrom gnuradio import eng_notation\n\n\n\nfrom gnuradio import qtgui\n\nclass sinwWaveFlowgraph(gr.top_block, Qt.QWidget):\n\n def __init__(self):\n gr.top_block.__init__(self, \"Your First Flowgraph\", catch_exceptions=True)\n Qt.QWidget.__init__(self)\n self.setWindowTitle(\"Your First Flowgraph\")\n qtgui.util.check_set_qss()\n try:\n self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))\n except:\n pass\n self.top_scroll_layout = Qt.QVBoxLayout()\n self.setLayout(self.top_scroll_layout)\n self.top_scroll = Qt.QScrollArea()\n self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)\n self.top_scroll_layout.addWidget(self.top_scroll)\n self.top_scroll.setWidgetResizable(True)\n self.top_widget = Qt.QWidget()\n self.top_scroll.setWidget(self.top_widget)\n self.top_layout = Qt.QVBoxLayout(self.top_widget)\n self.top_grid_layout = Qt.QGridLayout()\n self.top_layout.addLayout(self.top_grid_layout)\n\n self.settings = Qt.QSettings(\"GNU Radio\", \"sinwWaveFlowgraph\")\n\n try:\n if StrictVersion(Qt.qVersion()) < StrictVersion(\"5.0.0\"):\n self.restoreGeometry(self.settings.value(\"geometry\").toByteArray())\n else:\n self.restoreGeometry(self.settings.value(\"geometry\"))\n except:\n pass\n\n ##################################################\n # Variables\n ##################################################\n self.samp_rate = samp_rate = 32000\n self.frequency = frequency = 0\n\n ##################################################\n # Blocks\n ##################################################\n self.qtgui_time_sink_x_1 = qtgui.time_sink_f(\n 1024, #size\n samp_rate, #samp_rate\n \"\", #name\n 1, #number of inputs\n None # parent\n )\n self.qtgui_time_sink_x_1.set_update_time(0.10)\n self.qtgui_time_sink_x_1.set_y_axis(0, 1)\n\n self.qtgui_time_sink_x_1.set_y_label('Amplitude', \"\")\n\n self.qtgui_time_sink_x_1.enable_tags(True)\n self.qtgui_time_sink_x_1.set_trigger_mode(qtgui.TRIG_MODE_FREE, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, \"\")\n self.qtgui_time_sink_x_1.enable_autoscale(False)\n self.qtgui_time_sink_x_1.enable_grid(False)\n self.qtgui_time_sink_x_1.enable_axis_labels(True)\n self.qtgui_time_sink_x_1.enable_control_panel(False)\n self.qtgui_time_sink_x_1.enable_stem_plot(False)\n\n\n labels = ['Signal 1', 'Signal 2', 'Signal 3', 'Signal 4', 'Signal 5',\n 'Signal 6', 'Signal 7', 'Signal 8', 'Signal 9', 'Signal 10']\n widths = [1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1]\n colors = ['blue', 'red', 'green', 'black', 'cyan',\n 'magenta', 'yellow', 'dark red', 'dark green', 'dark blue']\n alphas = [1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0, 1.0, 1.0, 1.0, 1.0]\n styles = [1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1]\n markers = [-1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1]\n\n\n for i in range(1):\n if len(labels[i]) == 0:\n self.qtgui_time_sink_x_1.set_line_label(i, \"Data {0}\".format(i))\n else:\n self.qtgui_time_sink_x_1.set_line_label(i, labels[i])\n self.qtgui_time_sink_x_1.set_line_width(i, widths[i])\n self.qtgui_time_sink_x_1.set_line_color(i, colors[i])\n self.qtgui_time_sink_x_1.set_line_style(i, styles[i])\n self.qtgui_time_sink_x_1.set_line_marker(i, markers[i])\n self.qtgui_time_sink_x_1.set_line_alpha(i, alphas[i])\n\n self._qtgui_time_sink_x_1_win = sip.wrapinstance(self.qtgui_time_sink_x_1.qwidget(), Qt.QWidget)\n self.top_layout.addWidget(self._qtgui_time_sink_x_1_win)\n # Create the options list\n self._frequency_options = [0, 1000, -2000]\n # Create the labels list\n self._frequency_labels = ['frequency: 0', 'frequency: 1000', 'frequency: -2000']\n # Create the combo box\n self._frequency_tool_bar = Qt.QToolBar(self)\n self._frequency_tool_bar.addWidget(Qt.QLabel(\"'frequency'\" + \": \"))\n self._frequency_combo_box = Qt.QComboBox()\n self._frequency_tool_bar.addWidget(self._frequency_combo_box)\n for _label in self._frequency_labels: self._frequency_combo_box.addItem(_label)\n self._frequency_callback = lambda i: Qt.QMetaObject.invokeMethod(self._frequency_combo_box, \"setCurrentIndex\", Qt.Q_ARG(\"int\", self._frequency_options.index(i)))\n self._frequency_callback(self.frequency)\n self._frequency_combo_box.currentIndexChanged.connect(\n lambda i: self.set_frequency(self._frequency_options[i]))\n # Create the radio buttons\n self.top_layout.addWidget(self._frequency_tool_bar)\n self.blocks_throttle_1 = blocks.throttle(gr.sizeof_char*1, samp_rate,True)\n self.blocks_char_to_float_0 = blocks.char_to_float(1, 1)\n self.analog_random_source_x_0 = blocks.vector_source_b(list(map(int, numpy.random.randint(0, 2, 1000))), True)\n\n\n ##################################################\n # Connections\n ##################################################\n self.connect((self.analog_random_source_x_0, 0), (self.blocks_throttle_1, 0))\n self.connect((self.blocks_char_to_float_0, 0), (self.qtgui_time_sink_x_1, 0))\n self.connect((self.blocks_throttle_1, 0), (self.blocks_char_to_float_0, 0))\n\n\n def closeEvent(self, event):\n self.settings = Qt.QSettings(\"GNU Radio\", \"sinwWaveFlowgraph\")\n self.settings.setValue(\"geometry\", self.saveGeometry())\n self.stop()\n self.wait()\n\n event.accept()\n\n def get_samp_rate(self):\n return self.samp_rate\n\n def set_samp_rate(self, samp_rate):\n self.samp_rate = samp_rate\n self.blocks_throttle_1.set_sample_rate(self.samp_rate)\n self.qtgui_time_sink_x_1.set_samp_rate(self.samp_rate)\n\n def get_frequency(self):\n return self.frequency\n\n def set_frequency(self, frequency):\n self.frequency = frequency\n self._frequency_callback(self.frequency)\n\n\n\n\ndef main(top_block_cls=sinwWaveFlowgraph, options=None):\n\n if StrictVersion(\"4.5.0\") <= StrictVersion(Qt.qVersion()) < StrictVersion(\"5.0.0\"):\n style = gr.prefs().get_string('qtgui', 'style', 'raster')\n Qt.QApplication.setGraphicsSystem(style)\n qapp = Qt.QApplication(sys.argv)\n\n tb = top_block_cls()\n\n tb.start()\n\n tb.show()\n\n def sig_handler(sig=None, frame=None):\n tb.stop()\n tb.wait()\n\n Qt.QApplication.quit()\n\n signal.signal(signal.SIGINT, sig_handler)\n signal.signal(signal.SIGTERM, sig_handler)\n\n timer = Qt.QTimer()\n timer.start(500)\n timer.timeout.connect(lambda: None)\n\n qapp.exec_()\n\nif __name__ == '__main__':\n main()\n","sub_path":"etc/GNURadio/sinwWaveFlowgraph.py","file_name":"sinwWaveFlowgraph.py","file_ext":"py","file_size_in_byte":7764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"74180505","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 26 00:41:09 2018\r\n\r\n@author: Holtech\r\n\"\"\"\r\n\r\n#####################################################################\r\n# MODELO DE REGRESSÃO LINEAR USANDO THEANO #\r\n#####################################################################\r\n\r\n#Enunciado\r\n# No exemplo se geram alguns dados de forma aleatória (toy dataset) \r\n# e fixamos um modelo de regressão linear que será computado antes\r\n# e depois do treinamento usando a medida RMSE.\r\n\r\n#Input data\r\n# Consiste em 1000 vetores com dimensionalidade 100 \r\n# São 1000 exemplos com 100 caraterísticas\r\n\r\n#Output data\r\n# Consiste em valores gerados aleatóriamente\r\n\r\n#importar pacotes\r\nimport numpy as np\r\nimport theano.tensor as T\r\nfrom theano import shared\r\nfrom theano import function\r\nimport sklearn.metrics\r\n\r\n#gerar o toy dataset\r\nnum_examples = 1000\r\nnum_features = 100\r\ndataset = (np.random.randn(num_examples, num_features), \r\n np.random.randn(num_examples))\r\n\r\n#definir variáveis \r\nx = T.dmatrix('x')\r\ny = T.dvector('y')\r\nw = shared(np.random.randn(num_features), name = 'w')\r\nb = shared(0., name = 'b')\r\n\r\n#definir modelo linear\r\nnet = T.dot(x, w) + b\r\n\r\n#definir função de erro\r\ndef squared_error(x, y):\r\n return (x - y)**2\r\n\r\nerror = squared_error(y, net)\r\n \r\n#definir função de custo com regularização\r\n#função: loss = min{[y - (x * w + b)]^2} + lambda * w^2\r\ndef l2(x):\r\n return T.sum(x**2)\r\n\r\nlambda_ = 0.01\r\nloss = error.mean() + lambda_ * l2(w) \r\n\r\n#definir calculo do gradiente\r\ndelta_w, delta_b = T.grad(loss, [w, b])\r\n\r\n#fase de treinamento => obter w' e b' que otimizam loss \r\neta = 0.1\r\ntrain = function(inputs = [x, y], outputs = [net, error], \r\n updates = ((w, w - eta * delta_w), (b, b - eta * delta_b)))\r\n\r\n#fase de predição => obter y_pred = x * w' + b'\r\npredict = function(inputs = [x], outputs = net)\r\n\r\n#resultados antes do treinamento\r\nprint('RMSE pre-treino: ', \r\n sklearn.metrics.mean_squared_error(dataset[1], predict(dataset[0])))\r\n\r\n#resultados depois do treinamento\r\niter_ = 1000\r\n\r\nfor i in range(iter_):\r\n y_pred, error = train(dataset[0], dataset[1])\r\n\r\nprint('RMSE pós-treino: ', \r\n sklearn.metrics.mean_squared_error(dataset[1], predict(dataset[0])))\r\n\r\n","sub_path":"1- Basics of Theano/8-Linear_Regression.py","file_name":"8-Linear_Regression.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"105360975","text":"import pygame\nimport random\n#############################################################################################\n# 기본 초기화 (반드시 해야하는것들)\npygame.init() # 초기화\n\n# 화면크기 설정\nscreen_width = 480 # 가로\nscreen_hight = 640 # 세로\nscreen = pygame.display.set_mode((screen_width, screen_hight))\n\n# 화면 타이틀\npygame.display.set_caption(\"GS game\") \n\n# FPS\nclock = pygame.time.Clock()\n#############################################################################################\n\n# 1. 사용자 게임 초기화 (배경 화면, 게임이미지, 좌표, 폰트 등)\nbackground = pygame.image.load(\"C:\\\\pythonWorkspace\\\\pygame_basic\\\\background.png\")\ncharacter = pygame.image.load(\"C:\\\\pythonWorkspace\\\\pygame_basic\\\\character.png\")\ncharacter_size = character.get_rect().size\ncharacter_width = character_size[0] # 캐릭터의 가로 크기\ncharacter_height = character_size[1] # 캐릭터의 세로 크기\ncharacter_x_pos = (screen_width- character_width) / 2 # 화면 가로의 절반 크기의 위치에 \ncharacter_y_pos = screen_hight - character_height # 맨 밑에 위치\n\n# 이동할 좌표\nto_x = 0\ncharacter_speed = 10\n\n# 똥 만들기\nddong = pygame.image.load(\"C:\\\\pythonWorkspace\\\\pygame_basic\\\\enemy.png\")\nddong_size = ddong.get_rect().size\nddong_width = ddong_size[0] # 캐릭터의 가로 크기\nddong_height = ddong_size[1] # 캐릭터의 세로 크기\nddong_x_pos = random.randint(0, screen_width-ddong_width)\nddong_y_pos = 0\nddong_speed = 10\n\n\nrunning = True\nwhile running:\n dt = clock.tick(60) # 게임화면의 초당 프레임수\n\n # 2. 이벤트 처리 (키보드, 마우스 등)\n\n for event in pygame.event.get(): # 어떤 이벤트가 발생하는가?\n if event.type == pygame.QUIT: # 종료 이벤트이면?\n running = False # running 종료 \n\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n to_x -= character_speed\n elif event.key == pygame.K_RIGHT:\n to_x += character_speed\n\n if event.type == pygame.KEYUP: # 방향키를 떼면 멈춤\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n to_x = 0\n\n # 3. 게임 캐릭터 위치 정의\n character_x_pos += to_x\n\n if character_x_pos < 0:\n character_x_pos = 0\n elif character_x_pos > screen_width - character_width:\n character_x_pos = screen_width - character_width\n \n ddong_y_pos += ddong_speed\n\n if ddong_y_pos > screen_hight:\n ddong_y_pos = 0\n ddong_x_pos = random.randint(0, screen_width - ddong_width)\n\n # 4. 충돌 처리\n character_rect = character.get_rect()\n character_rect.left = character_x_pos # 실제 character위치 정보로 갱신\n character_rect.top = character_y_pos # 실제 character위치 정보로 갱신\n \n ddong_rect = ddong.get_rect()\n ddong_rect.left = ddong_x_pos # 위치가 고정이지만 한번이라도 위치값 반영이 있어야 아래 위치 체크 조건에 걸림. \n ddong_rect.top = ddong_y_pos\n\n if character_rect.colliderect(ddong_rect):\n print(\"충돌했어요\")\n running = False\n\n # 5. 화면에 그리기\n\n screen.blit(background, (0,0)) # 배경 그리기\n screen.blit(character, (character_x_pos, character_y_pos))\n screen.blit(ddong, (ddong_x_pos, ddong_y_pos))\n\n pygame.display.update() # 게임 화면을 다시 그리기 (화면 갱신)\n\npygame.quit() # 종료","sub_path":"pygame_basic/quiz.py","file_name":"quiz.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"273148943","text":"from numpy import *\ndef loadDataSet():\n return [ [1,3,4],[2,3,5],[1,2,3,5],[2,5]]\ndef createC1(dataSet):\n '''创建C1函数,C1是指把数据集中的所有元素分解开后放入一个冰冻的集合,就是说他们的类型是不可以改变的,\n 这样在可以做字典的key\n 构建初始候选项集的列表,即所有候选项集只包含一个元素,\n C1是大小为1的所有候选项集的集合'''\n C1=[ ]\n for transaction in dataSet:\n for item in transaction:\n if not [item] in C1:\n C1.append([item])\n\n C1.sort()\n return list(map(frozenset,C1))\n\ndef scanD(dataSet,Ck,minSupport):\n '''第一个参数,数据集,要求是集合类型的数据集,即列表里存放每个记录的集合形式如[{1,2},{1,3,4},{2,5,6}]'''\n # 函数的功能是计算Ck中的项集在数据集合D(记录或者transactions)中的支持度,\n # 返回满足最小支持度的项集的集合,和所有项集支持度信息的字典。\n ssCnt={}\n for tid in dataSet:\n for can in Ck:\n if can.issubset(tid):\n # issubset就是子集是否包含于父集\n if ssCnt.get(can) == None:\n # 字典的get()函数\n ssCnt[can]=1\n else:\n ssCnt[can]+=1\n numItems=float(len(dataSet))\n retList=[]\n supportData={ }\n for key in ssCnt:\n # 计算支持度\n support=ssCnt[key]/numItems\n if support>=minSupport:\n retList.insert(0,key)\n # 插入到首项\n supportData[key]=support\n return retList,supportData\n\ndef aprioriGen(Lk,k):\n '''由初始候选项集的集合Lk生成新的生成候选项集,\n k表示生成的新项集中所含有的元素个数'''\n retList=[]\n lenLk=len(Lk)\n for i in range(lenLk):\n for j in range(i+1,lenLk):\n # 此处k-2的意思是总取到这列数的倒数第二位,以保证除最后一个元素,其他元素都相等,这样算出来的集合具有唯一性\n # 否则可能出现多次相同的集合(那样之后还需要过滤)\n L1=list(Lk[i])[:k-2]\n L2=list(Lk[j])[:k-2]\n L1.sort()\n L2.sort()\n if L1==L2:\n retList.append(Lk[i]|Lk[j])\n # 添加L1和L2的并集\n return retList\ndef apriori(dataSet,minSupport=0.5):\n C1=createC1(dataSet)\n # 创建只含单个元素的冰冻集合的列表\n D=list(map(set,dataSet))\n # 将数据集集合化,每个交易记录(每行)都成为一个集合\n L1,supportData=scanD(D,C1,minSupport)\n # 过滤出来 满足最小支持度的单个元素的冰冻集合 的列表,以及key为各个冰冻集合和值为支持度的字典\n L=[L1]#将L1作为列表的第一个元素放入L列表中\n k=2 #下一次产生的冰冻集合 列表 是含有两个元素的\n while len(L[k-2])>0 :#当当前列表内容不为空的时候,每次k增加时候,列表取到下一个元素\n Ck=aprioriGen(L[k-2],k) #产生含k个元素的冰冻集合的列表\n Lk,supK=scanD(D,Ck,minSupport)#过滤含k个元素的满足条件的冰冻集合 ,放入列表,第二个是计算含k个元素的冰\n # 冻集合的支持度并放入字典\n supportData.update(supK)#将上步产生的字典加入到支持度字典中\n L.append(Lk)#将含k个元素的冰冻集合的列表 当作元素添加到L列表中\n k+=1\n return L,supportData\n\ndef generateRules(L,supportData,minConf=0.7):\n '''生成关联规则函数'''\n bigRuleList=[]\n for i in range(1,len(L)):\n for freqSet in L[i]:\n H1=[frozenset([item]) for item in freqSet]\n # print('===================H1================')\n # print(H1)\n if (i>1):\n rulesFromConseq(freqSet,H1,supportData,bigRuleList,minConf)\n else:\n calcConf(freqSet,H1,supportData,bigRuleList,minConf)\n return bigRuleList\ndef calcConf(freSet,H,supportData,brl,minconf=0.7):\n prunedH=[]\n for conseq in H:\n conf=supportData[freSet]/supportData[freSet-conseq]\n if conf >= minconf:\n print(freSet-conseq,'-->',conseq,'conf :',conf)\n brl.append((freSet-conseq,conseq,conf))\n prunedH.append(conseq)\n # print('======================测试线========================================')\n # print(prunedH)\n return prunedH\ndef rulesFromConseq(freqSet,H,supportData,brl,minConf=0.7):\n m=len(H[0])\n # print(m)\n if len(freqSet)> m+1 :\n Hmp1=aprioriGen(H,m+1)\n # print(Hmp1)\n Hmp1=calcConf(freqSet,Hmp1,supportData,brl,minConf)\n if len(Hmp1)>1:\n rulesFromConseq(freqSet,Hmp1,supportData,brl,minConf)\n\n\n\nif __name__==\"__main__\":\n # dataSet=loadDataSet()\n # # print(dataSet)\n # # c1=createC1(dataSet)\n # # print(c1)\n # # D=list(map(set,dataSet))\n # # print(D)\n # # L1,supportData=scanD(D,c1,0.5)\n # # print(L1,supportData)\n # # l=[L1]\n # # print(l)\n # L,supportData=apriori(dataSet,minSupport=0.5)\n # # print(L)\n # # print(L[0])\n # # print(L[1])\n # # print(L[2])\n # # print(L[3])\n # # print(L)\n # # print(aprioriGen(L[0],2))\n # # L,supportData=apriori(dataSet,minSupport=0.7)\n # # print(L)\n # rules=generateRules(L,supportData,minConf=0.5)\n # print(len(rules))\n fr=open('H:\\IDM下载\\机器学习实战pdf\\MLiA_SourceCode\\machinelearninginaction\\Ch11\\mushroom.dat')\n mushDataSet=[line.split() for line in fr.readlines()]\n L,supportData=apriori(mushDataSet,minSupport=0.3)\n\n for item in L[2]:\n if item.intersection('2'):\n # 支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算\n print(item)\n for item in L[1]:\n if item.intersection('2'):\n print(item)","sub_path":"Machine_Learning/apriori.py","file_name":"apriori.py","file_ext":"py","file_size_in_byte":5975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"320654762","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 12 21:40:27 2018\n\n@author: owen\n\"\"\"\n\nclass Solution:\n def findReplaceString(self, S, indexes, sources, targets):\n \"\"\"\n :type S: str\n :type indexes: List[int]\n :type sources: List[str]\n :type targets: List[str]\n :rtype: str\n \"\"\"\n n=len(indexes)\n res=\"\"\n last=0\n dmap={}\n for i in range(n):\n dmap[indexes[i]]=(sources[i],targets[i])\n indexes.sort()\n \n for i in range(n):\n if last 0\n # BoxMode.XYWH_ABS -> 1\n register_coco_instances(name, {\"bbox_mode\":1}, json_file, image_root)\n\n MetadataCatalog.get(\"custom_train\").thing_classes = [\"콜라\", \n \"몬스터\", \n \"박카스\", \n \"칠성사이다\",\n \"파워에이드\",\n \"토레타\",\n \"광동옥수수수염차\",\n \"펩시\",\n \"cu블루레몬에이드\",\n \"포도봉봉\",\n \"갈아만든배\",\n \"top더블랙\",\n \"top마스터라떼\",\n \"top스위트아메리카노\",\n \"비타500\"]\n\n custom_train_metadata = MetadataCatalog.get(\"custom_train\")\n custom_val_metadata = MetadataCatalog.get(\"custom_val\")\n custom_test_metadata = MetadataCatalog.get(\"custom_test\")\n \n\n","sub_path":"dataset/register_custom_dataset.py","file_name":"register_custom_dataset.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"445143813","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Aug 14 21:05:11 2021\r\n\r\n@author: tanvv\r\n\"\"\"\r\n\r\nfrom flask import Flask, render_template, request\r\nfrom flask_cors import cross_origin\r\n#import jsonify\r\n#import requests\r\nimport pickle\r\nimport numpy as np\r\n#import sklearn\r\n#from sklearn.preprocessing import StandardScaler\r\napp = Flask(__name__)\r\nmodel = pickle.load(open('dt_model.pkl', 'rb'))\r\n#model = pickle.load(r\"C:\\Users\\tanvv\\OneDrive\\Documents\\practice projects\\dt_model.pkl\", \"rb\")\r\n@app.route('/',methods=['GET'])\r\n@cross_origin()\r\ndef Home():\r\n return render_template('index.html')\r\n\r\n@app.route(\"/predict\", methods = [\"GET\", \"POST\"])\r\n@cross_origin()\r\ndef predict():\r\n if request.method == \"POST\":\r\n \r\n sepal_length = float(request.form[\"sepal_length\"])\r\n sepal_width = float(request.form[\"sepal_width\"])\r\n petal_length = float(request.form[\"petal_length\"])\r\n petal_width = float(request.form[\"petal_width\"])\r\n y_pred = [[sepal_length,sepal_width,petal_length,petal_width]]\r\n model = pickle.load(open('dt_model.pkl', 'rb'))\r\n prediction=model.predict(y_pred)\r\n categories = ['iris-setosa','iris-versicolor','iris-virginica']\r\n prediction = categories[prediction[0]]\r\n return render_template('index.html',prediction_text=\"The type of Iris flower is : {}\".format(prediction))\r\n return render_template(\"index.html\")\r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\nif __name__==\"__main__\":\r\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"582052342","text":"# coding: utf-8\n__author__ = 'liuyf'\n__date__ = '2018/10/7 19:56'\n\nCLOUDCONFIG = {\n # 云name\n \"cloud_name_list\": ['aliyun', 'baidu', 'ksyun'],\n\n # 云bucket\n \"cloud_bucket_list\": [\n {'cloud_name': 'aliyun', 'area_name': 'qingdao', 'storage_type': 'standard',\n 'bucket_name': 'shaoly-aliyun-qingdao', 'endpoint': 'http://oss-cn-qingdao.aliyuncs.com'},\n {'cloud_name': 'aliyun', 'area_name': 'shanghai', 'storage_type': 'standard',\n 'bucket_name': 'shaoly-aliyun-shanghai', 'endpoint': 'http://oss-cn-shanghai.aliyuncs.com'},\n {'cloud_name': 'ksyun', 'area_name': 'beijing', 'storage_type': 'standard',\n 'bucket_name': 'ks3test-bj', 'endpoint': 'ks3-cn-beijing.ksyun.com'}\n ],\n\n # 云账户(子账号,ksyun不是)\n \"cloud_account_list\": [\n {\"cloud_name\": \"aliyun\",\n \"accesskey_id\": \"your-ak-here\",\n \"accesskey_secret\": \"your-sk-here\",\n \"endpoint\": \"http://oss-cn-beijing.aliyuncs.com\",\n \"bucket_name\": \"shaoly-aliyun-beijing\"\n },\n {\"cloud_name\": \"ksyun\",\n \"accesskey_id\": \"your-ak-here\",\n \"accesskey_secret\": \"your-sk-here\",\n \"endpoint\": \"ks3-cn-beijing.ksyun.com\",\n \"bucket_name\": \"ks3test-bj\"\n }\n ],\n\n # 云定价\n \"cloud_price_list\": [\n # 标准存储\n {'cloud_name': 'aliyun',\n 'storage_type': 'standard',\n 'storage': 0.148, # 标准存储:0.148元/GB/月\n 'download': 0.5, # 下载流量:0.5元/GB\n 'request': 0.01, # 请求费用:0.01元/万次\n 'retrieve': 0, # 数据取回费用\n 'lowmonth': 0, # 最短存储期限为0个月\n },\n {'cloud_name': 'baidu',\n 'storage_type': 'standard',\n 'storage': 0.128,\n 'download': 0.6,\n 'request': 0.01,\n 'retrieve': 0,\n 'lowmonth': 0,\n },\n {'cloud_name': 'ksyun',\n 'storage_type': 'standard',\n 'storage': 0.17,\n 'download': 0.56,\n 'request': 0.01,\n 'retrieve': 0, # 数据取回费用\n 'lowmonth': 0, # 最短存储期限为0个月\n },\n\n # 低频存储\n {'cloud_name': 'aliyun',\n 'storage_type': 'low',\n 'storage': 0.08,\n 'download': 0.5,\n 'request': 0.1,\n 'retrieve': 0.0325, # 数据取回费用0.0325元/GB\n 'lowmonth': 1, # 最短存储期限为1个月\n },\n {'cloud_name': 'baidu',\n 'storage_type': 'low',\n 'storage': 0.08,\n 'download': 0.6,\n 'request': 0.25,\n 'retrieve': 0.03,\n 'lowmonth': 1,\n },\n\n # # 冷存储\n # {'cloud_name': 'baidu',\n # 'storage_type': 'cold',\n # 'storage': 0.048,\n # 'download': 0.6,\n # 'request': 0.5,\n # 'retrieve': 0.15,\n # 'lowmonth': 3,\n # }\n ],\n}\n","sub_path":"jcs_proxy/config/cloud_config.py","file_name":"cloud_config.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"385408362","text":"import time\nimport sys\n\nif __name__ == \"__main__\":\n SUNDAY = 6\n SATURDAY = 5\n\n print(\"When's Weekend?\")\n\n today = time.localtime().tm_wday\n\n if today == SUNDAY:\n print(\"Today.\")\n sys.exit()\n\n d = SATURDAY - today\n\n if (d == 0):\n print(\"Today.\")\n elif (d == 1):\n print(\"Tomorrow.\")\n elif (d == 2):\n print(\"In two days.\")\n else:\n print(\"Too far away.\")\n","sub_path":"Philosophy/When'sWeekend/Lambda.py","file_name":"Lambda.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"597340196","text":"from __future__ import annotations\n\nfrom copy import deepcopy\nfrom typing import TYPE_CHECKING\n\nimport pycls.core.builders as builders\nimport pycls.core.logging as logging\nimport torch\nimport torch.nn as nn\nfrom pycls.core.config import cfg\nfrom pycls.core.setup import model2cuda\nfrom pycls.quantization.hw_quant_op import QuantOps\nfrom pycls.quantization.quant_op import QConv2d, QConvBn2d, QLinear\nfrom pycls.quantization.quantizer import QuantizedModel\nfrom pycls.quantization.shift_fake_quantizer import ShiftFakeQuantize\nfrom pycls.quantization.shift_observer import (\n HistogramShiftObserver,\n MinMaxShiftObserver,\n MovingAvgMinMaxShiftObserver,\n)\nfrom torch.nn.modules.pooling import AdaptiveAvgPool2d\nfrom torch.nn.quantized.modules.functional_modules import FloatFunctional\nfrom torch.quantization.observer import HistogramObserver, MinMaxObserver\n\nif TYPE_CHECKING:\n from torch.nn import Module\n from torch.utils.data import DataLoader\n\nlogger = logging.get_logger(__name__)\n\n\ndef get_observer(method: str):\n observer = None\n if \"min_max\" == method:\n observer = MinMaxObserver\n elif \"mm_shift\" == method:\n observer = MinMaxShiftObserver\n elif \"avg_mm_shift\" == method:\n observer = MovingAvgMinMaxShiftObserver\n elif \"histogram\" == method:\n observer = HistogramObserver\n elif \"hist_shift\" == method:\n observer = HistogramShiftObserver\n else:\n raise AttributeError(\"Not supported\")\n return observer\n\n\ndef _model_equivalence(\n model_1: Module,\n model_2: Module,\n rtol=1e-05,\n atol=1e-08,\n num_tests=100,\n input_size=(1, 3, 32, 32),\n):\n for _ in range(num_tests):\n x = torch.rand(size=input_size)\n y1 = model_1(x)\n y2 = model_2(x)\n if not torch.allclose(y1, y2, rtol=rtol, atol=atol, equal_nan=False):\n print(\"Model equivalence test sample failed: \")\n print(y1)\n print(y2)\n return False\n\n return True\n\n\ndef fuse_network(model: Module, with_bn=False, debug=False):\n fused_model = deepcopy(model)\n if with_bn:\n fused_model.train()\n else:\n fused_model.eval()\n fused_model.fuse_model(cfg.QUANTIZATION.ACT_FUSION)\n # Model and fused model should be equivalent.\n if debug:\n model.eval()\n fused_model.eval()\n assert _model_equivalence(\n model_1=model,\n model_2=fused_model,\n rtol=1e-02,\n atol=1e-04,\n num_tests=100,\n input_size=(1, 3, 224, 224),\n ), \"Fused model is not equivalent to the original model!\"\n return fused_model\n\n\n@torch.no_grad()\ndef calibrate_model(model: QuantizedModel, loader: DataLoader, use_cuda=True):\n model.eval()\n for inputs, _ in loader:\n if use_cuda:\n inputs = inputs.cuda()\n _ = model(inputs)\n\n\ndef _quantize_model4qat(model: Module, method: str):\n import numpy as np\n from torch.nn.intrinsic.modules.fused import ConvBn2d\n from torch.quantization.quantization_mappings import get_default_qat_module_mappings\n\n quantized_model = QuantizedModel(model_fp32=model)\n\n observer = get_observer(method)\n quantization_config = torch.quantization.QConfig(\n activation=ShiftFakeQuantize.with_args(\n observer=observer,\n quant_min=0,\n quant_max=int(np.exp2(cfg.QUANTIZATION.QAT.ACT_BITWIDTH) - 1),\n dtype=torch.quint8,\n qscheme=torch.per_tensor_symmetric,\n reduce_range=False,\n ),\n weight=ShiftFakeQuantize.with_args(\n observer=HistogramShiftObserver,\n quant_min=-int(np.exp2(cfg.QUANTIZATION.QAT.WEIGHT_BITWIDTH - 1)),\n quant_max=int(np.exp2(cfg.QUANTIZATION.QAT.WEIGHT_BITWIDTH - 1) - 1),\n dtype=torch.qint8,\n qscheme=torch.per_tensor_symmetric,\n reduce_range=False,\n ),\n )\n quantized_model.qconfig = quantization_config\n\n mapping = get_default_qat_module_mappings()\n if cfg.QUANTIZATION.QAT.TRAIN_SHIFT_BIAS_QUANTIZATION:\n mapping[nn.Conv2d] = QConv2d\n mapping[ConvBn2d] = QConvBn2d\n mapping[nn.Linear] = QLinear\n\n quantized_model = torch.quantization.prepare_qat(\n quantized_model, mapping, inplace=True\n )\n\n if cfg.QUANTIZATION.QAT.TRAIN_SAME_SCALE4SKIP:\n quantized_model.postprocess_skip()\n return quantized_model\n\n\ndef _copy_fake_quant(src: QuantizedModel, dest: QuantizedModel):\n for s, d in zip(src.modules(), dest.modules()):\n if isinstance(s, ShiftFakeQuantize) and isinstance(d, ShiftFakeQuantize):\n d.activation_post_process = s.activation_post_process\n d.zero_point = s.zero_point\n\n\ndef get_last_postprocess_before(model: Module, module: Module):\n rev_modules = list(model.modules())\n for mod in reversed(rev_modules[: rev_modules.index(module)]):\n if isinstance(mod, (QConv2d, QConvBn2d, QLinear, FloatFunctional)):\n return mod.activation_post_process\n\n\ndef quantize_network_for_qat(model: QuantizedModel):\n model.train()\n model = fuse_network(model, cfg.QUANTIZATION.QAT.WITH_BN)\n\n assert (\n len(cfg.QUANTIZATION.METHOD) == 1\n ), \"When testing QAT, only one quantization method is supported.\"\n model = _quantize_model4qat(model, cfg.QUANTIZATION.METHOD[0])\n if cfg.QUANTIZATION.QAT.TRAIN_SHIFT_AVG_POOL:\n head = model.model_fp32.head\n prev_post_process = get_last_postprocess_before(model.model_fp32, head.avg_pool)\n head.avg_pool = QuantOps[AdaptiveAvgPool2d].from_trained_op(prev_post_process)\n\n model = model2cuda(model)\n ema = deepcopy(model)\n _copy_fake_quant(model, ema)\n loss_fun = builders.build_loss_fun().cuda()\n\n logger.info(f\"QAT Model:\\n {model}\")\n logger.info(f\"QAT EMA Model:\\n {ema}\")\n return model, ema, loss_fun\n","sub_path":"pycls/core/quantization_utils.py","file_name":"quantization_utils.py","file_ext":"py","file_size_in_byte":5858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"615946928","text":"import torch\nimport intel_extension_for_pytorch as ipex\nimport unittest\nimport copy\nfrom torch.testing._internal.common_utils import TestCase\n\nclass TestOptimizer(TestCase):\n\n def non_fused_lamb(self, param, exp_avg, exp_avg_sq, grad, step, beta1, beta2, lr, weight_decay, eps):\n bias_correction1 = 1 - beta1 ** step\n bias_correction2 = 1 - beta2 ** step\n # Decay the first and second moment running average coefficient\n exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1)\n exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)\n adam_step = (exp_avg / bias_correction1) / ((exp_avg_sq / bias_correction2).sqrt() + eps)\n if weight_decay != 0:\n adam_step.add_(param, alpha=weight_decay)\n weight_norm = param.norm(p=2)\n rtw_norm = adam_step.norm(p=2)\n true_ratio = weight_norm / rtw_norm\n param.add_(adam_step, alpha=-lr * true_ratio)\n\n def non_fused_adagrad(self, param, grad, state_sum, step, lr, weight_decay, lr_decay, eps):\n if weight_decay != 0:\n grad = grad.add(param, alpha=weight_decay)\n clr = lr / (1 + (step - 1) * lr_decay)\n state_sum.addcmul_(grad, grad, value=1)\n std = state_sum.sqrt().add_(eps)\n param.addcdiv_(grad, std, value=-clr)\n\n\n def test_lamb(self):\n fused = torch.ops.torch_ipex.lamb_fused_step\n non_fused = self.non_fused_lamb\n\n # fused fp32 args\n param = torch.randn(80, 100)\n grad = torch.randn(80, 100)\n exp_avg = torch.randn(80, 100).abs()\n exp_avg_sq = torch.randn(80, 100).abs()\n trail = torch.Tensor()\n\n # fused bf16 params\n param2, trail2 = torch.ops.torch_ipex.split_float_bfloat16(param)\n grad2 = grad.bfloat16()\n exp_avg2 = exp_avg.clone()\n exp_avg_sq2 = exp_avg_sq.clone()\n\n # non-fused fp32 params\n param3 = param.clone()\n grad3 = grad.clone()\n exp_avg3 = exp_avg.clone()\n exp_avg_sq3 = exp_avg_sq.clone()\n\n step = 10\n beta1 = 0.8\n beta2 = 0.9\n learning_rate = 0.1\n weight_decay = 0.3\n eps = 0.001\n\n fused(param, exp_avg, exp_avg_sq, grad, trail, step, beta1, beta2, learning_rate, weight_decay, eps)\n fused(param2, exp_avg2, exp_avg_sq2, grad2, trail2, step, beta1, beta2, learning_rate, weight_decay, eps)\n non_fused(param3, exp_avg3, exp_avg_sq3, grad3, step, beta1, beta2, learning_rate, weight_decay, eps)\n\n # compare fused and non-fused\n self.assertEqual(param, param3)\n self.assertEqual(exp_avg, exp_avg3)\n self.assertEqual(exp_avg_sq, exp_avg_sq3)\n\n # compare fused fp32 and fused bf16\n self.assertEqual(param, param2.float(), rtol=1e-4, atol=1e-1)\n self.assertEqual(exp_avg, exp_avg2.float(), rtol=1e-4, atol=1e-1)\n self.assertEqual(exp_avg_sq, exp_avg_sq2.float(), rtol=1e-4, atol=1e-1)\n\n def test_adagrad(self):\n fused = torch.ops.torch_ipex.adagrad_fused_step\n non_fused = self.non_fused_adagrad\n\n # fused fp32 args\n param = torch.randn(80, 100)\n grad = torch.randn(80, 100)\n state_sum = torch.randn(80, 100).abs()\n trail = torch.Tensor()\n\n # fused bf16 args\n param2, trail2 = torch.ops.torch_ipex.split_float_bfloat16(param)\n grad2 = grad.bfloat16()\n state_sum2 = state_sum.clone()\n\n # non-fused fp32 args\n param3 = param.clone()\n grad3 = grad.clone()\n state_sum3 = state_sum.clone()\n trail3 = torch.randn(80, 100).clone()\n\n step = 10\n learning_rate = 0.1\n weight_decay = 0.3\n lr_decay = 0.01\n eps = 0.001\n\n fused(param, grad, state_sum, trail, step, learning_rate, weight_decay, lr_decay, eps)\n fused(param2, grad2, state_sum2, trail2, step, learning_rate, weight_decay, lr_decay, eps)\n non_fused(param3, grad3, state_sum3, step, learning_rate, weight_decay, lr_decay, eps)\n\n # compare fused fp32 vs non-fused fp32\n self.assertEqual(param, param3)\n self.assertEqual(state_sum, state_sum3)\n # compare fused fp32 vs fused bf16 fused\n self.assertEqual(param, param2.float(), rtol=1e-4, atol=1e-1)\n self.assertEqual(state_sum, state_sum2.float(), rtol=1e-4, atol=1e-1)\n\n def _test_split_sgd(self, param, grad, param2, trail, grad2):\n packed_add = torch.ops.torch_ipex.packed_add\n non_fused = self.non_fused_adagrad\n\n learning_rate = 0.1\n\n param.add_(grad, alpha=-learning_rate)\n packed_add(param2, trail, grad2, alpha=-learning_rate)\n\n # compare fp32 vs bf16 fused\n self.assertEqual(param, param2.float(), rtol=1e-4, atol=1e-1)\n\n def test_split_sgd(self):\n # contiguous case\n # fp32 args\n param = torch.randn(80, 100)\n grad = torch.randn(80, 100)\n # bf16 args\n param2, trail = torch.ops.torch_ipex.split_float_bfloat16(param)\n grad2 = grad.bfloat16()\n self._test_split_sgd(param, grad, param2, trail, grad2)\n\n # transposed case\n # fp32 args\n param = torch.randn(80, 100).t().contiguous().t()\n grad = torch.randn(80, 100).t().contiguous().t()\n # bf16 args\n param2, trail = torch.ops.torch_ipex.split_float_bfloat16(param)\n grad2 = grad.bfloat16().t().contiguous().t()\n self._test_split_sgd(param, grad, param2, trail, grad2)\n\n # sliced-out case\n # fp32 args\n base_param = torch.randn(80, 100)\n base_grad = torch.randn(80, 100)\n param = base_param[10:20, 10:20]\n grad = base_grad[10:20, 10:20]\n # bf16 args\n param2, trail = torch.ops.torch_ipex.split_float_bfloat16(base_param)\n param2 = param2[10:20, 10:20]\n trail = trail[10:20, 10:20]\n grad2 = base_grad.bfloat16()[10:20, 10:20]\n self._test_split_sgd(param, grad, param2, trail, grad2)\n\nif __name__ == '__main__':\n test = unittest.main()\n","sub_path":"tests/cpu/test_optimizer.py","file_name":"test_optimizer.py","file_ext":"py","file_size_in_byte":5994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"490813813","text":"# -*- coding: utf-8 -*-\n# @Author: Andre Goncalves\n# @Date: 2018-11-13 08:37:27\n# @Last Modified by: Andre Goncalves\n# @Last Modified time: 2019-05-29 16:33:20\nimport numpy as np\nimport pandas as pd\nfrom design import DatasetMTL\nfrom sklearn.datasets import make_classification\n\n\nclass ArtificialClassificationDatasetMTL(DatasetMTL):\n \"\"\"\n Implement an MTL Artificial Classification dataset generator.\n The generated data is mainly to test MTL methods' recovery capabilities.\n \"\"\"\n\n def __init__(self, nb_tasks, nb_samples, dimension, nb_useless_vars=1):\n \"\"\"\n Args:\n nb_tasks (int): number of tasks\n nb_samples (int): number of sample per task\n dimension (int): problem dimension (all tasks have the same dim)\n nb_useless_vars (int): number of unrelated variables to be added to design matrix\n \"\"\"\n assert nb_samples > 0\n assert dimension > 0\n assert nb_tasks > 0\n assert nb_useless_vars < dimension\n\n self.nb_tasks = nb_tasks\n self.nb_samples = nb_samples\n self.dimension = dimension\n self.data = None\n self.train_split = 0.7\n self.unique_values_categ = None\n\n self.y_eps = 0.5\n self.wg1_eps = 0.5\n self.wg2_eps = 0.7\n self.alpha_group_1 = 0.8\n self.alpha_group_2 = 1.0\n self.nb_useless_vars = nb_useless_vars\n\n def prepare_data(self):\n \"\"\"\n Generate synthetic dataset.\n \"\"\"\n self.data = {'train': {'x': list(),\n 'y': list(),\n 'sample_id': list(),\n 'censor_flag': list(),\n 'svv_time': list()},\n 'test': {'x': list(),\n 'y': list(),\n 'sample_id': list(),\n 'censor_flag': list(),\n 'svv_time': list()},\n 'db_names': list(),\n 'true_w': dict()}\n\n self.column_names = ['X_{}'.format(d + 1) for d in range(self.dimension)]\n self.column_dtypes = [np.dtype(np.float32) for d in range(self.dimension)]\n\n for t in range(self.nb_tasks):\n\n xt, yt = make_classification(n_samples=self.nb_samples,\n n_features=self.dimension,\n n_informative=2, n_redundant=2)\n\n # number of training samples\n ntr = int(self.nb_samples * self.train_split)\n\n # encapsulate into a DataFrame object\n xtr = pd.DataFrame(xt[0:ntr, :], columns=self.column_names)\n ytr = pd.DataFrame(yt[0:ntr], columns=('Y',))\n\n # encapsulate into a DataFrame object\n xts = pd.DataFrame(xt[ntr:, :], columns=self.column_names)\n yts = pd.DataFrame(yt[ntr:], columns=('Y',))\n\n # organize it into a dictionary\n self.data['train']['x'].append(xtr)\n self.data['train']['y'].append(ytr)\n self.data['train']['sample_id'].append(None)\n self.data['train']['censor_flag'].append(None)\n self.data['train']['svv_time'].append(None)\n\n self.data['test']['x'].append(xts)\n self.data['test']['y'].append(yts)\n self.data['test']['sample_id'].append(None)\n self.data['test']['censor_flag'].append(None)\n self.data['test']['svv_time'].append(None)\n\n self.data['db_names'].append('Task %d' % (t))\n\n def shuffle_data(self):\n '''Shuffle and re-split the data into training and test '''\n\n ntasks = len(self.data['train']['x'])\n\n for t in range(ntasks):\n # pool the data from old train/test splits\n x = np.vstack((self.data['train']['x'][t],\n self.data['test']['x'][t]))\n\n y = np.vstack((self.data['train']['y'][t],\n self.data['test']['y'][t]))\n\n # number of training samples\n ntr = int(self.train_split * x.shape[0])\n ids = np.random.permutation(x.shape[0]) # shuffle data\n\n # split between train and test\n self.data['train']['x'][t] = x[ids[:ntr], :]\n self.data['test']['x'][t] = x[ids[ntr:], :]\n\n self.data['train']['y'][t] = y[ids[:ntr]]\n self.data['test']['y'][t] = y[ids[ntr:]]\n\n def get_data(self):\n '''Return dataset structure. '''\n if self.data is None:\n raise ValueError('Must call \\'prepare\\' data first.')\n else:\n return self.data\n\n def get_nb_tasks(self):\n \"\"\" Return the number of tasks in the dataset. \"\"\"\n return len(self.data['db_names'])\n","sub_path":"datasets/ArtificialClassificationDatasetMTL.py","file_name":"ArtificialClassificationDatasetMTL.py","file_ext":"py","file_size_in_byte":4800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"208773783","text":"\"\"\"\"\nTiming functions to show profile performance\n\"\"\"\nimport argparse\nimport os\nfrom timeit import default_timer as timer\nimport datetime as dt\nfrom pymongo import MongoClient\n\ntiming_filename = 'out.txt'\n\n\ndef timing_wrapper(func):\n \"\"\" \n Timing decorator\n \"\"\"\n def inner(*args, **kwargs):\n start = timer()\n result = func(*args, **kwargs)\n stop = timer()\n with open(timing_filename, 'a') as fout:\n fout.write('Function: %s , Time: %s , Records Processed: %s\\n' % (func.__name__,\n dt.timedelta(\n seconds=stop-start),\n len(list(result))))\n return result\n return inner\n\n\ndef parse_cmd_arguments():\n \"\"\"\n Parse command-line arguments\n \"\"\"\n parser = argparse.ArgumentParser(description='Read data files.')\n parser.add_argument('-c', '--customer',\n help='customer data file', required=True)\n parser.add_argument('-p', '--product',\n help='product data file', required=True)\n parser.add_argument(\n '-r', '--rental', help='rental data file', required=True)\n parser.add_argument(\n '-o', '--output', help='output text file', required=True)\n\n return parser.parse_args()\n\n\nclass MongoDBConnection():\n \"\"\" \n MongoDB Connection\n \"\"\"\n\n def __init__(self, host='127.0.0.1', port=27017):\n \"\"\" be sure to use the ip address not name for local windows\"\"\"\n self.host = host\n self.port = port\n self.connection = None\n\n def __enter__(self):\n self.connection = MongoClient(self.host, self.port)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.connection.close()\n\n\n@timing_wrapper\ndef query_products(col):\n \"\"\"\n Return Products found\n \"\"\"\n query_is_available = {\"quantity_available\": {\"$gt\": 0}}\n return col.find(query_is_available)\n\n\n@timing_wrapper\ndef query_rentals(col_cust, col_prod, col_rent):\n \"\"\"\n Return customer data\n \"\"\"\n return_data = []\n for e in col_rent.find():\n cust = col_cust.find_one({\"user_id\": e[\"user_id\"]})\n prod = col_prod.find_one({\"product_id\": e[\"product_id\"]})\n return_data.append('Customer %s rented %s.' %\n (cust['name'], prod['description']))\n return return_data\n\n\ndef print_mdb_collection(collection_name):\n \"\"\"\n Return collection names\n \"\"\"\n for doc in collection_name.find():\n print(doc)\n\n\ndef main():\n \"\"\"\n Runs program in main\n \"\"\"\n\n args = parse_cmd_arguments()\n\n global timing_filename\n timing_filename = args.output\n if os.path.isfile(timing_filename):\n os.remove(timing_filename)\n\n mongo = MongoDBConnection()\n\n with mongo:\n # mongodb database; it all starts here\n db = mongo.connection.media\n\n # customer.csv\n db_cust = db[\"customers\"]\n db_cust.drop()\n db_cust_data = list()\n with open(args.customer, 'r', encoding=\"utf8\", errors='ignore') as f:\n for line in f.readlines()[1:]:\n record = line.rstrip('\\n').split(',')\n if len(record) == 6:\n # user_id,name,address,zip_code,phone_number,email\n db_cust_data.append({\"user_id\": record[0],\n \"name\": record[1],\n \"address\": record[2],\n \"zip_code\": record[3],\n \"phone_number\": record[4],\n \"email\": record[5]})\n db_cust.insert_many(db_cust_data)\n\n print('Read customer data.')\n\n # product.csv\n db_prod = db[\"product\"]\n db_prod.drop()\n db_prod_data = list()\n with open(args.product, 'r', encoding=\"utf8\", errors='ignore') as f:\n for line in f.readlines()[1:]:\n record = line.rstrip('\\n').split(',')\n if len(record) == 4:\n # product_id,description,product_type,quantity_available\n db_prod_data.append({\"product_id\": record[0],\n \"description\": record[1],\n \"product_type\": record[2],\n \"quantity_available\": int(record[3])})\n db_prod.insert_many(db_prod_data)\n\n print('Read product data.')\n\n # rental.csv\n db_rent = db[\"rental\"]\n db_rent.drop()\n db_rent_data = list()\n with open(args.rental, 'r', encoding=\"utf8\", errors='ignore') as f:\n for line in f.readlines()[1:]:\n record = line.rstrip('\\n').split(',')\n if len(record) == 2:\n # product_id,user_id\n db_rent_data.append({\"product_id\": record[0],\n \"user_id\": record[1]})\n db_rent.insert_many(db_rent_data)\n\n print('Read rental data.')\n\n print('Queried available products.')\n\n print('Queried rentals.')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"students/alex_w/lesson10/assignment/src/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":5375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"509113898","text":"from django.urls import path\nfrom .views import index,reservation,contact,blog,about\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nurlpatterns = [\n path('',index, name= 'index'),\n path (\"Reservation\",reservation,name= 'reservation'),\n path (\"Contact\",contact,name= 'contact'),\n path (\"Blog\",blog,name= 'blog'),\n path (\"About\",about,name= 'about'),\n]\nurlpatterns += staticfiles_urlpatterns()\n","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"621152717","text":"import numpy as np\nfrom NeuralNet import NeuralNet\nfrom Bird import Bird\n\n\nclass Population:\n\n def __init__(self, inp, pop_size=150):\n self.generation = 1\n self.members = []\n self.previous = []\n self.best_ten = [None] * 10\n self.pop_size = pop_size\n self.seed(inp)\n \n def seed(self, starting_in):\n for i in range(0, self.pop_size):\n starting_pos = 100 + i\n starting_in[0] = starting_pos\n nn = NeuralNet(1, 4, starting_in, 1)\n self.members.append(Bird(230, starting_pos, nn))\n # self.members.append(nn)\n\n def reseed(self, starting_in):\n self.members = self.select()\n for i in range(len(self.members)):\n self.members[i].y = 200 + i\n\n for i in range(10, len(self.members)):\n self.mutate(self.members[i])\n \n for i in range(10, len(self.members) - 1):\n self.crossover(self.members[i], self.members[i + 1])\n\n def select(self):\n new_pop = []\n best = sorted(self.previous, key=lambda bird: bird.alive, reverse=True)\n total = 0\n\n for bird in best:\n total += (bird.alive * bird.pipes_passed)\n\n for itm in range(len(self.best_ten)):\n for bird in best:\n if not self.best_ten[itm]:\n self.best_ten[itm] = bird\n\n if self.best_ten[itm].pipes_passed < bird.pipes_passed:\n self.best_ten[itm] = bird\n break\n\n [new_pop.append(Bird(230, 0, bird.nn)) for bird in self.best_ten]\n\n if total > 0:\n weights = [(bird.alive * bird.pipes_passed)/total for bird in best]\n for i in range(self.pop_size - 10):\n index = 0\n r = np.random.random()\n while r > 0:\n r = r - weights[index]\n index += 1\n new_pop.append(Bird(230, 0, best[index].nn))\n else:\n for i in range(10, self.pop_size):\n new_pop.append(Bird(230, 0, best[i].nn))\n\n return new_pop\n\n def mutate(self, member):\n for m in member.nn.theta:\n for n in m: \n if np.random.random() > 0.9:\n n = 2 * np.random.random() - 1\n \n def crossover(self, member1, member2):\n for n in range(len(member1.nn.theta[0])):\n if np.random.random() > 0.9:\n temp1 = member1.nn.theta[:,n]\n member1.nn.theta[:,n] = member2.nn.theta[:,n]\n member2.nn.theta[:,n] = temp1\n","sub_path":"GeneticAlgorithm.py","file_name":"GeneticAlgorithm.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"488500030","text":"__author__ = 'traveloka'\nimport copy\n\nfrom common.util.PriorityQueue import PriorityQueue\n\n\nclass ConnectedGraph(object):\n \"\"\"\n vertices in list of integer or string\n #edges in dict; vertices as key; vertices X distance as value\n\n \"\"\"\n def __init__(self, vertices, edges):\n self.vertices = vertices\n self.edges = edges\n\n def find_shortest_path(self, source):\n \"\"\"\n :type source: str\n :param source:\n :return:\n cost: dict (city:str -> time_cost:int)\n transport:\n \"\"\"\n max_dist = 10000000000\n # dict \n transport = dict()\n # dict \n cost = dict()\n # dict \n previous = dict()\n # dict \n visited = dict()\n pq = PriorityQueue()\n\n previous[source] = source\n cost[source] = 0\n transport[source] = [(0, [])]\n visited[source] = False\n\n for city in self.vertices:\n if city != source:\n cost[city] = max_dist\n transport[city] = []\n previous[city] = None\n visited[city] = False\n pq.put(city, cost[city])\n\n while pq.size() > 0:\n city = pq.deque()\n visited[city] = True\n mode_list = self.edges[city]\n for mode in mode_list:\n next_city = mode.destination\n if not visited[next_city]:\n relative_cost = mode.cost()\n global_cost = cost[next_city]\n alternative_cost = cost[city]+relative_cost\n if alternative_cost < global_cost:\n cost[next_city] = alternative_cost\n previous[next_city] = city\n pq.put(next_city, cost[next_city])\n for trans in transport[city]:\n current_cost = trans[0]\n new_mode_list = copy.deepcopy(trans[1])\n new_mode_list.append(mode)\n transport[next_city].append((current_cost+mode.cost(), new_mode_list))\n temp_map = dict()\n temp_list = list()\n for trx in transport[next_city]:\n temp_map['_'.join(x.origin+'_'+x.destination for x in trx[1])] = trx\n for key in temp_map.keys():\n temp_list.append(temp_map[key])\n temp_list.sort(cmp=lambda x, y: x[0]-y[0])\n transport[next_city] = temp_list[:3]\n return cost, previous, transport\n","sub_path":"common/util/ConnectedGraph.py","file_name":"ConnectedGraph.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"386244156","text":"# This is where you build your AI for the Chess game.\n\nfrom joueur.base_ai import BaseAI\nimport random\n\n\nclass AI(BaseAI):\n \"\"\" The basic AI functions that are the same between games. \"\"\"\n\n def get_name(self):\n \"\"\" This is the name you send to the server so your AI will control the\n player named this string.\n\n Returns\n str: The name of your Player.\n \"\"\"\n\n return \"Chess Python Player\" # REPLACE THIS WITH YOUR TEAM NAME\n\n def start(self):\n \"\"\" This is called once the game starts and your AI knows its playerID\n and game. You can initialize your AI here.\n \"\"\"\n\n # replace with your start logic\n\n def game_updated(self):\n \"\"\" This is called every time the game's state updates, so if you are\n tracking anything you can update it here.\n \"\"\"\n\n # replace with your game updated logic\n\n def end(self, won, reason):\n \"\"\" This is called when the game ends, you can clean up your data and\n dump files here if need be.\n\n Args:\n won (bool): True means you won, False means you lost.\n reason (str): The human readable string explaining why you won or\n lost.\n \"\"\"\n\n # replace with your end logic\n\n def run_turn(self):\n \"\"\" This is called every time it is this AI.player's turn.\n\n Returns:\n bool: Represents if you want to end your turn. True means end your\n turn, False means to keep your turn going and re-call this\n function.\n \"\"\"\n\n # Here is where you'll want to code your AI.\n\n # We've provided sample code that:\n # 1) prints the board to the console\n # 2) prints the opponent's last move to the console\n # 3) prints how much time remaining this AI has to calculate moves\n # 4) makes a random (and probably invalid) move.\n\n # 1) print the board to the console\n self.print_current_board()\n\n # 2) print the opponent's last move to the console\n if len(self.game.moves) > 0:\n print(\"Opponent's Last Move: '\" + self.game.moves[-1].san + \"'\")\n\n # 3) print how much time remaining this AI has to calculate moves\n print(\"Time Remaining: \" + str(self.player.time_remaining) + \" ns\")\n\n # 4) make a random (and probably invalid) move.\n random_piece = random.choice(self.player.pieces)\n random_file = chr(ord(\"a\") + random.randrange(8))\n random_rank = random.randrange(8) + 1\n random_piece.move(random_file, random_rank)\n\n return True # to signify we are done with our turn.\n\n def print_current_board(self):\n \"\"\"Prints the current board using pretty ASCII art\n Note: you can delete this function if you wish\n \"\"\"\n\n # iterate through the range in reverse order\n for r in range(9, -2, -1):\n output = \"\"\n if r == 9 or r == 0:\n # then the top or bottom of the board\n output = \" +------------------------+\"\n elif r == -1:\n # then show the ranks\n output = \" a b c d e f g h\"\n else: # board\n output = \" \" + str(r) + \" |\"\n # fill in all the files with pieces at the current rank\n for file_offset in range(0, 8):\n # start at a, with with file offset increasing the char\n f = chr(ord(\"a\") + file_offset)\n current_piece = None\n for piece in self.game.pieces:\n if piece.file == f and piece.rank == r:\n # then we found the piece at (file, rank)\n current_piece = piece\n break\n\n code = \".\" # default \"no piece\"\n if current_piece:\n # the code will be the first character of their type\n # e.g. 'Q' for \"Queen\"\n code = current_piece.type[0]\n\n if current_piece.type == \"Knight\":\n # 'K' is for \"King\", we use 'N' for \"Knights\"\n code = \"N\"\n\n if current_piece.owner.id == \"1\":\n # the second player (black) is lower case.\n # Otherwise it's uppercase already\n code = code.lower()\n\n output += \" \" + code + \" \"\n\n output += \"|\"\n print(output)\n","sub_path":"Joueur.py/games/chess/ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":4632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"636389038","text":"# -*- coding: UTF-8 -*-\r\nimport xgboost as xgb\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import scale\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom xgboost.sklearn import XGBClassifier\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\n# 加载数据\r\ndef load_data():\r\n white_sample = pd.read_csv('../../data/white_train_feature_label.csv')\r\n black_sample = pd.read_csv('../../data/black_train_feature_label.csv')\r\n\r\n # white_train = white_sample.sample(n=500, random_state=np.random.seed())\r\n # black_train = black_sample.sample(n=350, random_state=np.random.seed())\r\n\r\n frames = [white_sample, black_sample]\r\n train_data = pd.DataFrame(pd.concat(frames))\r\n label = train_data['label'].copy()\r\n\r\n del train_data['id']\r\n del train_data['label']\r\n # del train_data['unrepeated_x_count']\r\n # del train_data['x_count_ratio']\r\n # del train_data['unrepeated_y_count']\r\n # del train_data['y_count_ratio']\r\n # del train_data['unrepeated_xy_count']\r\n # del train_data['xy_count_ratio']\r\n # del train_data['sample_time']\r\n\r\n return train_data, label\r\n\r\n\r\n# 自定义评价函数\r\ndef customed_score(preds, dtrain):\r\n label = dtrain.get_label()\r\n pred = [int(i >= 0.5) for i in preds]\r\n confusion_matrixs = confusion_matrix(label, pred)\r\n recall = float(confusion_matrixs[1][1]) / float(confusion_matrixs[1][1]+confusion_matrixs[1][0])\r\n precision = float(confusion_matrixs[1][1]) / float(confusion_matrixs[1][1]+confusion_matrixs[0][1])\r\n F = -5*precision*recall/(2*precision+3*recall)\r\n return 'FSCORE', float(F)\r\n\r\n\r\n# 交叉验证,返回训练好的模型\r\ndef xgboost_cv(alg, train_data, label):\r\n\r\n dtrain = xgb.DMatrix(train_data.values, label=label.values)\r\n param = alg.get_xgb_params()\r\n cvresult = xgb.cv(param, dtrain, num_boost_round=alg.get_params()['n_estimators'], nfold=5,\r\n feval=customed_score, early_stopping_rounds=50, show_progress=False)\r\n print(cvresult)\r\n print('树的个数为:%d'%(cvresult.shape[0]))\r\n alg.set_params(n_estimators=cvresult.shape[0])\r\n\r\n alg.fit(train_data, label, eval_metric=customed_score)\r\n\r\n feat_imp = pd.Series(alg.booster().get_fscore()).sort_values(ascending=False)\r\n feat_imp.plot(kind='bar', title='Feature Importances')\r\n plt.ylabel('Feature Importance Score')\r\n alg.booster().save_model('../../xgb.model')\r\n plt.show()\r\n return alg\r\n\r\n\r\n# 使用训练好的模型进行预测\r\ndef predict(alg):\r\n predict_sample = pd.read_csv('../../data/predict_feature.csv')\r\n predict_id = predict_sample['id'].copy()\r\n predict_id = pd.DataFrame(predict_id)\r\n del predict_sample['id']\r\n # del predict_sample['unrepeated_x_count']\r\n # del predict_sample['x_count_ratio']\r\n # del predict_sample['unrepeated_y_count']\r\n # del predict_sample['y_count_ratio']\r\n # del predict_sample['unrepeated_xy_count']\r\n # del predict_sample['xy_count_ratio']\r\n # del predict_sample['sample_time']\r\n y = alg.predict_proba(predict_sample)\r\n predict_id['prob'] = y[:, 1]\r\n res = predict_id.sort_values(by='prob')\r\n res.iloc[0:20000].id.to_csv('../../submission.txt', header=None, index=False)\r\n\r\n\r\n # ress = res[res['prob'] < 0.5]\r\n # ress = ress.sort_values(by='id')\r\n # ress.id.to_csv('../../submission.txt', index=False, index_label=False)\r\n\r\n ress = pd.read_csv('../../submission.txt', names=['id'])\r\n ress = ress.sort_values(by='id')\r\n ress.id.to_csv('../../submission.txt', header=None, index=False)\r\n\r\n\r\n# 主函数\r\ndef run():\r\n xgb1 = XGBClassifier(\r\n learning_rate=0.01,\r\n n_estimators=1000,\r\n max_depth=6,\r\n min_child_weight=1,\r\n gamma=0,\r\n reg_lambda=1,\r\n subsample=0.78,\r\n colsample_bytree=0.52,\r\n objective='binary:logistic',\r\n nthread=8,\r\n scale_pos_weight=1,\r\n seed=0)\r\n\r\n train_data, label = load_data()\r\n xgb1 = xgboost_cv(xgb1, train_data, label)\r\n predict(xgb1)\r\n\r\nif __name__ == '__main__':\r\n run()","sub_path":"gbdt_train.py","file_name":"gbdt_train.py","file_ext":"py","file_size_in_byte":4050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"603937156","text":"import datetime\nimport json\nimport magic\nimport os\nimport random\nimport time\nimport uuid\nimport yaml\nimport numpy as np\nimport tensorflow as tf\n\nfrom flask import Flask, request, jsonify, render_template\nfrom forms import ImageForm\nfrom PIL import Image\nfrom scipy.misc import imread, imresize\n\nconfig = yaml.safe_load(open(\"config.yml\"))\n\ndef _load_taxon_ids(taxa_file):\n taxon_ids = []\n with open(taxa_file) as f:\n for line in f:\n iter, taxon_id = line.rstrip().split(\": \")\n taxon_ids.append(int(taxon_id))\n return taxon_ids\nTENSORFLOW_TAXON_IDS = _load_taxon_ids(\"taxa.txt\")\n\napp = Flask(__name__)\napp.secret_key = config[\"app_secret\"]\n\nUPLOAD_FOLDER = \"static/\"\n\ngraph = None\nsess = tf.Session()\nwith sess.as_default():\n # Load in the graph\n graph_def = tf.GraphDef()\n with open('optimized_model-3.pb', 'rb') as f:\n graph_def.ParseFromString(f.read())\n sess.graph.as_default()\n tf.import_graph_def(graph_def, name='')\n graph = sess.graph\n\nsess.graph.finalize()\n\n# Get the input and output operations\ninput_op = graph.get_operation_by_name('images')\ninput_tensor = input_op.outputs[0]\noutput_op = graph.get_operation_by_name('Predictions')\noutput_tensor = output_op.outputs[0]\n\ndef write_logstash(image_file, image_uuid, file_path, request_start_datetime, request_start_time, mime_type):\n request_end_time = time.time()\n request_time = round((request_end_time - request_start_time) * 1000, 6)\n logstash_log = open('log/logstash.log', 'a')\n log_data = {'@timestamp': request_start_datetime.isoformat(),\n 'uuid': image_uuid,\n 'duration': request_time,\n 'mime_type': mime_type,\n 'client_ip': request.access_route[0],\n 'filename': image_file.filename,\n 'image_size': os.path.getsize(file_path)}\n json.dump(log_data, logstash_log)\n logstash_log.write(\"\\n\")\n logstash_log.close()\n\n@app.route('/', methods=['GET', 'POST'])\ndef classify():\n form = ImageForm()\n if request.method == 'POST':\n request_start_datetime = datetime.datetime.now()\n request_start_time = time.time()\n image_file = form.image.data\n extension = os.path.splitext(image_file.filename)[1]\n image_uuid = str(uuid.uuid4())\n file_path = os.path.join(UPLOAD_FOLDER, image_uuid) + extension\n image_file.save(file_path)\n\n mime_type = magic.from_file(file_path, mime=True)\n # attempt to convert non jpegs\n if mime_type != 'image/jpeg':\n im = Image.open(file_path)\n rgb_im = im.convert('RGB')\n file_path = os.path.join(UPLOAD_FOLDER, image_uuid) + '.jpg'\n rgb_im.save(file_path)\n\n # Load in an image to classify and preprocess it\n # Note that we are using imread to convert to RGB in case the image was\n # in grayscale or something: https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imread.html\n # Also note that imread is deprecated and we should probably switch to\n # imageio, and/or use PIL to perform this RGB conversion ourselves\n image = imread(file_path, False, 'RGB')\n image = imresize(image, [299, 299])\n image = image.astype(np.float32)\n image = (image - 128.) / 128.\n image = image.ravel()\n images = np.expand_dims(image, 0)\n\n # Get the predictions (output of the softmax) for this image\n preds = sess.run(output_tensor, {input_tensor : images})\n\n sorted_pred_args = preds[0].argsort()[::-1][:100]\n response_json = jsonify(dict({TENSORFLOW_TAXON_IDS[arg]: round(preds[0][arg] * 100, 6) for arg in sorted_pred_args}))\n write_logstash(image_file, image_uuid, file_path, request_start_datetime, request_start_time, mime_type)\n return response_json\n else:\n return render_template('home.html')\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=6006)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"145218202","text":"'''\nAuthor: Puffrora\nDate: 2021-11-21 19:19:47\nLastModifiedBy: Puffrora\nLastEditTime: 2021-11-21 19:48:49\n'''\n\nfrom typing import List\n\nclass Solution:\n def partitionLabels(self, s: str) -> List[int]:\n from collections import defaultdict\n\n pos_dict = defaultdict(list)\n\n for i, c in enumerate(s):\n if c not in pos_dict:\n pos_dict[c] = [i, i]\n else:\n pos_dict[c][1] = i\n \n pos_list = [v for v in pos_dict.values()]\n pos_list.sort(key=lambda x:(x[0], x[1]))\n\n cur_start, cur_end = pos_list[0]\n res = []\n for pos in pos_list:\n if pos[0] < cur_end:\n cur_end = max(cur_end, pos[1])\n elif pos[0] > cur_end:\n res.append(cur_end-cur_start+1)\n cur_start, cur_end = pos\n \n res.append(len(s)-cur_start)\n\n return res\n","sub_path":"Leetcode/leetcode763 划分字母区间.py","file_name":"leetcode763 划分字母区间.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"105911889","text":"# 4\n# 1 7\n#3 2 5 6\ninter=[int(n) for n in input().split(' ')]\nlatter=[int(n) for n in input().split(' ')]\nif len(inter)==1:\n print(inter[0])\nelse:\n tree=[]\n le=len(latter)\n root=latter[le-1]\n tree.append(root)\n \n","sub_path":"Code/CodeRecords/2432/60795/272044.py","file_name":"272044.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"387005996","text":"from asyncio import sleep\n\nfrom loader import bot\nfrom utils.dp_api.database import database\n\n\nasync def mailing(caption, item_type, item_category, photo, author_):\n type_ = item_type\n if type_ == \"Найдено\":\n type_ = \"Потеряно\"\n elif type_ == \"Потеряно\":\n type_ = \"Найдено\"\n results = await database.get_users(type_, item_category)\n for result in results:\n text = f\"Новый пост относящийся к твоей категории!\\n\\n\" \\\n f\"{item_type} -- {item_category}\\n\\n\"\n try:\n if photo:\n text += caption\n text += f\"\\n\\nКонтакты: {author_}\"\n await bot.send_photo(photo=photo, chat_id=result['author_id'], caption=text)\n await sleep(0.3)\n else:\n text += caption\n text += f\"\\n\\nКонтакты: {author_}\"\n await bot.send_message(chat_id=result['author_id'], text=text)\n await sleep(0.3)\n except Exception:\n pass\n","sub_path":"utils/misc/mailing.py","file_name":"mailing.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"421603085","text":"# -*- coding: utf8 -*-\n\nfrom beauty import config\nfrom beauty.config import feature_names\n\nfrom os import path\nfrom scipy.spatial import distance\nfrom imutils.face_utils import FaceAligner\nfrom PIL import Image, ImageDraw\nimport numpy as np\nimport cv2\nimport dlib\nimport face_recognition\nimport os\nimport time\n\n\ndef create_dir(outdir):\n if not path.exists(outdir):\n os.makedirs(outdir)\n\n\ndef create_pardir(outfile):\n outdir = path.dirname(outfile)\n create_dir(outdir)\n\n\ndef display_image(image):\n pimage = Image.fromarray(image)\n pdraw = ImageDraw.Draw(pimage)\n pimage.show()\n\n\ndef get_star_name(filepath):\n filename = path.basename(filepath)\n star_name = filename.split('.')[0]\n return star_name\n\n\ndef get_star_images(star_image_dir):\n signature = 'utils.get_star_images'\n image_files = []\n image_extensions = ['jfif', 'jpg', 'jpeg', 'png', 'JPG']\n # star_image_dir = config.star_image_dir\n for par_dir, dirnames, filenames in os.walk(star_image_dir):\n if len(filenames) == 0:\n continue\n for filename in filenames:\n is_image = False\n for image_extension in image_extensions:\n if filename.endswith(image_extension):\n is_image = True\n break\n if not is_image:\n print('%s:%s is not image' % (signature, filename))\n continue\n image_file = path.join(par_dir, filename)\n image_files.append(image_file)\n return image_files\n\n################################################################\n# server\n################################################################\n\n\ndef respond_failure(message):\n response = {\n 'data': {},\n 'code': 1,\n 'message': message,\n }\n return response\n\n\ndef respond_success(result):\n response = {\n 'data': result,\n 'code': 0,\n 'message': '',\n }\n return response\n\n\n################################################################\n# facial features and encoding\n################################################################\n\n\ndef get_aligned_face(image, verbose=False):\n signature = 'utils.get_aligned_face'\n start_time = time.time()\n predictor = face_recognition.api.pose_predictor_68_point\n aligner = FaceAligner(predictor, desiredFaceWidth=256)\n if verbose:\n duration = time.time() - start_time\n print('%s:initialize aligner=%.4fs' % (signature, duration))\n\n start_time = time.time()\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n face_locations = face_recognition.face_locations(image)\n if len(face_locations) == 0:\n return None\n face_location = face_locations[0]\n top, right, bottom, left = face_location\n rect = dlib.rectangle(left=left, top=top, right=right, bottom=bottom)\n if verbose:\n duration = time.time() - start_time\n print('%s:locate face=%.4fs' % (signature, duration))\n\n start_time = time.time()\n image = aligner.align(image, gray, rect)\n if verbose:\n duration = time.time() - start_time\n print('%s:align face=%.4fs' % (signature, duration))\n return image\n\ndef extract_features(image, verbose=False):\n pass\n\ndef extract_encoding(image, verbose=False):\n signature = 'utils.extract_encoding'\n image = get_aligned_face(image, verbose=verbose)\n if image is None:\n return None\n # display_image(image)\n\n start_time = time.time()\n face_encoding = face_recognition.face_encodings(image)[0]\n if verbose:\n duration = time.time() - start_time\n print('%s:encode face=%.4fs' % (signature, duration))\n return face_encoding\n\ndef extract_feature(image, save_image=False, verbose=False):\n signature = 'utils.extract_feature'\n start_time = time.time()\n predictor = face_recognition.api.pose_predictor_68_point\n aligner = FaceAligner(predictor, desiredFaceWidth=256)\n if verbose:\n duration = time.time() - start_time\n print('%s:predictor aligner=%.4fs' % (signature, duration))\n\n # extension = 'png'\n # line_width = 2\n # filename = path.basename(infile)\n # fields = filename.split('.')\n # outfile = path.join(config.star_face_dir, '%s.%s' % (fields[0], extension))\n # if path.isfile(outfile):\n # return\n\n # image = face_recognition.load_image_file(infile)\n # print(type(image), image.shape, image.dtype)\n start_time = time.time()\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n face_locations = face_recognition.face_locations(image)\n if len(face_locations) == 0:\n return None\n face_location = face_locations[0]\n top, right, bottom, left = face_location\n rect = dlib.rectangle(left=left, top=top, right=right, bottom=bottom)\n if verbose:\n duration = time.time() - start_time\n print('%s:face location=%.4fs' % (signature, duration))\n\n start_time = time.time()\n image = aligner.align(image, gray, rect)\n if verbose:\n duration = time.time() - start_time\n print('%s:align image=%.4fs' % (signature, duration))\n\n start_time = time.time()\n face_locations = face_recognition.face_locations(image)[:1]\n face_landmarks = face_recognition.face_landmarks(image, face_locations=face_locations)\n\n # TODO\n # face_encoding = face_recognition.face_encodings(image, known_face_locations=face_locations)[0]\n # print('face encoding', face_encoding.shape, face_encoding.dtype)\n\n face_location, face_landmark = face_locations[0], face_landmarks[0]\n if verbose:\n duration = time.time() - start_time\n print('%s:face landmark=%.4fs' % (signature, duration))\n\n start_time = time.time()\n # for feature_name in feature_names:\n # print('#%s=%d' % (feature_name, len(face_landmark[feature_name])))\n top, right, bottom, left = face_location\n # rescale location to include landmark\n half_width = (right - left) / 2.0\n half_height = (bottom - top) / 2.0\n center_x = (right + left) / 2.0\n center_y = (bottom + top) / 2.0\n scale_m = 1.0\n for feature_name in feature_names:\n for point_x, point_y in face_landmark[feature_name]:\n scale_x = abs((point_x - center_x) / half_width)\n scale_y = abs((point_y - center_y) / half_height)\n scale_m = max(scale_m, scale_x, scale_y)\n top = center_y - half_height * scale_m\n right = center_x + half_width * scale_m\n bottom = center_y + half_height * scale_m\n left = center_x - half_width * scale_m\n # face_location = top, right, bottom, left\n width = right - left\n height = bottom - top\n if verbose:\n duration = time.time() - start_time\n print('%s:rescale face location=%.4fs' % (signature, duration))\n\n start_time = time.time()\n face_feature = {}\n for feature_name in feature_names:\n feature = []\n for point_x, point_y in face_landmark[feature_name]:\n position_x = (point_x - left) / width\n position_y = (point_y - top) / height\n feature.extend([position_x, position_y])\n face_feature[feature_name] = feature\n location_rect = [\n (left, top),\n (right, top),\n (right, bottom),\n (left, bottom),\n (left, top)\n ]\n if verbose:\n duration = time.time() - start_time\n print('%s:extract features=%.4fs' % (signature, duration))\n\n if save_image:\n line_width = 2\n pimage = Image.fromarray(image)\n pdraw = ImageDraw.Draw(pimage)\n for feature_name in feature_names:\n pdraw.line(face_landmark[feature_name], width=line_width)\n pdraw.line(location_rect, width=line_width)\n pimage.show()\n # create_pardir(outfile)\n # pimage.save(outfile, extension)\n\n return face_feature\n\n################################################################\n# match star\n################################################################\n\ndef get_feature(face_feature, feature_names):\n feature = []\n for feature_name in feature_names:\n feature.extend(face_feature[feature_name])\n return feature\n\ndef search_star(face_feature, star_features, feature_names):\n face_feature = get_feature(face_feature, feature_names)\n best_star, best_dist = None, np.inf\n for star_name, star_feature in star_features.items():\n if star_feature == None:\n # print(star_name)\n continue\n star_feature = get_feature(star_feature, feature_names)\n dist = distance.euclidean(face_feature, star_feature)\n if dist < best_dist:\n best_dist = dist\n best_star = star_name\n # print('%s %.4f' % (best_star, best_dist))\n star_name = best_star.split('.')[0]\n return star_name, best_dist\n\n\n\n\n\n\n","sub_path":"beauty/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"7897635","text":"##################################### -PLS READ- ################################################################################################\r\n'''\r\n \r\n - I created a Youtube video that shows you exactly how to use this bot. I recommend you watch it by going to this link: https://youtu.be/v-Y1Eox3nf4\r\n\r\n - This bot is created in Python so to use it for yourself, go to any Python application and copy and paste this entire code.\r\n \r\n - If you want to learn how to create these type of bots for yourself you can take my course in web scraping to learn how. Here's the link: https://www.udemy.com/course/web-scraping-in-python-with-beautifulsoup-and-selenium/?referralCode=939EB64B8E029FCBBDEB\r\n\r\n'''\r\n\r\n##################################### -User Input- ################################################################################################\r\n\r\n#Input the URL between the commas of the body type of car you picked.\r\nurl = ''\r\n\r\n\r\n##################################### -Notes- ################################################################################################\r\n'''\r\n\r\n - There's a couple libraries you need to install first for this code to work.\r\n - 1. You have to install the BeautifulSoup library. I created a short 3-minute video on how to do this just use this link: https://www.youtube.com/watch?v=tv05NzizNtE&t=0s\r\n\r\n'''\r\n\r\n##################################### -Importing Necessary Libraries- ################################################################################################\r\n\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\n\r\n\r\n##################################### -Gets the HTML from Carpages- ##########################################################################################################\r\n\r\n#--Summary: The code below copies the HTML from Carpages into Python\r\n\r\n#Imports the HTML into python\r\npage = requests.get(url)\r\nsoup = BeautifulSoup(page.text, 'lxml')\r\n\r\n\r\n##################################### -Scraping the Car Postings- ##########################################################################################################\r\n\r\n#--Summary: The code below will go through each car posting and save the link, name, price, and color for each car in a dataframe\r\n\r\n#Creates an empty dataframe where the car information will go\r\ndf = pd.DataFrame({'Link':[''], 'Name':[''], 'Price':[''],'Distance':[''], 'Color':['']})\r\ncounter = 0\r\n\r\nwhile counter <= 10: \r\n #Gets the HTML of all the postings on the page\r\n postings = soup.find_all('div', class_ = 'media soft push-none rule')\r\n\r\n #This loop will then go through the HTML of each car posting and find the link, name, price, and color for each car\r\n for post in postings:\r\n link = post.find('a', class_ = 'media__img media__img--thumb').get('href')\r\n link_full = 'https://www.carpages.ca' +link\r\n name = post.find('h4', class_ = 'hN').text.strip()\r\n price = post.find('strong', class_ = 'delta').text.strip()\r\n distance = post.find_all('div', class_='grey l-column l-column--small-6 l-column--medium-4')[0].text\r\n color = post.find_all('div', class_ = 'grey l-column l-column--small-6 l-column--medium-4')[1].text.strip()\r\n #The link, name, price, and color for each car and is added to our dataframe \r\n df = df.append({'Link':link_full, 'Name':name, 'Price':price,'Distance':distance, 'Color':color}, ignore_index = True)\r\n \r\n #This chunck of code will loop through all the pages on Carpages until there are no more pages left with car postings\r\n try:\r\n next_page = soup.find_all('a', class_ = 'nextprev')[1].get('href')\r\n except:\r\n next_page = soup.find('a', class_ = 'nextprev').get('href')\r\n page = requests.get(next_page)\r\n soup = BeautifulSoup(page.text, 'lxml')\r\n counter +=1\r\n\r\n\r\n##################################### -Cleaning the Dataframe- ##########################################################################################################\r\n\r\n#--Summary: The code below just touches up the dataframe and cleans it a bit\r\n\r\ndf = df.iloc[1:,:]\r\n\r\n\r\n##################################### -Final Result- ##########################################################################################################\r\n\r\n#Displays the final dataframe\r\nprint(df)\r\n\r\n#To get a clearer view of this table, the code below will export it as an excel file, you just have to input the file location you want it saved\r\n#df.to_csv('A/File/Path/amazon_table.csv')\r\n\r\n\r\n\r\n","sub_path":"Carpages Bot.py","file_name":"Carpages Bot.py","file_ext":"py","file_size_in_byte":4521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"325745244","text":"\"\"\" Routines to support optional packages \"\"\"\nfrom distutils.version import LooseVersion\n\nfrom six import string_types\n\ntry:\n import nose\nexcept ImportError:\n have_nose = False\nelse:\n have_nose = True\n\nfrom .tripwire import TripWire\n\n\ndef _check_pkg_version(pkg, min_version):\n # Default version checking function\n if isinstance(min_version, string_types):\n min_version = LooseVersion(min_version)\n try:\n return min_version <= pkg.__version__\n except AttributeError:\n return False\n\n\ndef optional_package(name, trip_msg=None, min_version=None):\n \"\"\" Return package-like thing and module setup for package `name`\n\n Parameters\n ----------\n name : str\n package name\n trip_msg : None or str\n message to give when someone tries to use the return package, but we\n could not import it at an acceptable version, and have returned a\n TripWire object instead. Default message if None.\n min_version : None or str or LooseVersion or callable\n If None, do not specify a minimum version. If str, convert to a\n `distutils.version.LooseVersion`. If str or LooseVersion` compare to\n version of package `name` with ``min_version <= pkg.__version__``. If\n callable, accepts imported ``pkg`` as argument, and returns value of\n callable is True for acceptable package versions, False otherwise.\n\n Returns\n -------\n pkg_like : module or ``TripWire`` instance\n If we can import the package, return it. Otherwise return an object\n raising an error when accessed\n have_pkg : bool\n True if import for package was successful, false otherwise\n module_setup : function\n callable usually set as ``setup_module`` in calling namespace, to allow\n skipping tests.\n\n Examples\n --------\n Typical use would be something like this at the top of a module using an\n optional package:\n\n >>> from nibabel.optpkg import optional_package\n >>> pkg, have_pkg, setup_module = optional_package('not_a_package')\n\n Of course in this case the package doesn't exist, and so, in the module:\n\n >>> have_pkg\n False\n\n and\n\n >>> pkg.some_function() #doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n TripWireError: We need package not_a_package for these functions,\n but ``import not_a_package`` raised an ImportError\n\n If the module does exist - we get the module\n\n >>> pkg, _, _ = optional_package('os')\n >>> hasattr(pkg, 'path')\n True\n\n Or a submodule if that's what we asked for\n\n >>> subpkg, _, _ = optional_package('os.path')\n >>> hasattr(subpkg, 'dirname')\n True\n \"\"\"\n if callable(min_version):\n check_version = min_version\n elif min_version is None:\n check_version = lambda pkg: True\n else:\n check_version = lambda pkg: _check_pkg_version(pkg, min_version)\n # fromlist=[''] results in submodule being returned, rather than the top\n # level module. See help(__import__)\n fromlist = [''] if '.' in name else []\n exc = None\n try:\n pkg = __import__(name, fromlist=fromlist)\n except Exception as exc_:\n # Could fail due to some ImportError or for some other reason\n # e.g. h5py might have been checking file system to support UTF-8\n # etc. We should not blow if they blow\n exc = exc_ # So it is accessible outside of the code block\n else: # import worked\n # top level module\n if check_version(pkg):\n return pkg, True, lambda: None\n # Failed version check\n if trip_msg is None:\n if callable(min_version):\n trip_msg = 'Package %s fails version check' % min_version\n else:\n trip_msg = ('These functions need %s version >= %s' %\n (name, min_version))\n if trip_msg is None:\n trip_msg = ('We need package %s for these functions, but '\n '``import %s`` raised %s'\n % (name, name, exc))\n pkg = TripWire(trip_msg)\n\n def setup_module():\n if have_nose:\n raise nose.plugins.skip.SkipTest('No %s for these tests'\n % name)\n return pkg, False, setup_module\n","sub_path":"env/lib/python3.6/site-packages/nibabel/optpkg.py","file_name":"optpkg.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"313579660","text":"import Levenshtein as LV\r\nimport gensim\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.metrics.pairwise import cosine_similarity\r\n\"\"\"This script contains a single class which in turn, contains all 5 of the methods to be tested (as well as their \r\ninitialization functions.) The five methods are as follows:\r\n 1) Jacard Similarity between course descriptions \r\n 2) Leveshtein Distance between course names\r\n 3) Similarity of the average Word2Vec encoding of course descriptions\r\n 4) Similarity of the Doc2Vec encodings of course descriptions.\r\n 5) Similarity of the \"matrix\" encoding using the pretrained GloVe encodings.\r\n (The matrix encoding is a concatenation of 4 encoding vectors.\r\n 1) The average of all word vector encodings in the description.)\r\n 2) The average + 1 st dev of all vector encodings\r\n 3) A vector consisting of the max values of all vector encodings\r\n 4) A vector consisting of the min values of all vector encodings.\r\n \r\n The methods used to to call these are as follows:\r\n Jacard\r\n Lev\r\n WordSim\r\n DocSim\r\n GloveSim\r\n\"\"\"\r\n\r\nclass Similarities:\r\n \"\"\"This class takes in a training data frame that is used to train the word2vec and doc2vec embeddings. \r\n The 5 methods can the be called when passed the test data frame.\r\n Initialize this class with:\r\n trainDF - The dataframe used to train the embeddings. This will also be the dataframe from which\r\n the program will pull the course closest to the test course.\r\n Mode - Either \"All\" for initializing all 5 methods or \"Word\" for only initializing \"WordSim\"\r\n \"\"\"\r\n def __init__(self,trainDF,mode=\"All\"):\r\n self.GloveFail = False\r\n self.mode = mode\r\n #The input training data frame.\r\n\r\n self.trainDF = trainDF\r\n #Transforms the text strings from the descriptions into a list of list of words.\r\n self._initText()\r\n #Initializes and trains the word2vec embeddings.\r\n self._initWordVec()\r\n #Only initialize DocSim and GloveSim if required.\r\n if mode == \"All\":\r\n #Initializes and trains the doc2vec embeddigns.\r\n self._initDocVec()\r\n #Loads in the pretrained GloVe data.\r\n self._initGloveVec()\r\n #Build a dictionary containing the embeddings for each description. This make it so that the \r\n #the embedding functions only need to be called once for the test course which will then \r\n #be compared to the embeddings in this dictionary.\r\n self.VDF = {\"Word\":{},\"Doc\":{},\"Glove\":{}}\r\n self._BuildSims()\r\n \r\n \r\n def _initText(self):\r\n #Get text from descriptions. The variable is a nested list where the outer list represents\r\n #each description and the inner list is each word in that description.\r\n self.texts = []\r\n for index, row in self.trainDF.iterrows():\r\n self.texts.append(row['description'].split())\r\n print(\"Text initialized\")\r\n \r\n def _initWordVec(self):\r\n #Load the list of list consisting of the course descriptions into the word2vec model. Train the model\r\n self.WordVecModel = gensim.models.Word2Vec(self.texts,size=300,window=5,min_count=2,workers=4,iter=100)\r\n print(\"Word2Vec Model initialized\")\r\n def _initDocVec(self):\r\n #Initializes and trains the doc2vec embedding\r\n from gensim.models.doc2vec import Doc2Vec, TaggedDocument\r\n documents = []\r\n #Iterate through each course description and store each as a tagged docuent. Create list of \r\n #tagged documents.\r\n for i in range(len(self.texts)):\r\n documents.append(TaggedDocument(self.texts[i],[i]))\r\n #Train the doc2vec model with the tagged documents.\r\n self.DocVecModel = Doc2Vec(documents, vector_size=300, window=5, min_count=2, workers=4,epochs=100)\r\n print(\"Doc2Vec Model initialized\")\r\n def _initGloveVec(self):\r\n #Initializes the pre-trained GloVe model.\r\n import Setup\r\n import pickle\r\n import os\r\n #If the model has already been saved, import it from the pickle file and store to the variabe \"word_vectors\"\r\n if os.path.exists(Setup.gloveJar):\r\n with open(Setup.gloveJar,'rb') as f:\r\n glove = pickle.load(f)\r\n self.gloveModel = glove\r\n\r\n #If the model has not already been saved, call the api downloader to download the model.\r\n else:\r\n print(\"Downloading GloVe word embeddings with gensim...\")\r\n \"Maybe add an option to switch off pickle mode?\"\r\n try:\r\n import gensim.downloader as api\r\n glove = api.load(\"glove-wiki-gigaword-100\") \r\n\r\n #Once the model has been downloaded, save the word_vectors as a pickle file for later use.\r\n with open(Setup.gloveJar,'wb') as f:\r\n pickle.dump(glove,f)\r\n print(\"word vectors saved to .pkl file\")\r\n self.gloveModel = glove\r\n print(\"Glove model initialized\")\r\n except:\r\n print(\"Glove Sim model failed to download\")\r\n self.GloveFail = True\r\n #Allow word vectors to be accessed by other methods in the class.\r\n\r\n \r\n def Jacard(self,testDf,listCourse,inCourse):\r\n \"\"\"Calculates the Jacard similarity between two course descriptions.\r\n Inputs:\r\n testDF - The test dataframe consisting of columns ('index','description','preqNames',and 'school') with rows\r\n consisting of the course number indexes (all lowercase no colons.)\r\n a,b - each of these is a string representing the course number.\r\n Outputs:\r\n The Jacard similarity score scaled between 0 and 1.\r\n \"\"\"\r\n #Obtain the course descriptions for the two course indexes inputed into the function.\r\n A = self.trainDF['description'][listCourse]\r\n B = testDf['description'][inCourse]\r\n #Create a set of words for each description.\r\n setA = set(A.split())\r\n setB = set(B.split())\r\n \r\n #Count the number of words in set a that are also in set b.\r\n score = 0\r\n for a in setA:\r\n if a in setB:\r\n score +=1\r\n #Divide the number by the total length of both sets.\r\n return score/(len(setA.union(setB)))\r\n\r\n def Lev(self,testDf,listCourse,inCourse):\r\n \"\"\"Calculates the Levenshtein distance between two course names.\r\n Inputs:\r\n testDF - The test dataframe consisting of columns ('index','description','preqNames',and 'school') with rows\r\n consisting of the course number indexes (all lowercase no colons.)\r\n a,b - each of these is a string representing the course number.\r\n Outputs:\r\n The compliment of the normalized Levenshtein distance\r\n (The compliment is calculated by 1-(L/D) where L is the Levenshtein distance and D is the length of the \r\n longer of the two strings)\r\n This number is scaled between 0 and 1 where 1 represents a perfect match.\r\n \"\"\"\r\n #Obtain the couse names for the two courses provided\r\n A = self.trainDF['name'][listCourse]\r\n B = testDf['name'][inCourse]\r\n #Figure out the length of the longest course name.\r\n maxLen = max(len(A),len(B))\r\n #Calculate the compliment of the normalized Levenshtein distance. \r\n return 1-LV.distance(A,B)/maxLen \r\n \r\n def _WordSimAveVec(self,df,a):\r\n \"\"\"Calculates the a document embedding vector by taking the average of all word vectors in the document. This is\r\n a helper function to be used with the \"WordSim\" method.\r\n Inputs:\r\n testDF - A test dataframe consisting of columns ('index','description','preqNames',and 'school') with rows\r\n consisting of the course number indexes (all lowercase no colons.) \r\n a - A string representing the course number\r\n Output:\r\n A vector embedding representing the entire document.\r\n \"\"\"\r\n #Obtain the course description for the course provided and convert the string into a list of individual words.\r\n Description = df['description'][a].split()\r\n #Create a placeholder zero vector of the same size as the vector embedding.\r\n Vector = np.zeros(self.WordVecModel.layer1_size)\r\n wordCount = 0\r\n #Iterate over each word in the description.\r\n for word in Description:\r\n #If the word is in the trained vocabulary, obtain the word vector. \r\n #Continue to add the word vectors to the placeholder vector to get the running sum.\r\n if word in self.WordVecModel.wv.vocab:\r\n vector = self.WordVecModel.wv.get_vector(word)\r\n Vector +=vector\r\n #Keep track of how many word vectors (which were included in the vocabulary) were added.\r\n wordCount +=1\r\n #Calculate the mean by dividing the sum by the number of vectors.\r\n return Vector/wordCount\r\n \r\n def _BuildSims(self):\r\n \"\"\"Builds up the dictionary \"self.VDF\" to contain all of the document vector embeddings which are in \r\n the training dataset to act as a reference. This way, the references only need to be calculated once.\r\n The method will build up the dictionary using 3 \"columns\" - one for each word embedding if \"All\" mode\r\n was selected for initializing the class. If \"Word\" mode was selected, it will only build the dictionary\r\n for the \"WordSim\" method.\r\n Dictionary will be in the form VDF[Method][courseName]\r\n \"\"\"\r\n if self.mode == \"All\":\r\n #Iterate through all rows of the training dataframe.\r\n for index, _ in self.trainDF.iterrows():\r\n #Obtain the document embeddings for each method.\r\n wordVec = self._WordSimAveVec(self.trainDF,index)\r\n docVec = self._DocSim(self.trainDF,index)\r\n #Save the embeddings to a dictionary\r\n self.VDF[\"Word\"][index] = wordVec\r\n self.VDF[\"Doc\"][index] = docVec\r\n if self.GloveFail == False:\r\n gloveVec = self._GloveSim(self.trainDF,index)\r\n self.VDF[\"Glove\"][index] = gloveVec\r\n if self.mode == \"Word\":\r\n for index, _ in self.trainDF.iterrows():\r\n wordVec = self._WordSimAveVec(self.trainDF,index)\r\n self.VDF[\"Word\"][index] = wordVec\r\n \r\n \r\n def WordSim(self,testDF,listCourse,inCourse):\r\n \"\"\"Calculate the cosine similarity between two vectors where each vector represents a course\r\n description. Each vector is made by taking the average of each word vector that makes up the description. Average\r\n vectors are calculated by a helper method \"_WordSimAveVec\"\r\n Inputs:\r\n testDF - A test dataframe consisting of columns ('index','description','preqNames',and 'school') with rows\r\n consisting of the course number indexes (all lowercase no colons.) \r\n listCourse - A string containing the course number of the reference course in the trainSet\r\n inCourse - A string containing the course number of the input test course.\r\n \"\"\"\r\n #Obtain a single vector embedding for each course description (calculated by taking an average of each word \r\n #embedding that makes up each description)\r\n \r\n #Get the embedding from the dictionary for the list (reference) course\r\n aVec = self.VDF[\"Word\"][listCourse]\r\n #Calculate the embedding with the doc2Vec model.\r\n bVec = self._WordSimAveVec(testDF,inCourse)\r\n #Convert vectors to column vectors to be fed into the cosine_similarity function.\r\n A = np.expand_dims(aVec,0)\r\n B = np.expand_dims(bVec,0)\r\n #Calculate the cosine similarity between the two vectors.\r\n sim = cosine_similarity(A,B)\r\n return float(sim)\r\n \r\n def _DocSim(self,df,a):\r\n \"\"\"Calculate the cosine similarity between two document vectors.\r\n Inputs:\r\n testDF - A test dataframe consisting of columns ('index','description','preqNames',and 'school') with rows\r\n consisting of the course number indexes (all lowercase no colons.) \r\n a - A string representing the course number\"\"\"\r\n #Obtain the descriptions of the two input courses.\r\n textA = df['description'][a]\r\n #Obtain the document embedding vector for each description.\r\n vectorA = self.DocVecModel.infer_vector([textA], alpha=0.1, min_alpha=0.0001, steps=300)\r\n return vectorA\r\n \r\n def DocSim(self,testDF,listCourse,inCourse):\r\n \"\"\"Calculates a vector embedding for a course description using the doc2vec method.\r\n Inputs:\r\n testDF - A test dataframe consisting of columns ('index','description','preqNames',and 'school') with rows\r\n consisting of the course number indexes (all lowercase no colons.) \r\n listCourse - A string containing the course number of the reference course in the trainSet\r\n inCourse - A string containing the course number of the input test course.\r\n \"\"\"\r\n #Reference the VDF dictionary to get the doc embedding for the listCourse\r\n vectorA = self.VDF[\"Doc\"][listCourse]\r\n #Calculate the doc embedding for the input course\r\n vectorB = self._DocSim(testDF,inCourse)\r\n \r\n #Convert vectors to column vectors to be fed into the cosine_similarity function. \r\n A = np.expand_dims(vectorA,0)\r\n B = np.expand_dims(vectorB,0)\r\n #Calculate the cosine similarity between the two vectors.\r\n sim = cosine_similarity(A,B)\r\n return float(sim)\r\n \r\n\r\n def _GloveSim(self,testDf,a):\r\n \"\"\"Uses the word vectors from the pre-trained GloVe model to generate an array representing the document. \r\n Inputs:\r\n testDF - A test dataframe consisting of columns ('index','description','preqNames',and 'school') with rows\r\n consisting of the course number indexes (all lowercase no colons.) \r\n a - A string representing the course number\r\n Outputs:\r\n An array consistingof the mean, standard deviation, min and maximum of all word vector embeddings which \r\n make up the course description.\"\"\"\r\n #Obtain the course description for the given course number.\r\n doc = testDf['description'][a]\r\n #Iterate over each word in the document. For each word in the GloVe vocab, append the word vector to a list\r\n Vectors = []\r\n for word in doc:\r\n if word in self.gloveModel.vocab:\r\n vector = self.gloveModel.get_vector(word)\r\n Vectors.append(vector)\r\n #Turn the list of vectors into an array.\r\n Vectors = np.array(Vectors)\r\n \r\n #Calculate the mean, mean+1stdev, maximum, and minimum of this array (each operation reducing \r\n #the array to eliminate rows). Concatenate these 4 measures into one matrix to serve as an index for a \r\n #document.\r\n sd = np.std(Vectors,axis=0)\r\n a0 = np.average(Vectors,axis=0)\r\n asd = a0+sd\r\n amax = np.max(Vectors,axis=0)\r\n amin = np.amin(Vectors,axis=0)\r\n \r\n return np.stack((a0,asd,amax,amin),1)\r\n \r\n def GloveSim(self,testDf,listCourse,inCourse):\r\n \"\"\"Calculate the cosine similarity between two document arrays.\r\n Inputs:\r\n testDF - A test dataframe consisting of columns ('index','description','preqNames',and 'school') with rows\r\n consisting of the course number indexes (all lowercase no colons.) \r\n listCourse - A string containing the course number of the reference course in the trainSet\r\n inCourse - A string containing the course number of the input test course.\r\n Outputs\r\n Cosine similarity\"\"\"\r\n #Obtain the matrix representation of the document encoding for each description. Transpose the matricies\r\n \r\n #Obtain the embedding from the dictionary for the list course\r\n A = self.VDF['Glove'][listCourse].T\r\n #Calculate the embedding for the input course using the GloVe model.\r\n B = self._GloveSim(testDf,inCourse).T\r\n \r\n #Take the cosine similarity of these two matricies. This creates a 4x4 matrix where each row represents\r\n #one of the four categories (mean,stdev,max,min) of one course description and each column represents one of the four\r\n #of the other course description.\r\n sim = cosine_similarity(A,B)\r\n #The diagonal of this 4x4 matrix is a comparision of like categories across the two different course descriptions.\r\n #By taking the average of this diagonal, a similarity score can be obtained.\r\n result = np.average(np.diag(sim))\r\n return result\r\n \r\n \r\n\r\n# School Preq\r\n#Jacard 0.762222 0.497531\r\n#Lev 0.730000 0.475926\r\n#WordSim 0.820000 0.517284\r\n#DocSim 0.592222 0.444444\r\n#GloveSim 0.598889 0.503704\r\n \r\n","sub_path":"Similarities.py","file_name":"Similarities.py","file_ext":"py","file_size_in_byte":17423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"100704130","text":"from collections import defaultdict\r\nimport numpy as np\r\nimport math\r\nfrom utils import *\r\n\r\nclass KMeans:\r\n \"\"\"\r\n for implementation KMeans algorithms\r\n\r\n ______ Attribute:\r\n _num_clusters: num of clusters you want to start\r\n _clusters: list of Clusters\r\n _E: list of centroids - r_d vectors\r\n _S: overall similarity between Members and corresponding Clusters\r\n _data: list of Members\r\n _label_count: default dict - label: num of doc have that label\r\n _iteration: num of iteration runed\r\n\r\n ______ Methods:\r\n load_data(self, data_path)\r\n random_init(self, seed_value)\r\n compute_similarity(self, member, centroid)\r\n select_cluster_for(self, member)\r\n update_centroid_of(self, cluster)\r\n stopping_condition(self, criterion, threshold)\r\n compute_purity(self)\r\n compute_NMI(self)\r\n run(self, seed_value, criterion, threshold)\r\n \"\"\"\r\n def __init__(self, num_cluster):\r\n \"\"\"\r\n init Kmeans with (num_cluster) Clusters\r\n (without centroids, and Members)\r\n :param num_cluster: num of cluster that you wanna start\r\n \"\"\"\r\n self._num_cluster = num_cluster\r\n self._clusters = [Cluster() for _ in range(num_cluster)]\r\n self._E = []\r\n self._S = 0\r\n self._data = []\r\n\r\n\r\n def load_data(self, data_path, word_idfs_path):\r\n \"\"\"\r\n load data_tfidfs and words_idfs files\r\n in order to get model's data and label_count\r\n :param data_path: link to data_tf_idfs file\r\n :return: None\r\n \"\"\"\r\n def sparse_to_dense(sparse_r_d, vocab_size):\r\n \"\"\"\r\n transform r_d into vector that dims = vocab_size\r\n positions that in \"sparse r_d\" --> # 0\r\n else ---> = 0\r\n Eg. Form of sparse_r_d\r\n [14174:0.008788634650700206 13720:0.030925826829923748...]\r\n :param sparse_r_d: \"sparse r_d\" from file\r\n :param vocab_size: size of vocab\r\n :return: dense r_d vector\r\n \"\"\"\r\n r_d = [0.0 for _ in range(vocab_size)]\r\n indices_tfidfs = sparse_r_d.split()\r\n for index_tfidf in indices_tfidfs:\r\n index = int(index_tfidf.split(':')[0])\r\n tfidf = float(index_tfidf.split(':')[1])\r\n r_d[index] = tfidf\r\n\r\n #print(r_d)\r\n return np.array(r_d)\r\n\r\n #open full_precessed_data and words_idfs files\r\n with open(data_path) as f:\r\n d_lines = f.read().splitlines() #each row, each tfidf-data\r\n\r\n with open(word_idfs_path, 'rb') as f:\r\n vocab_size = len(f.read().splitlines())\r\n self._dims = vocab_size\r\n\r\n self._data = []\r\n self._label_count = defaultdict(int)\r\n\r\n #get label, doc_id, r_d vector from data_tfdifs files,\r\n #and put into self._data\r\n for d in d_lines:\r\n features = d.split('')\r\n label, doc_id = int(features[0]), int(features[1])\r\n self._label_count[label] +=1\r\n r_d = sparse_to_dense(features[2], vocab_size)\r\n self._data.append(Member(r_d, label, doc_id))\r\n\r\n print('Load data - Done!')\r\n\r\n def random_init(self, seed_value):\r\n \"\"\"\r\n random init centroid of each clusters\r\n Choose centroids randomly from data points.\r\n :param seed_value: random value to seed\r\n :return: None\r\n \"\"\"\r\n d = 0\r\n for cluster in self._clusters:\r\n d += 1\r\n np.random.seed(int(seed_value) + d)\r\n tmp = np.random.randint(len(self._data))\r\n cluster._centroid = self._data[tmp]._r_d\r\n\r\n\r\n def compute_similarity(self, member, centroid):\r\n \"\"\"\r\n this func use distance to compute similarity\r\n between member and centroid\r\n :param member: a Member object\r\n :param centroid: a r_d vector of Centroid\r\n :return: similarity = 1/Euclide_distance\r\n \"\"\"\r\n mem_r_d = np.array(member._r_d)\r\n cen_r_d = np.array(centroid)\r\n dis = np.linalg.norm(mem_r_d - cen_r_d) + 1e-12\r\n\r\n return 1./dis\r\n\r\n def select_cluster_for(self, member):\r\n \"\"\"\r\n select cluster - the most similar for member\r\n :return: max similarity of member and best fit cluster\r\n \"\"\"\r\n best_fit_cluster = None\r\n max_simimlarity = -1\r\n\r\n #find the best_fit cluster in self._clusters\r\n for cluster in self._clusters:\r\n similarity = self.compute_similarity(member, cluster._centroid)\r\n if similarity > max_simimlarity:\r\n best_fit_cluster = cluster\r\n max_simimlarity = similarity\r\n\r\n #add member to best fit cluster\r\n best_fit_cluster.add_member(member)\r\n\r\n return max_simimlarity\r\n\r\n def update_centroid_of(self, cluster):\r\n \"\"\"\r\n update centroid of cluster,\r\n :return None\r\n \"\"\"\r\n member_r_ds = np.array([member._r_d for member in cluster._members])\r\n\r\n #get mean of member_r_ds @@\r\n avg_rd = np.mean(member_r_ds, axis = 0)\r\n\r\n norm2_of_avg = np.linalg.norm(avg_rd)\r\n\r\n #nen centroid = avg_of_mem_rd/norm2_itself **\r\n new_centroid = avg_rd/norm2_of_avg\r\n\r\n cluster._centroid = new_centroid\r\n\r\n def stopping_condition(self, criterion, threshold):\r\n \"\"\"\r\n check the stopping_condition\r\n + max_iters: iters over threshold\r\n + centroid: centroids have changed so little\r\n + similarity: avg_similarity has increased so little\r\n\r\n :return: True/ False\r\n \"\"\"\r\n criteria = ['centroid', 'similarity', 'max_iters']\r\n assert criterion in criteria\r\n if criterion == 'max_iters':\r\n #num of iterations pass over threshold max_iters\r\n if self._iteration >= threshold:\r\n return True\r\n else:\r\n return False\r\n\r\n elif criterion == 'centroid':\r\n #centroids have changed so little\r\n E_new = [cluster._centroid() for cluster in self._clusters]\r\n E_new_minus_E = [centroid for centroid in E_new if centroid not in self._E]\r\n\r\n self._E = E_new #update _E\r\n\r\n #and check\r\n if len(E_new_minus_E) <= threshold:\r\n return True\r\n else:\r\n return False\r\n\r\n else:\r\n #minus to check\r\n new_S_minus_S = self._new_S - self._S\r\n self._S = self._new_S #update _S\r\n\r\n #and check:\r\n if new_S_minus_S <=threshold:\r\n return True\r\n else:\r\n return False\r\n\r\n def compute_purity(self):\r\n \"\"\"\r\n compute purity in order to valid clustering quality\r\n\r\n :return: purity of clustering\r\n = 1/len(data) * \\\r\n sigma_sum (max time that a label appear in a cluster)\r\n \"\"\"\r\n majoriry_sum = 0\r\n for cluster in self._clusters:\r\n member_labels = [member._label for member in cluster._members] #list of label in cluster\r\n max_count = max([member_labels.count(label) for label in range(20)]) #label that appear max times in cluster\r\n majoriry_sum += max_count\r\n\r\n return majoriry_sum *1./len(self._data)\r\n\r\n def compute_NMI(self):\r\n \"\"\"\r\n compute NMI (normalized mutual information)\r\n\r\n :return: NMI value of clustering\r\n \"\"\"\r\n #init values:\r\n I_value, H_omega, H_C, N = 0., 0., 0., len(self._data)\r\n\r\n #compute H_omega and I_value\r\n for cluster in self._clusters:\r\n wk = len(cluster._members)*1 #num of docs in cluster k\r\n H_omega += -wk/N * np.log10(wk/N)\r\n\r\n member_labels = [member._label for member in cluster._members] #list of label in cluster k\r\n for label in range(20):\r\n wk_cj = member_labels.count(label) *1 #num of mems in cluster k that have label j\r\n cj = self._label_count[label]\r\n I_value += wk_cj / N * np.log10(N * wk_cj / (wk * cj) + 1e-12)\r\n\r\n #compute H_C\r\n for label in range(20):\r\n cj = self._label_count[label] * 1\r\n H_C += -cj/N * np.log10(cj/N)\r\n\r\n return I_value*2/(H_omega + H_C)\r\n\r\n def run(self, seed_value, criterion, threshold):\r\n \"\"\"\r\n run KMeans\r\n :param seed_value: seed value to init clusters vs their centroids\r\n :param criterion: criterion for stopping\r\n :return: None\r\n \"\"\"\r\n #init centroids:\r\n self.random_init(seed_value)\r\n\r\n ######--Print init result!\r\n print(\"Init done!\")\r\n #####---\r\n\r\n #continually update clusters util convergence\r\n self._iteration = 0\r\n\r\n while True:\r\n print(\"--->iter: \", self._iteration, end = ' ')\r\n #reset clusters, retain only centroids\r\n for cluster in self._clusters:\r\n cluster.reset_members()\r\n\r\n #select cluster for members in _data\r\n self._new_S = 0\r\n for member in self._data:\r\n max_s = self.select_cluster_for(member)\r\n self._new_S += max_s\r\n\r\n #update centroids for clusters\r\n for cluster in self._clusters:\r\n self.update_centroid_of(cluster)\r\n\r\n #update num of iterations and check stopping condition\r\n self._iteration +=1\r\n if self.stopping_condition(criterion, threshold):\r\n break\r\n print('done')\r\n print(\"<3 <3 Done!!! <3 <3\")\r\n","sub_path":"[Section_2]KMeans/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":9650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"471738317","text":"#!/usr/bin/python3\n# bird_phylogenetics_setup.py by josh\n\nimport sys\nimport os\nimport glob\nimport re\n\nIDPattern = re.compile(\"^>(.+)$\")\nseqPattern = re.compile(\"^[ATGC*-]+$\")\n\nalignList = [os.path.basename(x) for x in glob.glob(\"./*_align.fasta\")]\n\nalignList.sort()\n\nprint(len(alignList))\n\nmasterTaxaList = []\n\nfor idx, alignment in enumerate(alignList):\n print(idx)\n inFile = open(alignment, \"r\")\n for line in inFile:\n line = line.strip()\n if IDPattern.match(line):\n taxon = line[1:].split(\"|\")[0]\n if taxon not in masterTaxaList:\n print(taxon)\n masterTaxaList.append(taxon)\n inFile.close()\n\nmasterTaxaList.sort()\nprint(masterTaxaList)\n\noutDirName = \"modified_aligns_for_phylo\"\n\nif not os.path.isdir(outDirName):\n os.makedirs(outDirName)\n\nmetaFile = open(\"retained_sequences_metadata_IMPORTANT.txt\", \"w\")\n\nfor idx, alignment in enumerate(alignList):\n print(idx)\n gene = alignment.replace(\"_align.fasta\", \"\")\n print(gene)\n hummerFound = 0\n seqDict = {}\n inFile = open(alignment, \"r\")\n for line in inFile:\n line = line.strip()\n if IDPattern.match(line):\n taxon = line[1:].split(\"|\")[0]\n # print(taxon)\n if taxon not in masterTaxaList:\n sys.exit(\"Error, taxon not recognised\")\n sequence = inFile.readline().strip()\n newSeq = \"\"\n for i in range(0, len(sequence), 3):\n codon = sequence[i:i+3]\n if codon == \"---\":\n pass\n elif codon.count(\"A\") + codon.count(\"G\") + codon.count(\"T\") + codon.count(\"C\") < 3:\n codon = \"---\"\n newSeq += codon\n if not seqPattern.match(newSeq):\n print(newSeq)\n sys.exit(\"Error, sequence not in expected format\")\n gapCount = newSeq.count(\"-\")\n species = \"_\".join([taxon.split(\"_\")[0][0], taxon.split(\"_\")[1]])\n if species == \"C_anna\":\n hummerFound = 1\n if species not in seqDict:\n seqDict[species] = [gapCount, newSeq, taxon]\n elif gapCount < seqDict[species][0]:\n seqDict[species] = [gapCount, newSeq, taxon]\n else:\n print(line)\n sys.exit(\"Error, line format not recognised\")\n inFile.close()\n speciesList = list(seqDict.keys())\n speciesList.sort()\n if len(speciesList) < 4:\n continue\n metaData = [gene] + [\":\".join([x, seqDict[x][2]]) for x in speciesList]\n metaFile.write(\"\\t\".join(metaData) + \"\\n\")\n print(len(speciesList), speciesList)\n outFileName = \"{}/{}_align.fasta\".format(outDirName, gene)\n print(outFileName)\n outFile = open(outFileName, \"w\")\n for species in speciesList:\n outFile.write(\">\" + species + \"\\n\")\n outFile.write(seqDict[species][1] + \"\\n\")\n outFile.close()\n\nmetaFile.close()\n\nquit()","sub_path":"bird_phylogenetics_setup.py","file_name":"bird_phylogenetics_setup.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"425233526","text":"\nfrom nltk.corpus import stopwords\nimport re\nfrom tokenizec import NlpTokenizer\nfrom tqdm import tqdm\n\n\nstop_words= stopwords.words('english')\n# import dectionary\ndictionary= open('words.txt').readlines()\n\nfor i in range(0,len(dictionary)):\n dictionary[i]= dictionary[i].strip().lower() \ndictionary=[x for x in dictionary if len(x)>1]\n\n# import stop words\nstop_words=open('stopwords.txt').readlines()\nfor i in range(len(stop_words)):\n stop_words[i]= stop_words[i].strip().lower() \n\n\nclass customized_stemmer():\n \n def sfx_stem(self,text,sfx):\n #print( text , sfx)\n reg_ex='('+sfx+')$' #create regular expression to be subtracted from the text\n l=len(sfx)\n if (text[-l-1]==text[-l-2] )and( text[-l-1] not in ['a','e','o','u','i','x','y','w'] )and (text[-l-3] in ['a','e','o','u','i']):\n #check doubled consonant like flipped\n return text[:-l-1]\n elif re.sub(reg_ex,'e',text) in dictionary and text[-l-1] not in ['a','e','o','u','i','x','y','w'] :\n #to check if there is removed vowel like \"taking\" \n return re.sub(reg_ex,'e',text)\n elif (text[-l-1]=='i' )and( text[-l-2] not in ['a','e','o','u','i'] and sfx not in['tion','tional']):\n #to check if there is consonant followed by y letter like studied\n return re.sub('('+'i'+sfx+')$','y',text)\n elif text[-l-1]=='y' and len(re.sub('('+sfx+')$','',text))<3 and re.sub('('+'y'+sfx+')$','ie',text) in dictionary :\n #to check if the y is from ie like die --> dying\n return re.sub('('+'y'+sfx+')$','ie',text)\n elif sfx=='s' and text[-l-2:-l] =='ie' and text[-l-3] not in ['a','e','o','u','i']:\n # for words ends with consonant and y that is changed to ie like accompany --> accompanies\n return re.sub('(ies)$','y',text) \n #rules for tion, tional \n elif sfx in ['tion','tional'] and text[-l-1:-l]=='a' and text[-l-2:-l]=='iz':\n # ize followed by tion or tional like authorize --> authorization\n return re.sub('('+'a'+sfx+')$','e',text) \n elif (sfx in ['tion','tional'] and text[-l-1:-l]=='a' ) :\n if text[-l-3:-l-1]=='ic':\n # ify followed by tion or tional like amplify --> amplification\n return re.sub('('+'ica'+sfx+')$','y',text) \n elif text[-l-3:-l-1]=='am': \n # ify followed by tion or tional like acclaim --> acclamation\n return re.sub('('+'ama'+sfx+')$','aim',text)\n else: return re.sub('('+sfx+')$','te',text)\n elif (sfx in ['tion','tional'] and text[-l-2:-l]=='ac'):\n # ify followed by tion or tional like liquefy --> liquefaction\n return re.sub('('+'ac'+sfx+')$','y',text) \n elif sfx in ['tion','tional'] and text[-l-3:-l] in ['cep','ump','duc','olu','osi']:\n # verbs like \n if text[-l-3:-l]==['cep']: return re.sub('('+'p'+sfx+')$','ive',text) #conceive --> conception\n elif text[-l-3:-l]=='ump': return re.sub('('+'p'+sfx+')$','e',text) #assume --> assumption\n elif text[-l-3:-l]=='duc': return re.sub('('+sfx+')$','e',text) #deduce --> deduction\n elif text[-l-3:-l]=='olu': return re.sub('('+'u'+sfx+')$','ve',text) #absolve→absolution\n elif text[-l-3:-l]=='osi': return re.sub('('+'i'+sfx+')$','e',text) #compose→composition\n else: return re.sub('('+'i'+sfx+')$','e',text) # compose→composition \n elif sfx in ['tion','tional'] and text[-l-1:-l+1]in['at','et','ut','it','ot']:\n # verbs end with ate like abbreviate -->abbreviation complete→completion attribute→attribution\n return re.sub(reg_ex,'t',text) \n elif sfx in ['tion','tional'] and text[-l-5:-l]=='scrip':\n # verbs end with ate like subscribe --> subscription\n return re.sub('('+'p'+sfx+')$','be',text) \n elif sfx in ['tion','tional'] and text[-l-1:-l+1] in ['pt','ct'] :\n # verbs end with ate like adopt --> adoption abstract --> abstraction\n return re.sub(reg_ex,'t',text) \n \n #ity rules \n #check bits , sequenty, access \n \n else: \n # remove the suffex without changing the text\n return re.sub(reg_ex,'',text) \n \n \n def checker(self,sfx,token,sensitivity):\n stemmed_token=\"\" \n if len(sfx) and len(token)>=3:\n #if a suffix is found\n if (len(sfx)/len(token))>sensitivity: #above threshold\n if re.sub('('+sfx+')$','',token) in dictionary: \n stemmed_token=re.sub('('+sfx+')$','',token)\n elif token.lower() not in stop_words and (len(token)-len(sfx))>=3 and self.sfx_stem(token,sfx) in dictionary:\n stemmed_token=self.sfx_stem(token,sfx)\n elif len(token)> len(sfx)+3:\n stemmed_token=self.sfx_stem(token,sfx) \n else:\n stemmed_token=self.sfx_stem(token,sfx) \n return stemmed_token\n \n def stemmer (self,token_set,sensitivity): \n \n if type(token_set)== list:\n for i in range(len(token_set)):\n #find suffixes using reg_ex\n sfx=''\n sfx=''.join(re.findall('(s|ed|es|ing|ment|tional|al|er|ly|ness|ity|ship|able|tion|es)$',token_set[i],flags=re.IGNORECASE))\n if len(sfx):\n token_set[i]=self.checker(sfx, token_set[i], sensitivity)\n \n else:\n sfx=''\n sfx=''.join(re.findall('(s|ed|es|ing|ment|tional|al|er|ly|ness|ity|ship|able|tion|es)$',token_set,flags=re.IGNORECASE))\n if len(sfx):\n token_set=self.checker(sfx, token_set, sensitivity)\n \n return token_set\n \n def my_stemmer (self, data):\n tk=NlpTokenizer()\n if type(data) == dict: \n data_tokens=tk.datatoken(data)\n stem_data={}\n \n for file in tqdm(data.keys()):\n stems=[]\n tags=[]\n for tag in data_tokens[file]:\n stemmed=[]\n for token in data_tokens[file][tag]:\n stemmed.append(self.stemmer(token,0.4))\n stems.append(stemmed)\n tags.append(tag)\n \n stem_data[file]=dict(zip(tags,stems))\n return stem_data\n else: \n stem_words= self.stemmer(data,0.4) \n return stem_words\n \n","sub_path":"custom_stemmer.py","file_name":"custom_stemmer.py","file_ext":"py","file_size_in_byte":6767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"276476280","text":"\nimport requests\n\n# 出于数据安全原因,各位各自登录账号后写一下cookies和headers,文件内不方便保存账号密码\ndata=\"\"\ncookies={}\nheaders={}\n\n# Only Python 3.6 is supported.\n# requests-html 是基于现有的框架 PyQuery、Requests、lxml、beautifulsoup4等库进行了二次封装,作者将Requests设计的简单强大的优点带到了该项目中。\n\n# 将cookie 转换成字典格式\ndef strToDictionary(b):\n d ={}#初始化字典变量 \n for line in b.split(';'):#按照字符:进行划分读取 \n #其设置为1就会把字符串拆分成2份 \n key,value = line.split('=',1)\n d[key] = value\n return d\n\ndef HARToDictionary(b):\n d ={}#初始化字典变量 \n for line in b:#分割 \n #其设置为1就会把字符串拆分成2份 \n d[line['name']]=line[ 'value']\n return d\n\n# 这里是我标记JSON的那几个,直接解决\nresponse = requests.get('http://zw.ql.jd.com/wholeProcess/query?orgId=0&proCode=&date=Tue+May+29+2018+00%3A00%3A00+GMT%2B0800+(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)', data=data,cookies=cookies,headers=headers)\nresponse.json()[\"allWaybillAmount\"]\n\n# 这里是我标记命中的那几个,用下载Excel的方式解决\n# showTime=2018/05/30 03:15:37&isToday=1&orgId=0&orgName=全国&proCode=&proName=全部省公司&areaCode=&areaName=全部片区&partCode=&partName=全部分区&siteId=&siteName=&provinceId=&provinceName=&cityId=&cityName=全部市&dimensionType=1\nresponse = requests.get('http://zw.ql.jd.com/realtimeDistribution/export?showTime=2018/05/30%2003:15:37&isToday=1&orgId=0&orgName=%25E5%2585%25A8%25E5%259B%25BD&proCode=&proName=%25E5%2585%25A8%25E9%2583%25A8%25E7%259C%2581%25E5%2585%25AC%25E5%258F%25B8&areaCode=&areaName=%25E5%2585%25A8%25E9%2583%25A8%25E7%2589%2587%25E5%258C%25BA&partCode=&partName=%25E5%2585%25A8%25E9%2583%25A8%25E5%2588%2586%25E5%258C%25BA&siteId=&siteName=&provinceId=&provinceName=&cityId=&cityName=%25E5%2585%25A8%25E9%2583%25A8%25E5%25B8%2582&dimensionType=1', data=data,cookies=cookies,headers=headers)\nprint(response.content)","sub_path":"PythonApplication1/自己的小练习/JD小组开发/realtimeDistribution.py","file_name":"realtimeDistribution.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"625219069","text":"### All of the living things\n\nimport math, sys\nimport pygame\nfrom pygame.locals import *\nfrom numpy import sign\n\n# -- Global constants\n \n# Colors - check out pygame.Colors. Probably does exactly what you want\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nBLUE = (50, 50, 255)\n \n# Screen dimensions\nSCREEN_WIDTH = 800\nSCREEN_HEIGHT = 600\nSCREEN_W_MID = SCREEN_WIDTH/2\nSCREEN_H_MID = SCREEN_HEIGHT/2\n\nclass Living(pygame.sprite.Sprite):\n \"\"\" This class is all the things that move. \"\"\"\n def __init__(self, x, y, width, height, image_file_name, initial_speed):\n \"\"\" x = upper left corner x component\n y = upper left corner y component\n width = x dimension to resize image to\n height = y dimension to resize image to\n image_file_name = a string of the image file name to load\n initial_speed = how quickly it moves in the x direction\n \"\"\"\n # Call the parent's constructor\n pygame.sprite.Sprite.__init__(self)\n\n # Set default image\n self.image = pygame.image.load(image_file_name).convert_alpha()\n self.image = pygame.transform.scale(self.image, (width, height))\n\n # Set position\n self.rect = self.image.get_rect()\n self.rect.y = y\n self.rect.x = x\n\n # Set initial_speed vector\n self.change_x = initial_speed\n self.change_y = 0\n\n # Set basic parameters/all the flags\n self.room = None # makes it so you can check collisions with objects in the room/affect them\n self.flipped = False # flips you over, used to draw you upside-down and let you float\n self.wet = False # checks to see if you are touching water and will make you drown\n self.talked = False # checks to see if you have spoken to your mushroom and triggers text\n\n def calc_grav(self):\n \"\"\" Calculate effect of gravity. Changes based on whether you're in the water or floating or on the ground. \"\"\"\n if self.wet and self.flipped and not self.is_floating():\n self.change_y -= .2\n elif self.is_floating() and self.flipped:\n pass\n else:\n if self.change_y == 0: # gives an initial speed bump\n self.change_y = 1\n else:\n self.change_y += .35 # steadily increases the fall\n \n def update(self):\n \"\"\" Makes sure all living things can update \"\"\"\n pass\n\n def is_floating(self):\n \"\"\" Check to see if you are floating on top of water \"\"\"\n # Checks if there is water 1 pixel below you\n self.rect.y += 1\n water_beneath = pygame.sprite.spritecollide(self, self.room.sludge, False)\n \n # Checks if there is water in the spot you actually occupy\n self.rect.y -= 1\n in_water = pygame.sprite.spritecollide(self, self.room.sludge, False)\n \n # If there's water beneath you but you're not in water, you're floating!\n return water_beneath and not in_water\n\nclass MushroomGuy(Living):\n \"\"\" This class represents the player character. \"\"\"\n def __init__(self):\n self.size = (75, 75)\n # Call the parent's constructor\n Living.__init__(self, 0, 0, self.size[0], self.size[1], 'png/mg_tc0.png', 0)\n \n # Set images\n self.image_list = [pygame.image.load('png/mg_tc0.png').convert_alpha(), pygame.image.load('png/mg_tc1.png').convert_alpha(), pygame.image.load('png/mg_tc2.png').convert_alpha()]\n for index, image in enumerate(self.image_list):\n self.image_list[index] = pygame.transform.scale(image, self.size)\n\n # Make list of things your mushroom will say to you\n self.text = [\"SYMBIOTE: C'mon, we won't be able to find your family if we don't eat something...!\",\n \"SYMBIOTE: Look at how strong we are! We don't need anyone else, aren't I enough for you?\",\n \"SYMBIOTE: Wow, um... I think that's... probably enough?\"]\n\n self.speed = 6\n\n # Corruption starts at zero. Eating mushrooms increases corruption. As corruption increases,\n # player avatar image changes (every corrupt_change points)\n self.corruption = 0\n self.corrupt_change = 7\n self.list_index = 0\n\n # Set shot direction: 1 = right, -1 = left\n self.shot_dir = 1\n\n # Set how much abuse the player can take before dying. wound will increase until it hits max_wound\n self.wound = 0\n self.max_wound = 1000\n \n #sets drowning for sludge\n self.drown = 0\n self.max_drown = 120\n\n #Fire!\n self.on_fire = False\n\n self.talk_length = 240 # Sets how long text from hitting 't' will last\n\n # Player-controlled movement:\n def go_left(self):\n \"\"\" Called when the user hits the left arrow. \"\"\"\n if ((self.is_floating() or self.wet) and self.flipped) or not self.flipped:\n self.change_x = -self.speed\n else:\n self.change_x = 0\n # Make the shot direction to the left\n self.shot_dir = -1\n \n def go_right(self):\n \"\"\" Called when the user hits the right arrow. \"\"\"\n if ((self.is_floating() or self.wet) and self.flipped) or not self.flipped:\n self.change_x = self.speed\n else:\n self.change_x = 0\n\n # Make the shot direction to the right\n self.shot_dir = 1\n \n def stop(self):\n \"\"\" Called when the user lets off the keyboard. \"\"\"\n self.change_x = 0\n\n def jump(self):\n \"\"\" Called when user hits 'jump' button. Currently does nothing, but can be uncommented if desired. \"\"\"\n pass\n # # move down a bit and see if there is a platform below us.\n # # Move down 2 pixels because it doesn't work well if we only move down\n # # 1 when working with a platform moving down.\n # self.rect.y += 2\n # wall_hit_list = pygame.sprite.spritecollide(self, self.room.wall_list, False)\n # self.rect.y -= 2\n \n # # If it is ok to jump, set our speed upwards\n # # That's a really cool way to do this\n # if len(wall_hit_list) > 0 and not self.flipped:\n # self.change_y = -5\n\n def how_corrupt(self):\n \"\"\" Changes the image based on the corruption level of the player. Currently, 3 levels of corruption. \"\"\"\n self.list_index = self.corruption/self.corrupt_change\n if self.list_index > len(self.image_list) - 1:\n self.list_index = len(self.image_list) - 1\n self.image = self.image_list[self.list_index]\n\n def draw_flipped(self):\n \"\"\"Flips the player's sprite based on the value assigned to self.flipped (controlled by keypress)\"\"\"\n if self.list_index > len(self.image_list) - 1:\n self.list_index = len(self.image_list) - 1\n if self.flipped:\n self.image = pygame.transform.flip(self.image_list[self.list_index], False, True)\n\n def climb(self):\n \"\"\" Allows the player to climb ledge fungi. \"\"\"\n if pygame.sprite.spritecollide(self, self.room.can_climb, False):\n self.change_y = -5\n \n def update(self):\n \"\"\" Update the player position. \"\"\"\n\n # Gravity\n self.calc_grav()\n\n # Move left/right\n self.rect.x += self.change_x\n \n # You only get to talk once.\n self.talked = False\n\n # Did this update cause us to hit a wall?\n block_hit_list = pygame.sprite.spritecollide(self, self.room.wall_list, False)\n for block in block_hit_list:\n # Check if it is deadly\n if block.mortality == True:\n self.wound += 50\n else:\n # If we are moving right, snap our right side to the left side of\n # the item we hit\n if self.change_x > 0:\n self.rect.right = block.rect.left\n else:\n # Otherwise if we are moving left, do the opposite.\n self.rect.left = block.rect.right\n\n # Move up/down\n self.rect.y += self.change_y\n \n # Check and see if we hit anything\n block_hit_list = pygame.sprite.spritecollide(self, self.room.wall_list, False)\n for block in block_hit_list:\n # Check if it's deadly ISUE: You can survive lava if you're at the bottom of a lake\n if block.mortality == True:\n self.wound += 50\n\n else:\n # Reset our position based on the top/bottom of the object.\n if self.change_y > 0:\n self.rect.bottom = block.rect.top\n else:\n self.rect.top = block.rect.bottom\n\n # Stop our vertical movement\n self.change_y = 0\n\n # Check if we are stuck in something viscous and slow us down + drown us if we are\n block_hit_list = pygame.sprite.spritecollide(self, self.room.sludge, False)\n if block_hit_list:\n self.wet = True\n if not self.flipped:\n self.drown += 1\n else:\n self.drown = 0\n self.wet = False\n for block in block_hit_list:\n self.rect.x -= self.change_x*block.visc\n self.rect.y -= self.change_y*block.visc\n\n # Check if we're hitting a dangerous enemy\n enemy_hit_list = pygame.sprite.spritecollide(self, self.room.enemy_list, False)\n for enemy in enemy_hit_list:\n if enemy.mortality == True:\n self.wound += 10\n\n # Kill player if he's beyond max_wound or max_drown\n if self.wound > self.max_wound or self.drown > self.max_drown:\n self.kill()\n\n # Update corruption and flipped status\n self.how_corrupt()\n self.draw_flipped()\n\n # Turn off death for easier debugging\n death = True\n if not death:\n self.wound = 0\n\n def __str__(self):\n # Used in Text\n return 'Player'\n\nclass Enemy(Living):\n \"\"\" This is the base class for anything that is alive and should move that isn't the player. \"\"\"\n def __init__(self, x, y, width, height, end_x, speed = -2, mortality = True):\n \"\"\" x = upper left corner x component\n y = upper left corner y component\n width = x dimension\n height = y dimension \n speed = how quickly it moves in the x direction\n distance = how far it can walk\n mortality = does it kill you? \"\"\"\n\n # Set the range of values it can go between\n self.start_x = x - width\n self.end_x = end_x\n\n # Call the parent's constructor\n Living.__init__(self, self.start_x, y, width, height, 'png/enemy.png', speed)\n\n # Set speed vector\n self.speed = abs(speed)\n self.change_x = speed\n self.change_y = 0\n\n self.mortality = mortality\n self.text = ['MONSTER: Rawr!', 'MONSTER: Rawr!', 'MONSTER: Rawr!']\n self.talk_length = 60\n\n self.near_player = False\n\n def update(self):\n \"\"\" Update the enemy position. \"\"\"\n # Gravity\n self.calc_grav()\n # Move left/right\n self.rect.x += self.change_x\n # If you talked last time, you don't talk this time\n self.talked = False\n #Check if you're on the same level as the player and close to the player\n if (abs(self.room.player.rect.centerx - self.rect.centerx) <= 300 and\n self.room.player.rect.bottom == self.rect.bottom):\n # Move towards him ISSUE: Enemy occasionally teleport far away and disappears\n self.change_x = sign(self.room.player.rect.centerx - self.rect.centerx)*self.speed*1.5\n if not self.near_player: # If I wasn't near him last step\n self.talked = True\n self.near_player = True\n else:\n #Reset your speed if you choose to change it\n self.change_x = sign(self.change_x)*self.speed\n self.near_player = False\n \n # Did this update cause it to hit a wall?\n block_hit_list = pygame.sprite.spritecollide(self, self.room.wall_list, False)\n for block in block_hit_list:\n # If the enemy is moving right, set its right side to the left side of\n # the item it hit\n if self.change_x > 0:\n self.rect.right = block.rect.left\n else:\n # Otherwise if it is moving left, do the opposite.\n self.rect.left = block.rect.right\n\n # Change direction\n self.change_x = -self.change_x\n\n # Check to see if it has hit the end of its range\n if self.rect.x <= self.end_x:\n self.change_x = self.speed\n elif self.rect.x >= self.start_x:\n self.change_x = -self.speed\n # Move up/down\n self.rect.y += self.change_y\n \n # Check and see if it hit anything\n block_hit_list = pygame.sprite.spritecollide(self, self.room.wall_list, False)\n for block in block_hit_list:\n \n # Reset its position based on the top/bottom of the object.\n if self.change_y > 0:\n self.rect.bottom = block.rect.top\n else:\n self.rect.top = block.rect.bottom\n\n # Stop its vertical movement\n self.change_y = 0\n\n def __str__(self):\n return 'Enemy'\n\nclass Friend(Enemy):\n \"\"\" A class of living creatures that will not kill you. Currently, it does not move.\"\"\"\n def __init__(self, x, y, width, height, not_used, image_file_name):\n \"\"\" x = upper left corner x component\n y = upper left corner y component\n width = x dimension\n height = y dimension \n image_file_name = the image wanted for the friend.\n The friend does not move, so speed and distance are 0 and mortality is False\"\"\"\n Enemy.__init__(self, x, y, width, height, 0, 0, False)\n self.image = pygame.image.load(image_file_name).convert_alpha()\n self.image = pygame.transform.scale(self.image, (width, height))\n self.near_player = False\n self.talk_length = 180\n\n def update(self):\n self.calc_grav()\n self.talked = False\n\n # Talks to you if you are within a certain distance\n if abs(self.room.player.rect.centerx - self.rect.centerx) <= 150:\n if not self.near_player:\n self.talked = True\n self.near_player = True\n else:\n self.near_player = False\n\n # Move up/down\n self.rect.y += self.change_y\n \n # Check and see if it hit anything\n block_hit_list = pygame.sprite.spritecollide(self, self.room.wall_list, False)\n for block in block_hit_list:\n \n # Reset its position based on the top/bottom of the object.\n if self.change_y > 0:\n self.rect.bottom = block.rect.top\n else:\n self.rect.top = block.rect.bottom\n\n # Stop its vertical movement\n self.change_y = 0\n\n def __str__(self):\n return 'Friend'\n\nclass AdultDuck(Friend):\n \"\"\" Makes an Adult Duck. No difference in corruption, just a different image and default size.\"\"\"\n def __init__(self, x, y, width = 100, height = 100, not_used = 0):\n self.width = width\n self.height = height\n Friend.__init__(self, x, y, self.width, self.height, not_used, \"png/adult_duck.png\")\n self.text = [\"DUCK: I'm sorry, but you can't stay with us. Good luck.\",\n \"DUCK: Ugh! Leave us alone, you don't belong with us!\",\n \"DUCK: Get away, you monster! We don't want you here!\"]\n\nclass ChildDuck(Friend):\n \"\"\" Baby Duck. Smaller than Adult. \"\"\"\n def __init__(self, x, y, width = 75, height = 75, not_used = 0):\n self.width = width\n self.height = height\n Friend.__init__(self, x, y, self.width, self.height, not_used, \"png/child_duck_friend.png\")\n self.text = [\"BABY DUCK: Hi! Wanna play?\",\n \"BABY DUCK: Uh... what's that on your head?\",\n \"BABY DUCK: Eek! Get away! MOMMY!\"]\n\nclass Log(Enemy):\n \"\"\" Unmoving enemy class, does not block or harm. \"\"\"\n def __init__(self, x, y, width = 100, height = 100, not_used = 0):\n Enemy.__init__(self, x, y, width, height, not_used, speed = 0, mortality = False)\n self.text = [\"Shhhh, it's sleeping\", \"Hah, it can't see us coming!\", \"This just makes it easier!\"]\n\nclass Edible(pygame.sprite.Sprite):\n \"\"\" This is the base class; any new foods should be modified from this one. \"\"\"\n def __init__(self, x, y, width, height, corr_points = 1, health_points = 50):\n \"\"\" Constructor for the wall that the player can run into. \"\"\"\n # Call the parent's constructor\n pygame.sprite.Sprite.__init__(self)\n\n # Set the visual\n self.image = pygame.image.load('png/edible.png').convert_alpha()\n self.image = pygame.transform.scale(self.image, (width, height))\n\n # Set parameters\n self.corr_points = corr_points\n self.health_points = health_points\n\n # Make our top-left corner the passed-in location.\n self.rect = self.image.get_rect()\n self.rect.y = y\n self.rect.x = x\n\nclass FriendEdible(Edible):\n \"\"\" This is an edible food that only comes from when you have killed a friendly creature. \"\"\"\n def __init__(self, x, y, width, height):\n Edible.__init__(self, x, y, width, height, 5, 150)","sub_path":"LivingThings.py","file_name":"LivingThings.py","file_ext":"py","file_size_in_byte":17484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"104944534","text":"# Konrad Budukiewicz 172108\r\n# Wykonałem losowanie 20 punktów zakres (0, 100), punkty maja odwołanie w klasie\r\n# Zaimplementowanie algorytmu Jarvisa\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom collections import namedtuple\r\nimport random\r\n\r\nPoint = namedtuple('Point', 'x y')\r\n\r\n\r\nclass Convex_Hull:\r\n points = []\r\n\r\n def __init__(self):\r\n pass\r\n\r\n def add(self, point):\r\n self.points.append(point)\r\n\r\n def orientation_points(self, pkt1, pkt2, pkt3): # orientacja punktów\r\n value = ((pkt2.y - pkt1.y) * (pkt3.x - pkt2.x) - (pkt2.x - pkt1.x) * (pkt3.y - pkt2.y))\r\n if value == 0:\r\n return 0\r\n elif value > 0:\r\n return 1\r\n else:\r\n return 2\r\n\r\n def the_lowest_index_pkt(self): # znajdowanie najmniejszego elementu\r\n min_index = 0\r\n points = self.points\r\n for i in range(1, len(points[1:])):\r\n if points[i:] < points[min_index:]:\r\n min_index = i\r\n elif points[i:] == points[min_index:]:\r\n if points[:i] > points[:min_index]:\r\n min_index = i\r\n return min_index\r\n\r\n def calculate_convex_hull(self): # funkcja licząca punkty i rysująca\r\n number_pkt = 20\r\n min_index = self.the_lowest_index_pkt()\r\n points = self.points\r\n hull_points = []\r\n p = min_index\r\n\r\n while True:\r\n q = 0\r\n hull_points.append(p)\r\n q = (p + 1) % number_pkt\r\n\r\n for i in range(number_pkt):\r\n if self.orientation_points(points[p], points[i], points[q]) == 2:\r\n q = i\r\n\r\n p = q\r\n\r\n if p == min_index:\r\n break\r\n\r\n x_hull = []\r\n y_hull = []\r\n\r\n print(hull_points)\r\n for j in hull_points:\r\n x_hull.append(points[j].x)\r\n y_hull.append(points[j].y)\r\n x_hull.append(x_hull[0])\r\n y_hull.append(y_hull[0])\r\n x = [pkt.x for pkt in self.points]\r\n y = [pkt.y for pkt in self.points]\r\n\r\n plt.title('Convex Hull')\r\n plt.plot(x, y, marker='D', linestyle='None')\r\n plt.plot(x_hull, y_hull, 'r')\r\n plt.show()\r\n\r\n def printing(self): # wypisuje punkty wylosowane\r\n x1 = [pkt.x for pkt in self.points]\r\n y1 = [pkt.y for pkt in self.points]\r\n print(x1, y1)\r\n\r\n\r\ndef main():\r\n new = Convex_Hull()\r\n for i in range(0, 20):\r\n new.add(Point(random.randint(0, 100), random.randint(0, 100))) # losowanie pkt(0, 100)\r\n\r\n new.printing()\r\n new.the_lowest_index_pkt()\r\n new.calculate_convex_hull()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"435401428","text":"\"\"\"\nThis script analyzes fragment size distributions to identify overrepresented fragments as putative sRNAs. \nOutput: list of enriched fragments, with their genomic context. Additionally: a bed-file with the candidates visualization in Jbrowse in intermediate stage of analysis.\nCommand: python small_frags.py [output_folder] [GFF_file] iter=XXX\nAfter the first iteration (iter=1), candidates are added to the 'small_features_N.txt' file.\nSubsequently, a new library-wide distribution is produced by running 'process_sam_nomulti.py' again, followed by another iteration of this script (iter=2).\n\nRequired files:\n[output_folder]/temp_files/chromsizes.txt - produced by 'process_sam_nomulti.py'\n[output_folder]/temp_files/small_features_1.txt - produced by 'process_annotation.py'\n[output_folder]/output/fragment_sizes/{}_fragsize_no_smallfeats.txt - produced by 'process_sam_nomulti.py'\n[output_folder]/temp_files/cont_peaks_in_term.txt - produced by 'terminator_analysis.py'\n\"\"\"\n\nfrom __future__ import division\nimport numpy as np\nimport math\nimport sys\nfrom collections import defaultdict\n\nout_folder = sys.argv[1]\n\nstrands = ['plus','minus']\nsamples = ['cont']\n\nbinsize = 10\nexpand_rna = 10\niterno = int(sys.argv[3].split('=')[1])\n\n# Read chromosome information\nchromsize_file = open(out_folder+'/temp_files/chromsizes.txt','r')\nchromsize_lines = chromsize_file.readlines()\nchromsize_file.close()\n\ngenome_name = chromsize_lines[0].split()[0]\ngenome_size = int(chromsize_lines[0].split()[1])\n\n## Read annotation\ngff_file = open(sys.argv[2],'r')\nann_lines = gff_file.readlines()\ngff_file.close()\n\npos_feat = defaultdict(lambda: defaultdict(set))\n\nfcounts = {}\nfeat_types = ['tRNA','rRNA','CDS','ncRNA','pseudogene','repeat_region','repeat_unit']\nfor feat_type in feat_types:\n\tfcounts[feat_type] = 0\n\nann_details = {}\nfor ann_line in ann_lines:\n\tif ann_line[0] == '#':\n\t\tcontinue\t\n\tline = ann_line.split('\\t')\n\tftype = line[2]\n\tstrand = line[6]\n\topp_strand = '-' if strand == '+' else '+'\n\tif ftype in feat_types:\n\t\tfcounts[ftype] += 1\n\t\tif 'Name=' in line[8]:\n\t\t\tfid = line[8].split('Name=')[1].split(';')[0]\n\t\telse:\n\t\t\tfid = line[8].split('ID=')[1].split(';')[0]\n\t\tleft = int(line[3]) - expand_rna if (ftype in ['rRNA','tRNA'] and strand == '-') else int(line[3])\n\t\tright = int(line[4]) + expand_rna if (ftype in ['rRNA','tRNA'] and strand == '+') else int(line[4])\n\t\tann_details[fid] = [ftype,left,right]\n\t\tfor i in range(left, right+1): # Don't use zero-based coordinates here\n\t\t\tpos_feat[strand][i].add(fid)\n\t\t\tif ftype in ['repeat_region','repeat_unit']:\n\t\t\t\tpos_feat[opp_strand][i].add(fid)\n\t\t\t\t\npos_feat_list = {}\nfor strand, data in pos_feat.items():\n\tlist_of_sets = []\n\tfor k in range(genome_size):\n\t\tlist_of_sets.append(list(data[k]))\n\tpos_feat_list[strand] = list_of_sets\n\n# Read small_feature data\nsmallfeat_file = open(out_folder+'/temp_files/small_features_{}.txt'.format(iterno),'r')\nsmallfeat_lines = smallfeat_file.readlines()\nsmallfeat_file.close()\nsmallfeats = {}\nsmallfeats['+'] = np.zeros((1,genome_size))\nsmallfeats['-'] = np.zeros((1,genome_size))\n\nsmallfeat_ext_file = open(out_folder+'/temp_files/small_features_{}.txt'.format(iterno+1),'w')\nfor line in smallfeat_lines:\n\tsmallfeat_ext_file.write(line)\n\tfrontbuffer = 30\n\tspecs = line.split()\n\tleft = int(specs[0])\n\tright = int(specs[1])\n\tstrand = specs[2]\n\tfeat_type = specs[3]\n\tif feat_type == 'tRNA':\n\t\tafterbuffer = 10\n\telse:\n\t\tafterbuffer = 0\n\t\n\tif strand == '+':\n\t\tleft -= frontbuffer\n\t\tright += afterbuffer\n\tif strand == '-':\n\t\tleft -= afterbuffer\n\t\tright += frontbuffer\t\n\t\n\tif left-1 < 0:\n\t\tsmallfeats[strand][0,genome_size+left-1:genome_size] = np.ones((1,1-left))[0]\n\t\tsmallfeats[strand][0,0:right] = np.ones((1,right))[0]\n\telif right > genome_size:\n\t\tsmallfeats[strand][0,0:right-genome_size] = np.ones((1,right-genome_size))[0]\n\t\tsmallfeats[strand][0,(left-1):genome_size] = np.ones((1,genome_size-left+1))[0]\n\telse:\n\t\tsmallfeats[strand][0,(left-1):(right)] = np.ones((1,right-left+1))[0]\n\n# Begin analysis\t\t\nfragsizes = {}\nend_counts = {}\nfor sample in samples:\n\tall_fragsize_file = open(out_folder+'/output/fragment_sizes/{}_fragsize_no_smallfeats.txt'.format(sample),'r')\n\tall_fragsize_lines = all_fragsize_file.readlines()\n\tall_fragsize_file.close()\n\t\n\tfout = open(out_folder+'/output/fragment_sizes/{}_small_RNA_elements.txt'.format(sample),'w')\n\tfout_bed = open(out_folder+'/output/bed/{}_sRNA_candidates.bed'.format(sample),'w')\n\tfirstline = '\\t'.join(['start','end','strand','enrichment','term_eff','occ_freq','classification','sense_overlap','antisense_overlap'])+'\\n'\n\tfout.write(firstline)\n\tall_fragsizes = np.zeros((len(all_fragsize_lines)-1,1))\n\tfor line in all_fragsize_lines[1:]: \n\t\tdata = line.split()\n\t\tfraglen = int(data[0])\n\t\tfreq = int(float(data[1]))\n\t\tall_fragsizes[fraglen-1,0] = freq\n\t\tmax_size = fraglen\n\t\n\tall_rel_freqs = all_fragsizes / sum(all_fragsizes)\n\tbin_no = int(math.ceil(max_size/binsize))\n\tbinned_fragsizes = {}\n\tfor l in range(bin_no):\n\t\tbinpos = (l+0.5) * binsize + 0.5\n\t\tbincount = int(sum(all_fragsizes[l*binsize:(l+1)*binsize,0])) if (l+1)*binsize <= max_size - 1 else int(sum(all_fragsizes[l*binsize:,0]))\n\t\tbinned_fragsizes[binpos] = bincount\n\t\t\n\tfragsizes[sample] = {}\n\tend_counts[sample] = {}\n\t\n\tfor strand in strands:\n\t\tfragsizes[sample][strand] = {'per_end':{},'per_start':{}}\n\t\tper_start_file = open(out_folder+'/output/fragment_sizes/{}_per_start_{}.txt'.format(sample,strand),'r')\n\t\tper_start_lines = per_start_file.readlines()\n\t\tper_start_file.close()\n\t\tfor line in per_start_lines:\n\t\t\tdata = line.split()\n\t\t\tnt = int(data[0])\n\t\t\tsizes = map(int,data[1].split(','))\n\t\t\tfragsizes[sample][strand]['per_start'][nt] = sizes\n\t\t\n\t\tper_end_file = open(out_folder+'/output/fragment_sizes/{}_per_end_{}.txt'.format(sample,strand),'r')\n\t\tper_end_lines = per_end_file.readlines()\n\t\tper_end_file.close()\n\t\tfor line in per_end_lines:\n\t\t\tdata = line.split()\n\t\t\tnt = int(data[0])\n\t\t\tsizes = map(int,data[1].split(','))\n\t\t\tfragsizes[sample][strand]['per_end'][nt] = sizes\n\t\tend_counts[sample][strand] = np.genfromtxt(out_folder+'/output/perbase/raw_{}_{}_end_count.txt'.format(sample,strand),dtype=None,names=('nt','count'))\n\t\t\n\tpeakfile = open(out_folder+'/temp_files/{}_peaks_in_term.txt'.format(sample),'r')\n\tpeaklines = peakfile.readlines()\n\tpeakfile.close()\n\t\n\tsRNA_count = 0\n\tfor peak in peaklines:\n\t\tdata = peak.split()\n\t\tstrandsign = data[0]\n\t\tstrand = 'plus' if strandsign == '+' else 'minus'\n\t\tstart,end = map(int,data[1:3])\n\t\tin_term = data[3]\n\t\tcounts = abs(end_counts[sample][strand]['count'][start-1:end])\n\t\tfragno = abs(sum(counts))\n\t\tmax_term_nt = start + counts.argmax() # nucleotide with highest termination frequency\n\t\t\n\t\tstarts = []\n\t\tfor nt in range(start,end+1):\n\t\t\tif nt in fragsizes[sample][strand]['per_end']:\n\t\t\t\tif strand == 'plus':\n\t\t\t\t\tstarts += list(nt - np.array(fragsizes[sample][strand]['per_end'][nt]) + 1)\n\t\t\t\telse:\n\t\t\t\t\tstarts += list(nt + np.array(fragsizes[sample][strand]['per_end'][nt]) - 1)\n\t\tstarts = np.array(starts) + 1000 # temporarily add 1000 to prevent that any start sites are negative\n\t\tabs_freqs = np.bincount(starts)\n\t\trel_freqs = abs_freqs / fragno\n\t\tnonzeros = np.nonzero(rel_freqs)[0]\n\t\tdists = abs(nonzeros-1000 - max_term_nt) + 1 # Subtract the artificial 1000 again\n\t\tarray = np.vstack((nonzeros-1000,dists,rel_freqs[nonzeros])).T # Note that rel_freqs is still built up with the nonzero coordinates that were increased by 1000\n\t\tindex_max = array[:,2].argmax() # nucleotide from which the highest portion of reads terminated at this peak start\n\t\tnt_max = int(array[index_max,0])\n\t\tmin_size = start - nt_max + 1 if strand == 'plus' else nt_max - end + 1\n\t\tmax_size = end - nt_max + 1 if strand == 'plus' else nt_max - start + 1\n\n\t\tsmallfeat_sum = np.sum(smallfeats[strandsign][0,start-1:end])\n\t\tif smallfeat_sum == 0: # Exclude small features when determining fragment size distribution\n\t\t\tall_other_fragsizes = np.array(all_fragsizes)\n\t\t\tall_other_rel_freqs = all_other_fragsizes / sum(all_other_fragsizes)\n\t\t\tenr = array[index_max,2] / all_other_rel_freqs[int(array[index_max,1])-1]\n\t\telse:\n\t\t\tenr = array[index_max,2] / all_rel_freqs[int(array[index_max,1])-1] # ratio between observed occurrence of this fragment size and the expected occurrence based on all fragments in the entire dataset\n\t\t\t\n\t\tif nt_max <= 0:\n\t\t\tnt_max += genome_size\n\t\t\n\t\tstart_sizes = fragsizes[sample][strand]['per_start'][nt_max]\n\t\tfrags_in = sum(size >= min_size for size in start_sizes)\n\t\tfrags_term = sum(size >= min_size and size <= max_size for size in start_sizes)\n\t\tterm_eff = 100 * frags_term / frags_in # fraction of reads starting at the chosen 'TSS' to be terminated in this peak\n\t\t\n\t\t### Cut-offs: \n\t\t###\tTermination eff. (term_eff): 30\n\t\t###\tEnrichment (enr): 25\n\t\t### Fragment coverage (frags_term): 200 for non-HC-terminator peaks, 15 for HC-terminator peaks\n\t\t### Then classify based on annotation context: tRNA, in rRNA region, inside CDS etc.\n\t\t\n\t\tif (in_term == 'True' and enr >= 25 and term_eff >= 25 and frags_term >= 15) or (term_eff >= 25 and enr >= 25 and frags_term >= 200):\n\t\t\tleft = min(nt_max,max_term_nt)\n\t\t\tright = max(nt_max,max_term_nt)\n\t\t\topp_strand = '+' if strand == 'minus' else '-'\n\t\t\t\n\t\t\tflist = []\n\t\t\tfor fset in pos_feat_list[strandsign][left:right+1]:\n\t\t\t\tfor el in fset:\n\t\t\t\t\tflist.append(el)\n\t\t\tflist = list(set(flist))\n\t\t\t\n\t\t\tflist_as = []\n\t\t\tfor fset in pos_feat_list[opp_strand][left:right+1]:\n\t\t\t\tfor el in fset:\n\t\t\t\t\tflist_as.append(el)\n\t\t\tflist_as = list(set(flist_as))\n\t\t\ttemp = list(flist_as)\n\t\t\tfor feat in flist_as:\n\t\t\t\tif 'repeat' in feat:\n\t\t\t\t\ttemp.remove(feat)\n\t\t\tflist_as = list(temp)\n\t\t\t\n\t\t\tclasses = []\n\t\t\tif len(flist) == 0:\n\t\t\t\tclasses.append('New')\n\t\t\telse:\n\t\t\t\tfor feat in flist:\n\t\t\t\t\tftype = ann_details[feat][0]\n\t\t\t\t\tfleft = ann_details[feat][1]\n\t\t\t\t\tfright = ann_details[feat][2]\n\t\t\t\t\tif ftype in ['tRNA','rRNA','ncRNA','pseudogene']:\n\t\t\t\t\t\tclasses.append(ftype)\n\t\t\t\t\tif 'repeat' in ftype:\n\t\t\t\t\t\tclasses.append('repeat')\n\t\t\t\t\tif ftype == 'CDS':\n\t\t\t\t\t\tif left <= fleft and right >= fright:\n\t\t\t\t\t\t\tclasses.append('CDS_full')\n\t\t\t\t\t\tif left <= fleft and right < fright:\n\t\t\t\t\t\t\tclassification = 'CDS_start' if strandsign == '+' else 'CDS_end'\n\t\t\t\t\t\t\tclasses.append(classification)\n\t\t\t\t\t\tif left > fleft and right < fright:\n\t\t\t\t\t\t\tclasses.append('CDS_inside')\n\t\t\t\t\t\tif left > fleft and right >= fright:\n\t\t\t\t\t\t\tclassification = 'CDS_start' if strandsign == '-' else 'CDS_end'\n\t\t\t\t\t\t\tclasses.append(classification)\n\t\t\tclasses = list(set(classes))\n\t\t\tclass_string = ','.join(classes)\n\t\t\tsense_partners = ','.join(flist)\n\t\t\tantisense_partners = ','.join(flist_as)\n\t\t\tsRNA_count += 1\n\t\t\tnewline = '{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n'.format(left,right,strandsign,int(enr),int(round(term_eff)),frags_term,class_string,sense_partners,antisense_partners)\n\t\t\tfout.write(newline)\n\t\t\tbedline = '{}\\t{}\\t{}\\tsRNA_{}\\t{}\\t{}\\n'.format(genome_name,left-1,right,sRNA_count,int(round(term_eff)),strandsign)\n\t\t\tfout_bed.write(bedline)\n\t\t\tsmallfeat_line = '{}\\t{}\\t{}\\t{}\\n'.format(left,right,strandsign,'ncRNA')\n\t\t\tsmallfeat_ext_file.write(smallfeat_line)\n\tfout.close()\n\tfout_bed.close()\n\nsmallfeat_ext_file.close()","sub_path":"small_frags.py","file_name":"small_frags.py","file_ext":"py","file_size_in_byte":11120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"208813904","text":"from django.shortcuts import render\nfrom django.urls import reverse\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login as Login,logout as Logout\nfrom django.views.generic import ListView\nfrom django.views.generic.edit import CreateView\nfrom .models import checkpost, vehicle_info, defaulter, closed_cases, staff\nfrom django.utils import timezone\nfrom . import forms\nfrom binascii import hexlify\nimport os\nfrom django.contrib.auth.decorators import login_required\n\n\n# Create your views here.\ndef home(request):\n\tctx={}\n\treturn render(request,'home/index.html',ctx)\n\n\n@login_required(login_url='/staffLogin/')\ndef register_checkpost(request):\n\terr_msg = ''\n\tif(request.user.has_perm('home.add_checkpost')):\n\t\tif(request.method=='POST'):\n\t\t\tform = forms.check_post_form(request.POST)\n\t\t\tif(form.is_valid()):\n\t\t\t\tkey = hexlify(os.urandom(15)).decode()\n\t\t\t\tcp_id = hexlify(os.urandom(5)).decode()\n\t\t\t\tcp = checkpost(state=form.cleaned_data['state'],\n\t\t\t\t\tdistrict=form.cleaned_data['state'],\n\t\t\t\t\tplace = form.cleaned_data['place'],\n\t\t\t\t\tpostCode = form.cleaned_data['pincode'],\n\t\t\t\t\tapi_key = key,\n\t\t\t\t\tpost_id = cp_id\n\t\t\t\t\t)\n\t\t\t\tcp.save()\n\t\t\t\treturn render(request,'home/show_api_key.html',{'api_key':key,'post_id':cp_id})\n\t\t\telse:\n\t\t\t\treturn render(request,'home/checkpost_form',{'form':form})\n\t\telse:\n\t\t\tform = forms.check_post_form()\n\t\t\treturn render(request,'home/checkpost_form.html',{'form':form})\n\telse:\n\t\tform = forms.user_login_form()\n\t\terr_msg = 'You are not Authorized to add Check-Posts, Enter with a superuser account'\n\t\treturn render(request,'home/staff_login.html',{'form':form,'err_msg':err_msg})\n\ndef login_checkpost(request):\n\terr_msg = ''\n\tif(request.method=='POST'):\n\t\tform = forms.check_post_login_form(request.POST)\n\t\tif(form.is_valid()):\n\t\t\tif(checkpost.objects.filter(state=form.cleaned_data['state'],\n\t\t\t\tdistrict=form.cleaned_data['district'],\n\t\t\t\tpostCode = form.cleaned_data['pincode'],\n\t\t\t\tpost_id = form.cleaned_data['check_post_id']\n\t\t\t\t).count()>0):\n\t\t\t\tdfltr_list = defaulter.objects.filter(checkpost_id=checkpost.objects.get(post_id = form.cleaned_data['check_post_id']))\n\t\t\t\tclosed_cases_list = closed_cases.objects.filter(checkpost_id=checkpost.objects.get(post_id = form.cleaned_data['check_post_id']))\n\n\t\t\t\treturn render(request,'home/checkpost_details.html',{'dfltr_list':dfltr_list,'closed_cases_list':closed_cases_list})\n\t\t\telse:\n\t\t\t\terr_msg='No checkpost found for the input combination'\n\t\t\t\treturn render(request,'home/checkpost_login_form.html',{'form':form,'err_msg':err_msg})\n\t\telse:\n\t\t\treturn render(request,'home/checkpost_login_form.html',{'form':form})\n\telse:\n\t\tform = forms.check_post_login_form()\n\t\treturn render(request,'home/checkpost_login_form.html',{'form':form,'err_msg':err_msg})\n\ndef validate_vrn(vrn):\n\tif(len!=10):\n\t\treturn \"Enter 10-digit Vehicle registration No.\"\n\telse:\n\t\treturn True\n\ndef vrnForm(request):\n\tctx={'error_msg':\"\"}\n\treturn render(request,'home/vrnform.html',ctx)\n\ndef vrnform_submit(request):\n\tctx={'error_msg':\"\"}\n\tif(request.method==\"POST\"):\n\t\tvrn=request.POST['VRN']\n\t\tif(len(vrn)!=10):\n\t\t\tctx['error_msg']=\"Enter your 10-digit Vehicle registration No.\"\n\t\t\tctx['vrn']=vrn\n\t\t\treturn render(request,'home/vrnform.html',ctx)\n\t\telse:\n\t\t\tctx['vrn']=vrn\n\t\t\tctx['isData']=False\n\t\t\tif(defaulter.objects.filter(vrn_id=vehicle_info.objects.filter(vrn=vrn)[0]).count()>0):\n\t\t\t\td=defaulter.objects.get(vrn_id=vehicle_info.objects.filter(vrn=vrn)[0])\n\t\t\t\tctx['isData']=True\n\t\t\t\tctx['owner']=vehicle_info.objects.filter(vrn=vrn)[0].reg_owner\n\t\t\t\tctx['rulecat']=d.get_rule_cat_id_display()\n\t\t\t\tcp = checkpost.objects.get(post_id=d.checkpost_id)\n\t\t\t\tctx['place']= str(cp.place) +' '+ str(cp.get_district_display()) +' '+ str(cp.get_state_display()) +' '+ str(cp.postCode)\n\t\t\t\tctx['time']=d.date_time\n\n\t\t\t\treturn render(request,'home/challandetail.html',ctx)\n\t\t\telse:\n\n\t\t\t\treturn render(request,'home/challandetail.html',ctx)\n\telse:\n\t\treturn render(request,'home/vrnform.html',ctx)\n\n\ndef staff_login(request):\n\terr_msg = ''\n\tif(request.method==\"POST\"):\n\t\tform = forms.user_login_form(request.POST)\n\t\tif(form.is_valid()):\n\t\t\temail = form.cleaned_data['email']\n\t\t\tpassword = form.cleaned_data['password']\n\t\t\ttry:\n\t\t\t\tusername=User.objects.filter(email=email)[0].username\n\t\t\texcept:\n\t\t\t\terr_msg='No account associated with this email'\n\t\t\t\treturn render(request, 'home/staff_login.html',{'form':form,'err_msg':err_msg})\n\t\t\tuser = authenticate(request, username=username, password=password)\n\t\t\tif user is not None:\n\t\t\t\tLogin(request,user)\n\t\t\t\t \t# Redirect to a success page.\n\t\t\t\t# HttpResponseRedirect(url('home:index'))\n\t\t\t\treturn HttpResponseRedirect('/')\n\t\t\telse:\n\t\t\t\t# Return an 'invalid login' error message.\n\t\t\t\tprint(9999999999999999999999)\n\t\t\t\treturn render(request,'home/staff_login.html',{'form':form})\n\t\telse:\n\t\t\tprint(7777777777777777)\n\t\t\treturn render(request,'home/staff_login.html',{'form':form})\n\telse:\n\t\tprint(222222222222222222222222)\n\t\tif(request.user.is_authenticated):\n\t\t\terr_msg = 'Currently you are logged in as {}.'.format(request.user.username)\n\t\tif(request.GET.get('next')=='/registerCheckpost/'):\n\t\t\terr_msg = 'To register a check post, login with superuser account.'\n\t\tform = forms.user_login_form()\n\t\treturn render(request, 'home/staff_login.html',{'form':form,'err_msg':err_msg})\n\n\n\ndef staff_registration(request):\n\terr_msg = ''\n\tif(request.method=='POST'):\n\t\tform = forms.user_registration_form(request.POST)\n\t\tif(form.is_valid()):\n\t\t\tif(checkpost.objects.filter(post_id = form.cleaned_data['check_post_id']).count()>0):\n\t\t\t\tuser = User.objects.create_user(first_name=form.cleaned_data['first_name'],\n\t\t\t\t\t\tlast_name=form.cleaned_data['last_name'],\n\t\t\t\t\t\temail=form.cleaned_data['email'],\n\t\t\t\t\t\tusername = str(form.cleaned_data['first_name'])+' '+str(form.cleaned_data['last_name']),\n\t\t\t\t\t\tpassword=form.cleaned_data['password'])\n\t\t\t\tstaff.objects.create(name = user,\n\t\t\t\tcheckpost = checkpost.objects.get(post_id=form.cleaned_data['check_post_id'])\n\t\t\t\t)\n\t\t\t\tLogin(request,user)\n\t\t\t\treturn HttpResponseRedirect('/')\n\t\t\telse:\n\t\t\t\terr_msg = 'Post Id entered is not valid'\n\t\t\t\treturn render(request,'home/staff_register.html',{'form':form,'err_msg':err_msg})\n\t\telse:\n\t\t\treturn render(request,'home/staff_register.html',{'form':form})\n\telse:\n\t\tdisable = ''\n\t\tif(request.user.is_authenticated):\n\n\t\t\terr_msg = 'Currently you are logged in as {}.'.format(request.user.username)\n\t\t\tdisable = 'disabled'\n\t\tform = forms.user_registration_form()\n\t\treturn render(request,'home/staff_register.html',{'form':form,'err_msg':err_msg,'disable':disable})\n\ndef staff_logout(request):\n\tLogout(request)\n\treturn HttpResponseRedirect('/')\n","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"138011302","text":"import csv\nimport numpy as np\n\n\ndef module_sizes(mydict):\n\tlength = []\n\tfor val in mydict.values(): \n\t\ttemp = 0 \n\t\tfor i in range(56): \n\t\t\tif i<10: \n\t\t\t\tif ' '+str(i) in val: \n\t\t\t\t\ttemp +=1 \n\t\t\telse: \n\t\t\t\tif str(i) in val: \n\t\t\t\t\ttemp += 1 \n\t\tlength.append(temp) \n\treturn length\n\ndef gene_persistence(mydict):\n\tcount = np.zeros(56)\n\tfor val in mydict.values(): \n\t\tfor i in range(56): \n\t\t\tif i<10: \n\t\t\t\tif ' '+str(i) in val: \n\t\t\t\t\tcount[i]+= 1 \n\t\t\telse: \n\t\t\t\tif str(i) in val: \n\t\t\t\t\tcount[i]+= 1\n\treturn count\n\n\n\t\n\n\nfilename = 'hk_cluster_clst.csv'\n\nwith open(filename, mode='r') as infile: \n\treader = csv.reader(infile) \n\tmydict = {rows[0]:rows[1] for rows in reader} ","sub_path":"OLD/read_cluster_csv.py","file_name":"read_cluster_csv.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"216652563","text":"def DT_Bagging(self):\n\t\t\n\t\tjvm.start(packages=True)\n\n\t\tT_dtbg = [\"index\",\"Ib\",\"C\",\"M\",\"AccDev\",\"AccCrV\",\"AccDif\"]\n\n\t\tdt_train = \"\"\n\t\tdt_test = \"\"\n\n\t\tloader = Loader(classname=\"weka.core.converters.ArffLoader\")\n\t\ttrain = loader.load_file(dt_train)\n\t\ttrain.class_index = train.num_attributes - 1\n\n\t\ttest = loader.load_file(dt_test)\n\t\ttest.class_is_last()\n\n\t\tdef xfrange(start, stop, step):\n\t\t\ti = 0\n\t\t\twhile start + i * step < stop:\n\t\t\t\tyield start + i * step\n\t\t\t\ti += 1\n\n\t\tdex = 0\n\t\tr = 0\n\t\tself.count = 0\n\t\t\n\t\tfor j in range(0.1,1.0,0.1):\n\t\t\tfor j in range(1,10):\n\t\t\n\t\t\t\tdt = Classifier(classname=\"weka.classifiers.trees.J48\", options=[\"-C\",str(j),\"-M\",str(i)])\n\t\n\t\t\t\tfor x in range(5,100,1):\n\t\t\t\t\tdex += 1\n\t\t\t\t\tcls = SingleClassifierEnhancer(classname=\"weka.classifiers.meta.Bagging\", options=[\"-P\",\"100\",\"-S\",\"1\",\"-num-slots\",\"1\",\"-I\",str(x)])\n\t\t\t\t\tcls.classifier = dt\n\t\t\t\t\tcls.build_classifier(train)\n\n\t\t\t\t\tind = 1\n\t\t\t\t\tacc_ind = 0\n\n\t\t\t\t\tfor index, inst in enumerate(test):\n\t\t\t\t\t\tpred = cls.classify_instance(inst)\n\t\t\t\t\t\tdist = cls.distribution_for_instance(inst)\n\t\t\t\t\t\tind = index\n\n\t\t\t\t\t\tif pred == inst.get_value(inst.class_index):\n\t\t\t\t\t\t\tacc_ind += 1\n\t\t\t\n\t\t\t\t\tT_dtbg.append(dex)\n\t\t\t\t\tT_dtbg.append(x)\n\t\t\t\t\tT_dtbg.append(i)\n\t\t\t\t\tT_dtbg.append(j)\n\t\t\n\t\t\t\t\tnd = ind+1\n\t\t\t\t\taccuracy = acc_ind/float(nd)\n\t\n\t\t\t\t\tevlt = Evaluation(test)\n\t\t\t\t\tevlt.test_model(cls, test)\n\t\t\t\t\tT_dtbg.append(str(evlt.percent_correct))\n\t\t\n\t\t\t\t\tevlcr = Evaluation(train)\n\t\t\t\t\tevlcr.crossvalidate_model(cls, train, 2, Random(1))\n\t\t\t\t\tT_dtbg.append(str(evlcr.percent_correct))\n\t\t\n\t\t\t\t\taccDif = evlt.percent_correct - evlcr.percent_correct\n\t\t\t\t\tT_dtbg.append(accDif)\n\t\t\t\n\t\t\t\t\tfor self.count in range(r,r+2):\n\t\t\t\t\t\tself.count += 1\n\t\t\t\t\t\ttime.sleep(0.5)\n\t\t\t\t\t\tr += 1\n\t\t\t\t\t\tself.progressBar.setValue(self.count)\n\n\t\tTab_dtbg = np.reshape(T_dtbg, (-1, 7))\n\n\t\tpath = \"\"\n\t\tname = \"\"\n\n\t\twith open(path+\"/\"+name, \"wb\") as f:\n\t\t\twriter = csv.writer(f)\n\t\t\twriter.writerows(Tab_dtbg)\n\n\t\tjvm.stop()\n\n\t\tpat = path +\"/\" + name\n\n\t\twith open(unicode(pat), 'rb') as stream:\n\t\t\tself.tableWidget.setRowCount(0)\n\t\t\tself.tableWidget.setColumnCount(0)\n\t\t\tfor rowdata in csv.reader(stream):\n\t\t\t\trow = self.tableWidget.rowCount()\n\t\t\t\tself.tableWidget.insertRow(row)\n\t\t\t\tself.tableWidget.setColumnCount(len(rowdata))\n\t\t\t\tfor column, data in enumerate(rowdata):\n\t\t\t\t\titem = QtGui.QTableWidgetItem(data.decode('utf8'))\n\t\t\t\t\tself.tableWidget.setItem(row, column, item)\n","sub_path":"DT_Bagging.py","file_name":"DT_Bagging.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"347002632","text":"import tkinter as tk\nfrom enum import Enum\nfrom tkinter import ttk\n\nfrom conway_main import Universe\n\n\nclass GameStatus(Enum):\n PAUSE = 0\n ONGOING = 1\n\nclass GameOfLife(tk.Frame):\n WIDTH = 803\n HEIGHT = 506\n\n def __init__(self, master=None):\n super().__init__(master)\n self.pack()\n self.canvas = tk.Canvas(self, width=self.WIDTH, height=self.HEIGHT)\n self.canvas.pack(side=tk.TOP)\n # self.control_info = tk.Frame(self)\n # self.control_info.pack(side=tk.TOP, fill=tk.X)\n # self.start_button = tk.Button(self.control_info, text='Start', command=self.start)\n # self.start_button.pack(side=tk.RIGHT)\n # self.pause_button = tk.Button(self.control_info, text='Pause', command=self.pause)\n # self.pause_button.pack(side=tk.RIGHT)\n # # self.reset_button = tk.Button(self.control_area, text='Random Input', command=self.reset)\n # # self.reset_button.pack(side=tk.LEFT, padx=3, pady=2)\n # self.generation_text_var = tk.StringVar()\n # self.generation_text = tk.Label(self.control_info, textvariable=self.generation_text_var)\n # self.generation_text.pack()\n\n self.control_area = tk.Frame(self)\n self.control_area.config(bg=\"#808080\")\n self.control_area.pack(side=tk.BOTTOM, fill=tk.X)\n self.create_widgets()\n\n dim = (25, 40)\n nos = 100\n self.u = Universe(dim)\n self.nseed = nos\n\n self.status = GameStatus.ONGOING\n self.reset()\n\n def draw(self):\n if self.status == GameStatus.ONGOING:\n self.canvas.delete('all')\n h, w = self.u.dim\n ds = self.WIDTH / max(h, w)\n for i in range(h):\n for j in range(w):\n if self.u.space[i][j] == 1:\n self.canvas.create_rectangle(\n j*ds, i*ds, j*ds+ds, i*ds+ds, fill=\"green\", outline='#101010')\n else:\n self.canvas.create_rectangle(\n j*ds, i*ds, j*ds+ds, i*ds+ds, fill=\"#808080\")\n self.generation_text_var.set(\"Width: {}, Height: {}, Number of initial seeds: {}\\nGeneration: {} \".\n format(self.u.dim[1], self.u.dim[0], self.nseed, self.u.generation))\n self.u.next_generation()\n self.after(1000, self.draw)\n\n def start(self):\n self.status = GameStatus.ONGOING\n self.draw()\n\n def reset(self):\n self.u.random_reset(self.nseed)\n self.status = GameStatus.ONGOING\n self.draw()\n self.status = GameStatus.PAUSE\n\n def pause(self):\n self.status = GameStatus.PAUSE\n\n def create_widgets(self):\n \"\"\"all widget code is here\"\"\"\n tkvar = tk.StringVar(root)\n # Dictionary with options\n choices = ('Clear', 'Small Glider', 'Glider', 'Exploder', '10 Cell Row', 'Light Weight Spaceship', 'Tumbler',\n 'Gosper Glider Gun')\n self.combo_input = ttk.Combobox(self.control_area, width=25, values=choices, state='readonly')\n self.combo_input.pack(side=tk.LEFT)\n self.combo_input.current(0)\n self.combo_input.bind(\"<>\", self.combo_callback)\n\n self.next = tk.Button(self.control_area, text=\"Next\", command=\"\")\n self.next.pack(side=tk.LEFT, padx=3, pady=2)\n self.start = tk.Button(self.control_area, text=\"Start\", command=self.start)\n self.start.pack(side=tk.LEFT, padx=3, pady=2)\n\n self.stop = tk.Button(self.control_area, text=\"Pause\", fg=\"red\", command=self.pause)\n self.stop.pack(side=tk.LEFT, padx=3, pady=2)\n\n self.stop = tk.Button(self.control_area, text=\"Fast\", fg=\"red\", command=\"\")\n self.stop.pack(side=tk.LEFT, padx=3, pady=2)\n\n self.reset_button = tk.Button(self.control_area, text='Random Input', command=self.reset)\n self.reset_button.pack(side=tk.LEFT, padx=3, pady=2)\n\n self.generation_text_var = tk.StringVar()\n self.gen_label = tk.Label(self.control_area, textvariable=self.generation_text_var, bg=\"#808080\")\n self.gen_label.pack(side=tk.RIGHT, padx=3, pady=2)\n\n def combo_callback(self, eventobj):\n \"\"\"this method get combobox events\"\"\"\n # TODO implement method for initial input types other than random initailistion\n print(self.combo_input.get()) # print name\n print(self.combo_input.current()) # print index\n input_index = self.combo_input.current()\n if input_index == 0 and GameStatus.ONGOING:\n GameStatus.PAUSE\n self.canvas.delete('all')\n GameStatus.ONGOING\n # TODO only clear fill rectangles\n elif input_index == 1:\n print(input_index)\n self.nos = 1000\n elif input_index == 2:\n print(input_index)\n elif input_index == 3:\n print(input_index)\n elif input_index == 4:\n print(input_index)\n elif input_index == 5:\n print(input_index)\n elif input_index == 6:\n print(input_index)\n else:\n print(input_index)\n\nroot = tk.Tk()\nroot.title(\"Conway's Game of Life\")\nroot.resizable(0, 0)\napp = GameOfLife(master=root)\napp.mainloop()\n","sub_path":"main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":5271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"366408481","text":"'''\nGreen Monster GUI Revamp\nContaining VQWK Tab\nCode Commissioned 2019-01-16\nCode by A.J. Zec\nAlarm Handler GUI \nCameron Clarke 2019-05-28\n'''\n\nimport tkinter as tk\nfrom tkinter import ttk\nimport utils as u\nimport bclient as bclient\nimport os\nimport time\nimport gc\nfrom decimal import Decimal\nfrom threading import Thread, Lock\n\n# EPICS\nimport logging\n#import rcdb\nimport subprocess\nimport socket\nfrom datetime import datetime\n\nclass ALARM_LOOP_MONITOR():\n def __init__(self,alarmHandlerGUI):\n self.nLoops = 1\n self.Monitor = True\n #self.alarm_loop_monitor(alarmHandlerGUI)\n\n def alarm_loop_monitor(self,alarmHandlerGUI):\n if (alarmHandlerGUI.alarmLoop.globalLoopStatus==\"Looping\"):\n #if self.Monitor:\n # self.Monitor = False\n #else:\n # self.Monitor = True\n # Recursion loop here - splits off a new instance of this function and finishes the one currently running (be careful) - 30 second loop\n if alarmHandlerGUI.alarmLoop.userNotifyLoop.nLoops <= self.nLoops and self.nLoops>10 and self.Monitor:\n print(\"\\n\\nALERT ALERT: Alarm handler notification loop has been stale for 1 minute\\n\\nRebooting alarm loops - Probably you should just reboot the alarm handler entirely now\\n\\n\")\n self.nLoops = alarmHandlerGUI.alarmLoop.userNotifyLoop.nLoops\n alarmHandlerGUI.win.after(1000*alarmHandlerGUI.OL.cooldownReduction,alarmHandlerGUI.alarmLoop.userNotifyLoop.user_notify_loop, alarmHandlerGUI.alarmLoop,alarmHandlerGUI.OL,alarmHandlerGUI.fileArray,alarmHandlerGUI)\n alarmHandlerGUI.win.after(10000,alarmHandlerGUI.alarmLoop.alarm_loop,alarmHandlerGUI) # Recursion loop here - splits off a new instance of this function and finishes the one currently running (be careful)\n else: \n if self.Monitor:\n print(\"\\n\\nAlarm Handler Health Check passed: 60 second loop's Notify Counter # = {}, notify loop's counter # = {}, should not be the same\\n\\n\".format(self.nLoops,alarmHandlerGUI.alarmLoop.userNotifyLoop.nLoops))\n self.nLoops = alarmHandlerGUI.alarmLoop.userNotifyLoop.nLoops\n alarmHandlerGUI.win.after(30000*alarmHandlerGUI.OL.cooldownReduction,self.alarm_loop_monitor,alarmHandlerGUI)\n\nclass ALARM_LOOP_GUI():\n def __init__(self,alarmHandlerGUI):\n pass\n\n def GUI_loop(self,alarmHandlerGUI):\n gc.collect()\n del gc.garbage[:]\n if (alarmHandlerGUI.alarmLoop.globalLoopStatus==\"Looping\"):\n print(\"Active mode: waited 5 seconds, refreshing GUI\")\n u.update_objectList(alarmHandlerGUI.OL,alarmHandlerGUI.alarmLoop.alarmList)\n u.write_textfile(alarmHandlerGUI.OL,alarmHandlerGUI.fileArray) #FIXME Do this here?\n if alarmHandlerGUI.tabs.get(\"Alarm Handler\",u.defaultKey) != u.defaultKey:\n alarmHandlerGUI.tabs[\"Alarm Handler\"].refresh_screen(alarmHandlerGUI.OL,alarmHandlerGUI.fileArray,alarmHandlerGUI.alarmLoop,alarmHandlerGUI.HL)\n if alarmHandlerGUI.tabs.get(\"Grid Alarm Handler\",u.defaultKey) != u.defaultKey:\n alarmHandlerGUI.tabs[\"Grid Alarm Handler\"].refresh_screen(alarmHandlerGUI.OL,alarmHandlerGUI.fileArray,alarmHandlerGUI.alarmLoop,alarmHandlerGUI.HL)\n if alarmHandlerGUI.tabs.get(\"Expert Alarm Handler\",u.defaultKey) != u.defaultKey:\n alarmHandlerGUI.tabs[\"Expert Alarm Handler\"].refresh_screen(alarmHandlerGUI.OL,alarmHandlerGUI.fileArray,alarmHandlerGUI.alarmLoop,alarmHandlerGUI.HL)\n if alarmHandlerGUI.tabs.get(\"Active Alarm Handler\",u.defaultKey) != u.defaultKey:\n alarmHandlerGUI.tabs[\"Active Alarm Handler\"].refresh_screen(alarmHandlerGUI.OL,alarmHandlerGUI.fileArray,alarmHandlerGUI.alarmLoop,alarmHandlerGUI.HL)\n if alarmHandlerGUI.tabs.get(\"Alarm History\",u.defaultKey) != u.defaultKey:\n alarmHandlerGUI.tabs[\"Alarm History\"].refresh_screen(alarmHandlerGUI.OL,alarmHandlerGUI.fileArray,alarmHandlerGUI.alarmLoop,alarmHandlerGUI.HL)\n if alarmHandlerGUI.tabs.get(\"Settings\",u.defaultKey) != u.defaultKey:\n alarmHandlerGUI.tabs[\"Settings\"].refresh_screen(alarmHandlerGUI)\n alarmHandlerGUI.masterAlarmButton.destroy()\n if alarmHandlerGUI.alarmLoop.globalAlarmStatus == \"OK\":\n alarmHandlerGUI.masterAlarmImage = tk.PhotoImage(file='ok.ppm').subsample(2)\n alarmHandlerGUI.masterAlarmButton = tk.Label(alarmHandlerGUI.win, image=alarmHandlerGUI.masterAlarmImage, cursor=\"hand2\", bg=u.lightgrey_color)\n alarmHandlerGUI.masterAlarmButton.image = tk.PhotoImage(file='ok.ppm').subsample(2)\n if alarmHandlerGUI.alarmLoop.globalAlarmStatus != \"OK\":\n alarmHandlerGUI.masterAlarmImage = tk.PhotoImage(file='alarm.ppm').subsample(2)\n alarmHandlerGUI.masterAlarmButton = tk.Label(alarmHandlerGUI.win, image=alarmHandlerGUI.masterAlarmImage, cursor=\"hand2\", bg=u.lightgrey_color)\n alarmHandlerGUI.masterAlarmButton.image = tk.PhotoImage(file='alarm.ppm').subsample(2)\n alarmHandlerGUI.masterAlarmButton.grid(rowspan=3, row=1, column=0, padx=5, pady=10, sticky='NESW')\n alarmHandlerGUI.masterAlarmButton.bind(\"\", alarmHandlerGUI.update_show_alarms)\n alarmHandlerGUI.win.after(5000,self.GUI_loop, alarmHandlerGUI) # Recursion loop here - splits off a new instance of this function and finishes the one currently running (be careful)\n if (alarmHandlerGUI.alarmLoop.globalLoopStatus==\"Paused\"):\n alarmHandlerGUI.win.after(5000,self.GUI_loop, alarmHandlerGUI) # Recursion loop here - splits off a new instance of this function and finishes the one currently running (be careful)\n print(\"In sleep mode: waited 5 seconds to refresh GUI again\")\n gc.collect()\n del gc.garbage[:]\n\nclass ALARM_LOOP():\n def __init__(self,alarmHandlerGUI):\n self.alarmList = alarmHandlerGUI.OL.objectList # FIXME am I sure that this is a copy by pointer? Is it even necessary to make it a class object?\n #print(\"Initializing, adding alarm list parameterList = {}\".format(alarmHandlerGUI.OL.objectList[i].alarm.parameterList))\n self.globalAlarmStatus = \"OK\" # Start in non-alarmed state\n self.checkExternalStatus = True # Check the externalAlarms.csv file\n self.globalLoopStatus = \"Looping\" # Start in looping state\n self.globalUserAlarmSilence = \"Alert\"\n self.userNotifyLoop = USER_NOTIFY(self)\n self.userNotifyLoop.user_notify_loop(self,alarmHandlerGUI.OL,alarmHandlerGUI.fileArray,alarmHandlerGUI)\n \n def ok_notify_check(self,checkNotifyStatus):\n checkedStat = \"OK\"\n if checkNotifyStatus != \"OK\":\n if checkNotifyStatus.split(' ')[0] == \"Cooldown\":\n #print(\"Checked if we are in a countdown, we are, status = {}\".format(checkNotifyStatus))\n checkedStat = \"OK\"\n else:\n #print(\"Checked if we are in a countdown, we are not, status = {}\".format(checkNotifyStatus))\n checkedStat = checkNotifyStatus\n return checkedStat\n\n def ok_notify_update(checkNotifyStatus,reduction):\n checkedStat = \"OK\"\n if checkNotifyStatus != \"OK\":\n tmpCheck = checkNotifyStatus.split(' ')\n if tmpCheck[0] == \"Cooldown\":\n if tmpCheck[1] != '':\n checkedStat = \"Cooldown {}\".format(int(tmpCheck[1])-reduction)\n if int(tmpCheck[1]) <= reduction:\n checkedStat = \"OK\" # Reset\n else:\n checkedStat = checkNotifyStatus\n return checkedStat\n \n # Add the external alarms file info into the objectList, etc.\n def doExternal(self,alarmHandlerGUI):\n if os.path.exists(alarmHandlerGUI.externalFilename) and self.checkExternalStatus == True and (time.time() - os.path.getmtime(alarmHandlerGUI.externalFilename)) < alarmHandlerGUI.externalParameterFileStaleTime:\n #print(\"Adding External alarms from {}\".format(alarmHandlerGUI.externalFileArray.filename))\n u.update_extra_filearray(alarmHandlerGUI.fileArray,alarmHandlerGUI.externalFileArray)\n # FIXME these two lines seem to be unnccessary CPU time ... are we gaining any clarity by refreshing internal memory?\n alarmHandlerGUI.OL.objectList.clear() # FIXME is this necessary?\n alarmHandlerGUI.OL.objectList = u.create_objects(alarmHandlerGUI.fileArray,alarmHandlerGUI.OL.cooldownLength) # FIXME Necessary?\n alarmHandlerGUI.OL.keys.clear() # FIXME is this necessary?\n alarmHandlerGUI.OL.keys = u.create_objects_keys(alarmHandlerGUI.fileArray)\n for i in range(0,len(alarmHandlerGUI.OL.keys)):\n alarmHandlerGUI.OL.objectList[alarmHandlerGUI.OL.keys[i]].index = i\n # This should be a copy by pointer - as I want the editting of alarmList to fully edit entries in objectList .... is this the right way to do things? FIXME FIXME \n self.alarmList = alarmHandlerGUI.OL.objectList\n gc.collect()\n del gc.garbage[:]\n u.write_textfile(alarmHandlerGUI.OL,alarmHandlerGUI.fileArray) #FIXME Do this here?\n else:\n print(\"No extra alarm files found\")\n\n def doAlarmChecking(self,alarmHandlerGUI):\n print(\"\\n - Global Alarm Status: \")\n localAlStat = 0\n for key,alrm in self.alarmList.items():\n # FIXME This is what I want to replace the above line with, using the object list dictionary of ALARM_OBJECT rather than their ALARMs\n # for i in range (0,len(alarmHandlerGUI.OL.objectList)):\n Thread(target=alrm.alarm_analysis).start()\n if alrm.parameterList[\"Alarm Status\"] != \"OK\":\n #print(\" -- Alarm {}: {}, {} = {}\".format(alrm.parameterList[\"Alarm Status\"],key,alrm.name,alrm.value))\n localAlStat += 1\n Thread(target=alrm.alarm_evaluate).start()\n # Check if the alarm is alarming and has not been \"OK\"ed by the user acknowledge\n #print(\"Checking alarm {} alarm status = {}, silence status = {}, and user acknowledge = {}\".format(i,alrm.alarmSelfStatus,alrm.userSilenceSelfStatus,self.ok_notify_check(alrm.userNotifySelfStatus)))\n # If the userNotifyStatus is NULL (i.e. not set) then the alarm handler will just read it and move on with its life\n if self.globalUserAlarmSilence == \"Alert\" and self.ok_notify_check(alrm.userNotifyStatus) != \"OK\" and alrm.userSilenceStatus == \"Alert\":\n # Just let the method I wrote take care of determining global alarm status\n self.globalAlarmStatus = alrm.userNotifyStatus # Update global alarm status\n u.append_historyList(alarmHandlerGUI.HL,alarmHandlerGUI.OL,key) # Update Alarm History\n localStat = alrm.userNotifyStatus\n if localAlStat == 0:\n print(' -- '+'\\x1b[1;1;32m'+'Alarms all OK '+'\\x1b[0m'+'\\n')\n else:\n print(' -- '+'\\x1b[1;1;31m'+'{} alarms triggered '.format(localAlStat)+'\\x1b[0m'+'\\n')\n\n def alarm_loop(self,alarmHandlerGUI):\n if (self.globalLoopStatus==\"Looping\"):\n print(\"Waited 10 seconds, analyzing alarms\")\n Thread(self.doExternal(alarmHandlerGUI)).start()\n localStat = \"OK\"\n self.doAlarmChecking(alarmHandlerGUI)\n if localStat == \"OK\":\n self.globalAlarmStatus = \"OK\"\n else:\n print(\"Global Alarm Alarmed\")\n u.update_objectList(alarmHandlerGUI.OL,self.alarmList) # If I am doing a copy by pointer this operation is entirely redundant... right? FIXME FIXME FIXME\n u.write_historyFile(alarmHandlerGUI.HL)\n alarmHandlerGUI.win.after(10000,self.alarm_loop, alarmHandlerGUI) # Recursion loop here - splits off a new instance of this function and finishes the one currently running (be careful)\n if (self.globalLoopStatus==\"Paused\"):\n alarmHandlerGUI.win.after(10000,self.alarm_loop, alarmHandlerGUI) # Recursion loop here - splits off a new instance of this function and finishes the one currently running (be careful)\n print(\"In sleep mode: waited 10 seconds to try to check alarm status again\")\n\nclass USER_NOTIFY():\n def __init__(self,alarmLoop):\n self.nLoops = 0\n\n def user_notify_loop(self,alarmLoop,OL,fileArray,alarmHandlerGUI):\n self.nLoops = self.nLoops + 1\n localStat = \"OK\"\n alarmHandlerGUI.alertTheUserSoundNow = alarmHandlerGUI.alertTheUserSound # Default = 7 every restart of loop\n for key,alrm in alarmLoop.alarmList.items():\n alrm.alarm_evaluate()\n # Check if the alarm is alarming and has not been \"OK\"ed by the user acknowledge\n #print(\"Checking alarm {} alarm status = {}, silence status = {}, and user acknowledge = {}\".format(i,alrm.alarmSelfStatus,alrm.userSilenceSelfStatus,alarmLoop.ok_notify_check(alrm.userNotifySelfStatus)))\n # If the userNotifyStatus is NULL (i.e. not set) then the alarm handler will just read it and move on with its life\n if alarmLoop.globalUserAlarmSilence == \"Alert\" and alarmLoop.ok_notify_check(alrm.userNotifyStatus) != \"OK\" and alrm.userSilenceStatus == \"Alert\":\n # Just let the method I wrote take care of determining global alarm status\n #print(\"Alert status = {}\".format(alrm.alertSound))\n alarmLoop.globalAlarmStatus = alrm.userNotifyStatus # Update global alarm status\n if alrm.alertSound != alarmHandlerGUI.alertTheUserSound:\n alarmHandlerGUI.alertTheUserSoundNow = alrm.alertSound # Update global alarm sound\n u.append_historyList(alarmHandlerGUI.HL,alarmHandlerGUI.OL,key) # Update Alarm History\n localStat = alrm.userNotifyStatus\n if localStat == \"OK\":\n alarmLoop.globalAlarmStatus = \"OK\"\n else:\n print(\"Global Alarm Alarmed\")\n if (alarmLoop.globalLoopStatus==\"Looping\" and alarmLoop.globalUserAlarmSilence == \"Alert\"):\n self.update_user_notify_status(alarmLoop,OL,fileArray) # Assumes OK, checks each OL.objectList[2] entry for its notify status, continues\n if alarmHandlerGUI.alertTheUser == True and alarmLoop.globalAlarmStatus != \"OK\": # globalAlarmStatus determined by these set acknowledged stati\n try:\n if alarmHandlerGUI.alertTheUserSoundNow != alarmHandlerGUI.alertTheUserSound:\n alarmHandlerGUI.alarmClient.sendPacket(alarmHandlerGUI.alertTheUserSoundNow) \n else:\n alarmHandlerGUI.alarmClient.sendPacket(alarmHandlerGUI.alertTheUserSound)\n except:\n print(\"Alarm Sound Server not running\\nPlease Launch an instance on the EPICS computer\\nssh hacuser@hacweb7, cd parity-alarms, ./bserver&\")\n # Recursion loop here - splits off a new instance of this function and finishes the one currently running (be careful)\n alarmHandlerGUI.win.after(1000*OL.cooldownReduction,self.user_notify_loop, alarmLoop,OL,fileArray,alarmHandlerGUI) \n else: \n # Recursion loop here - splits off a new instance of this function and finishes the one currently running (be careful) - Wait longer if paused, no need to overkill \n alarmHandlerGUI.win.after(1000*OL.cooldownReduction,self.user_notify_loop, alarmLoop,OL,fileArray,alarmHandlerGUI) \n\n def update_user_notify_status(self,alarmLoop,OL,fileArray):\n for key in OL.objectList.keys():\n tmpUNS = \"OK\" # Assume its ok, then update with the alarmList's \"self\" values\n if OL.objectList[key].userNotifyStatus != \"OK\":\n tmpCheck = OL.objectList[key].userNotifyStatus.split(' ')\n if tmpCheck[0] == \"Cooldown\":\n if tmpCheck[1] != '':\n print(\"In cooldown save region - actually cooling down\")\n tmpUNS = \"Cooldown {}\".format(int(tmpCheck[1])-OL.cooldownReduction)\n if int(tmpCheck[1]) <= OL.cooldownReduction:\n tmpUNS = \"OK\" # Reset upond 2nd click\n print(\"In cooldown save region - cooldown over, now we're OK\")\n else: # it isn't a Cooldown # array, so just take the 0th element\n tmpUNS = tmpCheck[0]\n #print(\"COOL: Saving to file [{}][{}] userNotifyStatus = {}\".format(2,e,tmpUNS))\n OL.objectList[key].parameterList[\"User Notify Status\"] = tmpUNS\n OL.objectList[key].userNotifyStatus = tmpUNS\n # FIXME Depreciated - filearray gets wiped when written anyway right?\n #for t in range(OL.objectList[key].indexStart,OL.objectList[key].indexEnd+1):\n # if fileArray.filearray[t][3] == \"User Notify Status\":\n # fileArray.filearray[t][4] = tmpUNS\n # # Update the object list all children's user notify status\n \nclass FILE_ARRAY():\n def __init__(self,filen,delimiter):\n self.mutex = Lock()\n self.filename = filen\n self.delim = delimiter\n self.conf = {}\n self.filearray = [[]]\n self.filearray = u.parse_textfile(self)\n\nclass HISTORY_LIST():\n def __init__(self,filen,delimiter,pdelimiter,time):\n self.mutex = Lock()\n self.currentHist = -1\n self.displayPList = 0\n self.timeWait = time\n self.filename = filen\n self.delim = delimiter\n self.paramDelim = pdelimiter\n self.filearray = [[]]\n self.filearray = u.parse_textfile(self) # Reads text file just like fileArray, same names so Python doesn't know the difference\n self.historyList = u.init_historyList(self)\n\n# FIXME The Object List class is full of old features that need to be removed and streamlined\nclass OBJECT_LIST():\n def __init__(self,fileArray,cooldownLength):\n self.objectList = u.create_objects(fileArray,cooldownLength)\n self.keys = u.create_objects_keys(fileArray)\n if self.keys == None or len(self.keys) == 0:\n print(\"Null alarm input file, please resolve in configure file\")\n else:\n for i in range(0,len(self.keys)):\n self.objectList[self.keys[i]].index = i\n self.currentlySelectedButton = -1\n self.displayPList = 0\n self.cooldownLength = cooldownLength # Wait a minute before alarming again\n # FIXME this time step should be from the config file too\n self.cooldownReduction = 2\n # These three lists need to be removed and just use self.currentlySelectedButton...\n\n # FIXME Depreciated chunk clicking feature here - replace with just click...\n def set_clicked(self,i,j):\n self.currentlySelectedButton = j\n self.objectList[self.keys[j]].click(1)\n\nclass ALARM_OBJECT():\n def __init__(self):\n # Needed parameters\n self.name = \"NULL\"\n self.value = \"NULL\"\n self.parameterList = {} # Using a dictionary makes life much easier\n self.color = u.lightgrey_color\n self.alarmStatus = \"OK\"\n self.userSilenceStatus = \"Alert\"\n self.userNotifyStatus = \"OK\"\n # Should come from the config file?\n self.alertSound = \"7\"\n self.cooldownLength = 60 # Default initialize, will be overwritten later\n #self.parameterList[\"User Silence Status\"] = self.userSilenceStatus\n # FIXME FIXME old version.... needed a lambda!??\n #self.alarm = lambda: ALARM(self);\n self.clicked = 0\n\n # FIXME Depreciated\n self.index = 0\n self.parameterListHistory = [] # Every time we update parameterList pass its prior value to history ... let actually accumulating of values take place in alarmLoop if wanted...\n\n # Old \"ALARM\" Class initializer remnants\n self.alarmAnalysisReturn = None # For camguin outputs to stdout to catch\n self.alarmErrorReturn = None\n self.runNumber = 0\n self.alarmType = self.parameterList.get(\"Alarm Type\",u.defaultKey)\n # Default alarm criteria is whether the value is not-null and otherwise is defined on context from given parameterList entries\n # Do I need to make a lambda initialized instance of the alarm action per event? I don't think this matters like it did for button context menu placements.... especially since these actions are being taken by the alarm handler in a loop over objectList\n #print(\"Initializing new alarm for object {}, name = {}\".format(self.index,self.name+\" \"+self.value))\n self.alarm_analysis = lambda : self.do_alarm_analysis()\n self.alarm_evaluate = lambda : self.do_alarm_evaluate() # Just keep this stub here in case\n\n def click(self,clickStat):\n self.clicked = clickStat\n if (clickStat == 0 and self.alarmStatus == \"OK\"):\n self.color = u.lightgrey_color\n if (clickStat == 1 and self.alarmStatus == \"OK\"):\n self.color = u.grey_color\n #if (clickStat == 0 and self.alarmStatus == 1):\n #if self.alarmStatus != \"OK\":\n # self.color = self.color #FIXME col #3 still == red problem in expert mode? \n #if self.alarmStatus != \"OK\" and self.userSilenceStatus == \"Alert\":\n # self.color = u.red_color\n #if self.userSilenceStatus == \"Silenced\":\n # self.color = u.darkgrey_color\n\n # FIXME FIXME super depreciated value style adding\n def add_parameter(self,obj1,obj2): # Updates dictionary with new value, appends or edits appropriately, but names are the keys... so be careful\n self.parameterList[obj1.value]=obj2.value\n\n # FIXME FIXME super depreciated history method\n def add_parameter_history(self,val_append):\n self.parameterListHistory.append(val_append)\n # add a pair to a list of parameter names and values\n\n def polish_alarm_object(self):\n # Silence status\n if \"Value\" not in self.parameterList:\n self.parameterList[\"Value\"] = \"NULL\"\n self.value = self.parameterList[\"Value\"]\n if \"User Silence Status\" not in self.parameterList:\n self.parameterList[\"User Silence Status\"] = \"Alert\"\n self.userSilenceStatus = self.parameterList[\"User Silence Status\"]\n if self.alarmStatus != \"OK\" and self.userSilenceStatus == \"Alert\":\n self.color = u.red_color\n elif self.userSilenceStatus == \"Silenced\":\n self.color = u.yellow_color\n elif self.alarmStatus == \"OK\" and self.userSilenceStatus != \"Silenced\":\n self.color = u.lightgrey_color\n\n # Alarm status\n if \"Alarm Status\" not in self.parameterList:\n self.parameterList[\"Alarm Status\"] = \"OK\"\n self.alarmStatus = self.parameterList[\"Alarm Status\"]\n if self.alarmStatus != \"OK\":\n self.color = u.red_color\n if self.userSilenceStatus == \"Silenced\":\n self.color = u.yellow_color\n\n if \"User Notify Status\" not in self.parameterList:\n self.parameterList[\"User Notify Status\"] = \"OK\"\n self.userNotifyStatus = self.parameterList[\"User Notify Status\"]\n if self.userSilenceStatus == \"Silenced\":\n self.parameterList[\"User Notify Status\"] = \"OK\"\n elif self.alarmStatus != \"OK\" and self.userNotifyStatus.split(' ')[0] != \"Cooldown\":\n self.parameterList[\"User Notify Status\"] = self.alarmStatus\n # FIXME what was this ELSE for?\n #else:\n # self.parameterList[\"User Notify Status\"] = self.value\n self.userNotifyStatus = self.parameterList[\"User Notify Status\"]\n if \"Alarm Type\" not in self.parameterList:\n self.parameterList[\"Alarm Type\"] = \"BASH\"\n self.alarmType = self.parameterList[\"Alarm Type\"]\n\n def do_alarm_analysis(self):\n if \"Camguin\" in self.alarmType: # Alarm Type is the parameter (level 4 object) which keeps track of what analysis to do\n subprocess(\"root -L camguin_C.so({},{},{},{},{},{},{},{},{},{},{})\".format(self.parameterList[\"Analysis\"],self.parameterList[\"Tree\"],self.parameterList[\"Branch\"],self.parameterList[\"Leaf\"],self.parameterList[\"Cuts\"],int(self.parameterList[\"Ignore Event Cuts\"]),self.parameterList[\"Hist Rebinning\"],int(self.parameterList[\"Stability Ring Length\"]),self.runNumber,1,0.0), stdout=self.alarmAnalysisReturn, stderr=self.alarmErrorReturn, timeout=30)\n\n # FIXME Bash and EPICS are basically the same - find a way to merge them\n if \"BASH\" in self.alarmType: # Alarm Type parameter (level 4) for indicating that the return value is some special bash script\n if self.parameterList.get(\"Script Name\",u.defaultKey) != \"NULL\":\n #print(\"Checking Script = {}\".format(self.parameterList.get(\"Script Name\",u.defaultKey)))\n cmds = [self.parameterList.get(\"Script Name\",u.defaultKey)]\n cond_out = \"NULL\"\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Needs to be decoded... be careful \n except:\n print(\"Failed: {}\".format(cmds))\n print(\"TEST 1: {}\".format(cond_out))\n if \"not found\" in str(cond_out): # Then the Script was invalid\n print(\"Error: command {} not found\".format(self.parameterList.get(\"Script Name\",u.defaultKey)))\n cond_out = \"NULL\"\n self.parameterList[\"Value\"] = cond_out\n if self.parameterList.get(\"Threshold Variable Name\",u.defaultKey) != \"NULL\" and self.parameterList.get(\"Script Name\",u.defaultKey) != \"NULL\":\n cmds = [self.parameterList.get(\"Script Name\",u.defaultKey),self.parameterList.get(\"Threshold Variable Name\",u.defaultKey)]\n cond_out = \"NULL\"\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Needs to be decoded... be careful \n except:\n print(\"Failed: {}\".format(cmds))\n if \"not found\" in str(cond_out): # Then the Script was invalid\n print(\"Error: command {} not found\".format(self.parameterList.get(\"Script Name\",u.defaultKey)))\n cond_out = u.defaultKey\n \n self.parameterList[\"Threshold Value\"] = cond_out\n if self.parameterList.get(\"Threshold 2 Variable Name\",u.defaultKey) != \"NULL\" and self.parameterList.get(\"Script Name\",u.defaultKey) != \"NULL\":\n cmds = [self.parameterList.get(\"Script Name\",u.defaultKey),self.parameterList.get(\"Threshold 2 Variable Name\",u.defaultKey)]\n cond_out = \"NULL\"\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Needs to be decoded... be careful \n except:\n print(\"Failed: {}\".format(cmds))\n if \"not found\" in str(cond_out): # Then the Script was invalid\n print(\"Error: command {} not found\".format(self.parameterList.get(\"Script Name\",u.defaultKey)))\n cond_out = u.defaultKey\n \n self.parameterList[\"Threshold 2 Value\"] = cond_out\n if self.parameterList.get(\"Case Variable Name\",u.defaultKey) != \"NULL\" and self.parameterList.get(\"Script Name\",u.defaultKey) != \"NULL\":\n cmds = [self.parameterList.get(\"Script Name\",u.defaultKey),self.parameterList.get(\"Case Variable Name\",u.defaultKey)]\n cond_out = \"NULL\"\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Needs to be decoded... be careful \n except:\n print(\"Failed: {}\".format(cmds))\n if \"not found\" in str(cond_out): # Then the Script was invalid\n print(\"Error: command {} not found\".format(self.parameterList.get(\"Script Name\",u.defaultKey)))\n cond_out = \"BAD\"\n \n self.parameterList[\"Case Value\"] = cond_out\n if self.parameterList.get(\"Double Case Variable Name\",u.defaultKey) != \"NULL\" and self.parameterList.get(\"Script Name\",u.defaultKey) != \"NULL\":\n cmds = [self.parameterList.get(\"Script Name\",u.defaultKey),self.parameterList.get(\"Double Case Variable Name\",u.defaultKey)]\n cond_out = \"NULL\"\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Needs to be decoded... be careful \n except:\n print(\"Failed: {}\".format(cmds))\n if \"not found\" in str(cond_out): # Then the epics Script was invalid\n print(\"Error: command {} not found\".format(self.parameterList.get(\"Script Name\",u.defaultKey)))\n cond_out = \"BAD\"\n self.parameterList[\"Double Case Value\"] = cond_out\n if (self.parameterList.get(\"Same Value Comparator\",u.defaultKey) != \"NULL\" or self.parameterList.get(\"Same Value Comparator {}\".format(self.parameterList.get(\"Case Value\",u.defaultKey)),u.defaultKey) != \"NULL\" or self.parameterList.get(\"Same Value Comparator {}\".format(self.parameterList.get(\"Double Case Value\",u.defaultKey)),u.defaultKey) != \"NULL\") and self.parameterList.get(\"Script Name\",u.defaultKey) != \"NULL\":\n cmds = [self.parameterList.get(\"Script Name\",u.defaultKey)]\n cond_out = \"NULL\"\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Needs to be decoded... be careful \n except:\n print(\"Failed: {}\".format(cmds))\n if \"not found\" in str(cond_out): # Then the Script was invalid\n print(\"Error: command {} not found\".format(self.parameterList.get(\"Script Name\",u.defaultKey)))\n cond_out = \"BAD\"\n \n if self.parameterList.get(\"Same Value Comparator\",u.defaultKey) != \"NULL\":\n self.parameterList[\"Same Value Comparator 2\"] = self.parameterList[\"Same Value Comparator\"]\n self.parameterList[\"Same Value Comparator\"] = cond_out\n if self.parameterList.get(\"Same Value Comparator {}\".format(self.parameterList.get(\"Case Value\",u.defaultKey)),u.defaultKey) != \"NULL\":\n self.parameterList[\"Same Value Comparator 2 {}\".format(self.parameterList.get(\"Case Value\",u.defaultKey))] = self.parameterList[\"Same Value Comparator {}\".format(self.parameterList.get(\"Case Value\",u.defaultKey))]\n self.parameterList[\"Same Value Comparator {}\".format(self.parameterList.get(\"Case Value\",u.defaultKey))] = cond_out\n if self.parameterList.get(\"Same Value Comparator {}\".format(self.parameterList.get(\"Double Case Value\",u.defaultKey)),u.defaultKey) != \"NULL\":\n self.parameterList[\"Same Value Comparator 2 {}\".format(self.parameterList.get(\"Double Case Value\",u.defaultKey))] = self.parameterList[\"Same Value Comparator {}\".format(self.parameterList.get(\"Double Case Value\",u.defaultKey))]\n self.parameterList[\"Same Value Comparator {}\".format(self.parameterList.get(\"Double Case Value\",u.defaultKey))] = cond_out\n\n if \"CODA\" in self.alarmType or \"RCND\" in self.alarmType or \"RCDB\" in self.alarmType or \"PVDB\" in self.alarmType:\n # TEMP FIXME Do the CODA on/taking good data (split = 0, EB alive) here... why not?\n #CODAonAlarm = \"NULL\"\n #CODAonAlarmReturn = \"NULL\"\n #subprocess(\"./checkIfRun\", shell=True, stdout=CODAonAlarm, stderr=CODAonAlarmReturn, timeout=10)\n runNumber = 0\n if self.parameterList.get(\"Run Number\",u.defaultKey) != 0 and self.parameterList.get(\"Run Number\",u.defaultKey) != \"NULL\":\n runNumber = self.parameterList.get(\"Run Number\")\n else:\n runNumber = self.get_run_number()\n new_runNumber = self.get_run_number()\n if runNumber != new_runNumber: # Then this is a new run, update new run type alarms\n print(\"Original run number = {}, New Run number = {}\".format(self.runNumber,new_runNumber))\n if self.parameterList.get(\"Variable Name\",u.defaultKey) == \"Run Number\":\n self.parameterList[\"Low\"] = self.runNumber\n self.parameterList[\"Value\"] = new_runNumber # Update the run number\n if self.parameterList.get(\"Variable Name\",u.defaultKey) == \"Run Start Time\":\n self.parameterList[\"Start Time\"] = int(time.time())\n self.parameterList[\"Value\"] = 0# int(time.time()) # Update the time value\n self.parameterList[\"High\"] = 80*60 #int(time.time()) + 80*60\n self.runNumber = new_runNumber\n self.parameterList[\"Run Number\"] = new_runNumber\n else:\n if self.parameterList.get(\"Variable Name\",u.defaultKey) == \"Run Start Time\" and self.parameterList.get(\"Start Time\",u.defaultKey) != \"NULL\":\n self.parameterList[\"Value\"] = int(time.time()) - int(self.parameterList.get(\"Start Time\",u.defaultKey)) # Update the time value\n \n if self.parameterList.get(\"Variable Name\",u.defaultKey) != \"Run Start Time\" and self.parameterList.get(\"Variable Name\",u.defaultKey) != \"Run Number\": # Else update other alarms\n cmds = ['rcnd',self.runNumber,self.parameterList[\"Variable BName\"]]\n cond_out = \"NULL\"\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Decoding...\n except:\n print(\"Failed: {}\".format(cmds))\n self.parameterList[\"Value\"] = cond_out\n\n if \"EPICS\" in self.alarmType:\n if self.parameterList.get(\"Variable Name\",u.defaultKey) != \"NULL\":\n #print(\"Checking EPICs variable = {}\".format(self.parameterList.get(\"Variable Name\",u.defaultKey)))\n cmds = ['caget', '-t', '-w 1', self.parameterList[\"Variable Name\"]]\n cond_out = \"NULL\"\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Needs to be decoded... be careful \n except:\n print(\"Failed: {}\".format(cmds))\n #print(\"The epics output for variable {} is {}\".format(self.parameterList[\"Variable Name\"],cond_out))\n if \"Invalid\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR Invalid epics channel, check with caget again:\\t {}\".format(self.parameterList[\"Variable Name\"]))\n cond_out = \"NULL\"\n if \"not found\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR caget missing!!\")\n cond_out = \"NULL\"\n self.parameterList[\"Value\"] = cond_out\n elif self.parameterList.get(\"IOC Alarm List Name\",u.defaultKey) != \"NULL\":\n #print(\"Checking EPICs variable = {}\".format(self.parameterList.get(\"Variable Name\",u.defaultKey)))\n listNames = ['.B1','.B2','.B3','.B4','.B5','.B6','.B7','.B8','.B9','.BA']\n cond_out = \"NULL\"\n cmds = [\"NULL\"]\n if self.parameterList.get(\"Current Variable\",u.defaultKey) != \"NULL\":\n cmds = ['caget', '-t', '-w 1', self.parameterList[\"Current Variable\"]]\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Needs to be decoded... be careful \n except:\n print(\"Failed: {}\".format(cmds))\n if \"Invalid\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR Invalid epics channel, check with caget again:\\t {}\".format(self.parameterList.get(\"Variable Name\",u.defaultKey)))\n cond_out = \"NULL\"\n if \"not found\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR caget missing!!\")\n cond_out = \"NULL\"\n elif u.is_number(cond_out) and Decimal(cond_out) > 35.0:\n for eachName in listNames:\n cmds = ['caget', '-t', '-w 1', self.parameterList[\"IOC Alarm List Name\"]+eachName]\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Needs to be decoded... be careful \n except:\n print(\"Failed: {}\".format(cmds))\n if cond_out == \"1\":\n self.parameterList[\"Value\"] = cond_out;\n #print(\"The epics output for variable {} is {}\".format(self.parameterList[\"Variable Name\"],cond_out))\n if \"Invalid\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR Invalid epics channel, check with caget again:\\t {}\".format(self.parameterList.get(\"Variable Name\",u.defaultKey)))\n cond_out = \"NULL\"\n if \"not found\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR caget missing!!\")\n cond_out = \"NULL\"\n self.parameterList[\"Value\"] = cond_out\n else: \n self.parameterList[\"Value\"] = \"0\"\n else: # User didn't have \"Value\" in their parameter list, add it and make it init to NULL\n self.parameterList[\"Variable Name\"] = \"NULL\"\n self.parameterList[\"Value\"] = \"NULL\"\n if self.parameterList.get(\"Difference Reference Variable Name\",u.defaultKey) != \"NULL\":\n #print(\"Checking EPICs variable = {}\".format(self.parameterList.get(\"Difference Reference Variable Name\",u.defaultKey)))\n cmds = ['caget', '-t', '-w 1', self.parameterList[\"Difference Reference Variable Name\"]]\n cond_out = \"NULL\"\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Needs to be decoded... be careful \n except:\n print(\"Failed: {}\".format(cmds))\n #print(\"The epics output for variable {} is {}\".format(self.parameterList[\"Variable Name\"],cond_out))\n if \"Invalid\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR Invalid epics channel, check with caget again:\\t {}\".format(self.parameterList[\"Difference Reference Variable Name\"]))\n cond_out = \"NULL\"\n if \"not found\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR caget missing!!\")\n cond_out = \"NULL\"\n self.parameterList[\"Difference Reference Value\"] = cond_out\n if self.parameterList.get(\"Value\",u.defaultKey) != \"NULL\" and self.parameterList.get(\"Difference Reference Value\") != \"NULL\":\n # FIXME HACKED this to just go ahead and take the difference here. Reference value is now only stored in file for user knowledge\n self.parameterList[\"Value\"] = str(Decimal(self.parameterList[\"Value\"]) - Decimal(self.parameterList[\"Difference Reference Value\"]))\n #else: # User didn't have \"Value\" in their parameter list, add it and make it init to NULL\n # self.parameterList[\"Difference Reference Variable Name\"] = \"NULL\"\n # self.parameterList[\"Difference Reference Value\"] = \"NULL\"\n if self.parameterList.get(\"Threshold Variable Name\",u.defaultKey) != \"NULL\":\n cmds = ['caget', '-t', '-w 1', self.parameterList[\"Threshold Variable Name\"]]\n cond_out = \"NULL\"\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Needs to be decoded... be careful \n except:\n print(\"Failed: {}\".format(cmds))\n if \"Invalid\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR Invalid epics channel, check with caget again:\\t {}\".format(self.parameterList[\"Threshold Variable Name\"]))\n cond_out = u.defaultKey\n if \"not found\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR caget missing!!\")\n cond_out = \"NULL\"\n self.parameterList[\"Threshold Value\"] = cond_out\n if self.parameterList.get(\"Threshold 2 Variable Name\",u.defaultKey) != \"NULL\":\n cmds = ['caget', '-t', '-w 1', self.parameterList[\"Threshold 2 Variable Name\"]]\n cond_out = \"NULL\"\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Needs to be decoded... be careful \n except:\n print(\"Failed: {}\".format(cmds))\n if \"Invalid\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR Invalid epics channel, check with caget again:\\t {}\".format(self.parameterList[\"Threshold 2 Variable Name\"]))\n cond_out = u.defaultKey\n if \"not found\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR caget missing!!\")\n cond_out = \"NULL\"\n self.parameterList[\"Threshold 2 Value\"] = cond_out\n if self.parameterList.get(\"Case Variable Name\",u.defaultKey) != \"NULL\":\n cmds = ['caget', '-t', '-w 1', self.parameterList[\"Case Variable Name\"]]\n cond_out = \"NULL\"\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Needs to be decoded... be careful \n except:\n print(\"Failed: {}\".format(cmds))\n if \"Invalid\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR Invalid epics channel, check with caget again:\\t {}\".format(self.parameterList[\"Case Variable Name\"]))\n cond_out = \"BAD\"\n if \"not found\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR caget missing!!\")\n cond_out = \"NULL\"\n self.parameterList[\"Case Value\"] = cond_out\n #else: # User didn't have \"Value\" in their parameter list, add it and make it init to NULL\n # self.parameterList[\"Case Variable Name\"] = \"NULL\"\n # self.parameterList[\"Case Value\"] = \"NULL\"\n if self.parameterList.get(\"Double Case Variable Name\",u.defaultKey) != \"NULL\":\n cmds = ['caget', '-t', '-w 1', self.parameterList[\"Double Case Variable Name\"]]\n cond_out = \"NULL\"\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Needs to be decoded... be careful \n except:\n print(\"Failed: {}\".format(cmds))\n if \"Invalid\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR Invalid epics channel, check with caget again:\\t {}\".format(self.parameterList[\"Double Case Variable Name\"]))\n cond_out = \"BAD\"\n if \"not found\" in str(cond_out): # Then the epics variable was invalid\n print(\"ERROR caget missing!!\")\n cond_out = \"NULL\"\n self.parameterList[\"Double Case Value\"] = cond_out\n #else: # User didn't have \"Value\" in their parameter list, add it and make it init to NULL\n # self.parameterList[\"Double Case Variable Name\"] = \"NULL\"\n # self.parameterList[\"Double Case Value\"] = \"NULL\"\n\n #print(\"Parameter list value for \\\"Value\\\" updated to be {}\".format(self.parameterList[\"Value\"]))\n\n if \"External\" in self.alarmType: # Alarm Type is the parameter (level 4 object) which keeps track of what analysis to do\n # Read the external output text file, parse each line, compare with current alarm object's dictionaries, update object's values, evaluate status, continue\n pass\n\n def get_run_number(self):\n cmds = ['rcnd']\n cond_out = \"NULL\"\n try:\n cond_out = subprocess.Popen(cmds, stdout=subprocess.PIPE).stdout.read().strip().decode('ascii') # Needs to be decoded... be careful \n except:\n print(\"Failed: {}\".format(cmds))\n lines = cond_out.split('\\n')\n runNumber = 0\n for linei in lines:\n if \":\" not in linei:\n continue\n if len(linei.split(':')) < 2:\n continue\n if linei.split(':')[0].replace(' ','') == \"Lastrun\":\n runNumber = linei.split(':')[1].replace(' ','')\n return runNumber\n\n def do_alarm_evaluate(self):\n # Consider making a candidate list of possible key words, but for now stick to hard-coded names... \n #print(\"Updating: parameterList = {}\".format(self.parameterList))\n val = self.parameterList.get(\"Value\",u.defaultKey)\n threshold = self.parameterList.get(\"Threshold Variable Name\",u.defaultKey)\n thresholdValue = self.parameterList.get(\"Threshold Value\",u.defaultKey)\n thresholdLow = self.parameterList.get(\"Threshold Low\",u.defaultKey)\n thresholdHigh = self.parameterList.get(\"Threshold High\",u.defaultKey)\n threshold2 = self.parameterList.get(\"Threshold 2 Variable Name\",u.defaultKey)\n threshold2Value = self.parameterList.get(\"Threshold 2 Value\",u.defaultKey)\n threshold2Low = self.parameterList.get(\"Threshold 2 Low\",u.defaultKey)\n threshold2High = self.parameterList.get(\"Threshold 2 High\",u.defaultKey)\n case = self.parameterList.get(\"Case Variable Name\",u.defaultKey)\n caseValue = self.parameterList.get(\"Case Value\",\"BAD\")\n case2nd = self.parameterList.get(\"Double Case Variable Name\",u.defaultKey)\n case2ndValue = self.parameterList.get(\"Double Case Value\",\"BAD\")\n differenceReference = self.parameterList.get(\"Difference Reference Variable Name\",u.defaultKey)\n differenceReferenceValue = self.parameterList.get(\"Difference Reference Value\",u.defaultKey)\n\n tripLimit = self.parameterList.get(\"Trip Limit\",u.defaultKey)\n if u.is_number(tripLimit):\n tripLimit = int(tripLimit)\n tripCounter = self.parameterList.get(\"Trip Counter\",u.defaultKey)\n if u.is_number(tripCounter):\n tripCounter = int(tripCounter)\n\n lowlowStr = \"Low Low\"\n lowStr = \"Low\"\n highStr = \"High\"\n highhighStr = \"High High\"\n exactlyStr = \"Exactly\"\n comparatorStr = \"Same Value Comparator\"\n comparatorStr2 = \"Same Value Comparator 2\"\n differenceLowStr = \"Difference Low\"\n differenceHighStr = \"Difference High\"\n lowlow = u.defaultKey\n low = u.defaultKey\n high = u.defaultKey\n highhigh = u.defaultKey\n exactly = u.defaultKey\n comparator = u.defaultKey\n comparator2 = u.defaultKey\n differenceLow = u.defaultKey\n differenceHigh = u.defaultKey\n # Done initializing\n\n if case2nd != u.defaultKey and case2ndValue != \"BAD\" and case != u.defaultKey and caseValue != \"BAD\": # Then we have a double case determining which set of limits to use\n lowlowStr = \"Low Low \"+caseValue+\" \"+case2ndValue\n lowStr = \"Low \"+caseValue+\" \"+case2ndValue\n highStr = \"High \"+caseValue+\" \"+case2ndValue\n highhighStr = \"High High \"+caseValue+\" \"+case2ndValue\n exactlyStr = \"Exactly \"+caseValue+\" \"+case2ndValue\n comparatorStr = \"Same Value Comparator\"+caseValue+\" \"+case2ndValue\n comparatorStr2 = \"Same Value Comparator 2 \"+caseValue+\" \"+case2ndValue\n differenceLowStr = \"Difference Low \"+caseValue+\" \"+case2ndValue\n differenceHighStr = \"Difference High \"+caseValue+\" \"+case2ndValue\n lowlow = self.parameterList.get(\"Low Low \"+caseValue+\" \"+case2ndValue,u.defaultKey) # Assume the user knows what the case's return values can be and names their cased limits as such\n low = self.parameterList.get(\"Low \"+caseValue+\" \"+case2ndValue,u.defaultKey) \n high = self.parameterList.get(\"High \"+caseValue+\" \"+case2ndValue,u.defaultKey) \n highhigh = self.parameterList.get(\"High High \"+caseValue+\" \"+case2ndValue,u.defaultKey) \n exactly = self.parameterList.get(\"Exactly \"+caseValue+\" \"+case2ndValue,u.defaultKey) \n comparator = self.parameterList.get(\"Same Value Comparator \"+caseValue+\" \"+case2ndValue,u.defaultKey) \n comparator2 = self.parameterList.get(\"Same Value Comparator 2 \"+caseValue+\" \"+case2ndValue,u.defaultKey) \n differenceLow = self.parameterList.get(\"Difference Low \"+caseValue+\" \"+case2ndValue,u.defaultKey) \n differenceHigh = self.parameterList.get(\"Difference High \"+caseValue+\" \"+case2ndValue,u.defaultKey) \n # Now get the default, non-cased values and catch any general case free values too\n if lowlow == u.defaultKey: \n lowlow = self.parameterList.get(\"Low Low\",u.defaultKey)\n if low == u.defaultKey: \n low = self.parameterList.get(\"Low\",u.defaultKey)\n if high == u.defaultKey: \n high = self.parameterList.get(\"High\",u.defaultKey)\n if highhigh == u.defaultKey: \n highhigh = self.parameterList.get(\"High High\",u.defaultKey)\n if exactly == u.defaultKey: \n exactly = self.parameterList.get(\"Exactly\",u.defaultKey)\n if comparator == u.defaultKey: \n comparator = self.parameterList.get(\"Same Value Comparator\",u.defaultKey)\n if comparator2 == u.defaultKey: \n comparator2 = self.parameterList.get(\"Same Value Comparator 2\",u.defaultKey)\n if differenceLow == u.defaultKey: \n differenceLow = self.parameterList.get(\"Difference Low\",u.defaultKey)\n if differenceHigh == u.defaultKey: \n differenceHigh = self.parameterList.get(\"Difference High\",u.defaultKey)\n # FIXME vastly redundant ELSE condition here... just make them from the top?\n elif case != u.defaultKey and caseValue != \"BAD\": # Then we have a single case determining which set of limits to use\n lowlowStr = \"Low Low \"+caseValue\n lowStr = \"Low \"+caseValue\n highStr = \"High \"+caseValue\n highhighStr = \"High High \"+caseValue\n exactlyStr = \"Exactly \"+caseValue\n comparatorStr = \"Same Value Comparator \"+caseValue\n comparatorStr2 = \"Same Value Comparator 2 \"+caseValue\n differenceLowStr = \"Difference Low \"+caseValue\n differenceHighStr = \"Difference High \"+caseValue\n lowlow = self.parameterList.get(\"Low Low \"+caseValue,u.defaultKey) # Assume the user knows what the case's return values can be and names their cased limits as such\n low = self.parameterList.get(\"Low \"+caseValue,u.defaultKey) \n high = self.parameterList.get(\"High \"+caseValue,u.defaultKey) \n highhigh = self.parameterList.get(\"High High \"+caseValue,u.defaultKey) \n exactly = self.parameterList.get(\"Exactly \"+caseValue,u.defaultKey) \n comparator = self.parameterList.get(\"Same Value Comparator \"+caseValue,u.defaultKey) \n comparator2 = self.parameterList.get(\"Same Value Comparator 2 \"+caseValue,u.defaultKey) \n differenceLow = self.parameterList.get(\"Difference Low \"+caseValue,u.defaultKey) \n differenceHigh = self.parameterList.get(\"Difference High \"+caseValue,u.defaultKey) \n # Now get the default, non-cased values and catch any general case free values too\n if lowlow == u.defaultKey: \n lowlow = self.parameterList.get(\"Low Low\",u.defaultKey)\n if low == u.defaultKey: \n low = self.parameterList.get(\"Low\",u.defaultKey)\n if high == u.defaultKey: \n high = self.parameterList.get(\"High\",u.defaultKey)\n if highhigh == u.defaultKey: \n highhigh = self.parameterList.get(\"High High\",u.defaultKey)\n if exactly == u.defaultKey: \n exactly = self.parameterList.get(\"Exactly\",u.defaultKey)\n if comparator == u.defaultKey: \n comparator = self.parameterList.get(\"Same Value Comparator\",u.defaultKey)\n if comparator2 == u.defaultKey: \n comparator2 = self.parameterList.get(\"Same Value Comparator 2\",u.defaultKey)\n if differenceLow == u.defaultKey: \n differenceLow = self.parameterList.get(\"Difference Low\",u.defaultKey)\n if differenceHigh == u.defaultKey: \n differenceHigh = self.parameterList.get(\"Difference High\",u.defaultKey)\n #print(\"Value = {}, high = {}\".format(val, high))\n #valD = Decimal(val)\n #highD = Decimal(high)\n #if valD > highD:\n # print(\"Value is > high\")\n #if not u.is_number(str(val)): # Then we are not dealing with a number alarm - for now just return false\n if self.parameterList.get(exactlyStr,u.defaultKey) != u.defaultKey: # Then we are not dealing with a number alarm - for now just return false\n #print(\"ERROR: Assume alarms values can only be numbers for now\")\n #if exactly != \"NULL\" and val != exactly:\n # self.parameterList[\"Alarm Status\"] = \"Exactly\"\n #else:\n # self.parameterList[\"Alarm Status\"] = \"OK\"\n pass\n elif self.parameterList.get(comparatorStr,u.defaultKey) != u.defaultKey: # Then we are not dealing with a number alarm - for now just return false\n #print(\"ERROR: Assume alarms values can only be numbers for now\")\n pass\n elif self.parameterList.get(comparatorStr2,u.defaultKey) != u.defaultKey: # Then we are not dealing with a number alarm - for now just return false\n #print(\"ERROR: Assume alarms values can only be numbers for now\")\n pass\n else:\n if u.is_number(str(val)):\n val = Decimal(self.parameterList.get(\"Value\",u.defaultKey))\n if u.is_number(str(thresholdValue)):\n thresholdValue = Decimal(self.parameterList.get(\"Threshold Value\",u.defaultKey))\n if u.is_number(str(thresholdLow)):\n thresholdLow = Decimal(self.parameterList.get(\"Threshold Low\",u.defaultKey))\n if u.is_number(str(thresholdHigh)):\n thresholdHigh = Decimal(self.parameterList.get(\"Threshold High\",u.defaultKey))\n if u.is_number(str(threshold2Value)):\n threshold2Value = Decimal(self.parameterList.get(\"Threshold 2 Value\",u.defaultKey))\n if u.is_number(str(threshold2Low)):\n threshold2Low = Decimal(self.parameterList.get(\"Threshold 2 Low\",u.defaultKey))\n if u.is_number(str(threshold2High)):\n threshold2High = Decimal(self.parameterList.get(\"Threshold 2 High\",u.defaultKey))\n #if u.is_number(str(differenceReferenceValue)) and differenceReferenceValue != u.defaultKey:\n # differenceReferenceValue = Decimal(self.parameterList.get(\"Difference Reference Value\",u.defaultKey))\n if u.is_number(str(lowlow)): # And now check the other ones too\n lowlow = Decimal(self.parameterList.get(lowlowStr,u.defaultKey))\n if u.is_number(str(low)):\n low = Decimal(self.parameterList.get(lowStr,u.defaultKey))\n if u.is_number(str(high)):\n high = Decimal(self.parameterList.get(highStr,u.defaultKey))\n if u.is_number(str(highhigh)):\n highhigh = Decimal(self.parameterList.get(highhighStr,u.defaultKey))\n if u.is_number(str(differenceLow)):\n differenceLow = Decimal(self.parameterList.get(differenceLowStr,u.defaultKey))\n if u.is_number(str(differenceHigh)):\n differenceHigh = Decimal(self.parameterList.get(differenceHighStr,u.defaultKey))\n if val != \"NULL\":\n if low != \"NULL\" and u.is_number(low) and u.is_number(val) and val < low:\n #if low != \"NULL\" and u.is_number(low) and u.is_number(val) and val < \"TEST\":\n #if low != \"NULL\":\n # if u.is_number(low):\n # if u.is_number(val):\n # if val < low:\n self.parameterList[\"Alarm Status\"] = lowStr\n #print(\"Alarm {} Low\".format(val))\n elif lowlow != \"NULL\" and u.is_number(lowlow) and u.is_number(val) and val < lowlow:\n self.parameterList[\"Alarm Status\"] = lowlowStr\n elif high != \"NULL\" and u.is_number(high) and u.is_number(val) and val > high:\n #print(\"Updating status to high\")\n self.parameterList[\"Alarm Status\"] = highStr\n elif highhigh != \"NULL\" and u.is_number(highhigh) and u.is_number(val) and val > highhigh:\n self.parameterList[\"Alarm Status\"] = highhighStr\n #elif differenceLow != \"NULL\" and differenceReferenceValue != \"NULL\" and val != \"NULL\" and u.is_number(differenceLow) and u.is_number(val) and u.is_number(differenceReferenceValue) and ((val - differenceReferenceValue) < differenceLow):\n # self.parameterList[\"Alarm Status\"] = differenceLowStr\n #elif differenceHigh != \"NULL\" and differenceReferenceValue != \"NULL\" and val != \"NULL\" and u.is_number(differenceHigh) and u.is_number(differenceReferenceValue) and u.is_number(val) and ((val - differenceReferenceValue) > differenceHigh):\n # self.parameterList[\"Alarm Status\"] = differenceHighStr\n elif exactly != \"NULL\" and val != exactly:\n self.parameterList[\"Alarm Status\"] = exactlyStr\n elif comparator != \"NULL\" and comparator2 != \"NULL\" and (val == comparator and val == comparator2): # Comparator wants to check if its not exactly\n # FIXME This assumes the comparator is only ever used for Aq feedback\n self.parameterList[\"Alarm Status\"] = \"Value is Static!\"\n else:\n self.parameterList[\"Alarm Status\"] = \"OK\"\n # If the thresholds conditions are NOT met then erase prior alarm status, else let that Alert status propagate forward\n if threshold != u.defaultKey and thresholdValue != u.defaultKey and ((thresholdLow != u.defaultKey and thresholdValue < thresholdLow) or (thresholdHigh != u.defaultKey and thresholdValue > thresholdHigh)):\n self.parameterList[\"Alarm Status\"] = \"OK\"\n #print(\"Alarm {} OK, checked against {} = {}. Is < {} threshold, therefore alarm is OK\".format(val,threshold,thresholdValue,thresholdLow))\n if threshold2 != u.defaultKey and threshold2Value != u.defaultKey and ((threshold2Low != u.defaultKey and threshold2Value < threshold2Low) or (threshold2High != u.defaultKey and threshold2Value > threshold2High)):\n self.parameterList[\"Alarm Status\"] = \"OK\"\n #print(\"Alarm {} OK, checked against {} = {}. Is < {} threshold2, therefore alarm is OK\".format(val,threshold2,threshold2Value,threshold2Low))\n if tripCounter != \"NULL\" and tripLimit != \"NULL\" and tripCounter < tripLimit and self.parameterList.get(\"Alarm Status\",u.defaultKey) != \"OK\":\n #print(\"Not OK: Less than, Trip counter = {}, trip limit = {}\".format(tripCounter, tripLimit))\n # The alarm has not surpassed the limit\n self.parameterList[\"Alarm Status\"] = \"OK\"\n if \"Cooldown\" not in self.parameterList[\"User Notify Status\"]:\n self.parameterList[\"Trip Counter\"] = str(tripCounter + 1)\n elif tripCounter != \"NULL\" and tripLimit != \"NULL\" and tripCounter >= tripLimit and self.parameterList.get(\"Alarm Status\",u.defaultKey) != \"OK\":\n #print(\"Not OK: Greater than, Trip counter = {}, trip limit = {}\".format(tripCounter, tripLimit))\n # The alarm has surpassed the limit\n self.parameterList[\"Trip Counter\"] = str(tripCounter + 1)\n elif tripCounter != \"NULL\" and tripLimit != \"NULL\":\n #print(\"OK: Trip counter = {}, trip limit = {}\".format(tripCounter, tripLimit))\n # We have an OK alarm status and should reset the counter\n self.parameterList[\"Trip Counter\"] = \"0\"\n else:\n val = \"NULL\"\n self.parameterList[\"Alarm Status\"] = \"OK\"\n #print(\"Updated: parameterList = {}\".format(self.parameterList))\n if self.parameterList.get(\"Alarm Status\",u.defaultKey) != \"OK\" and self.parameterList.get(\"Alarm Status\",u.defaultKey) != \"Invalid\" and self.parameterList.get(\"Alarm Status\",u.defaultKey) != \"NULL\": # Update global alarm status unless NULL or invalid\n self.alertSound = self.parameterList.get(\"Alert Sound\",\"7\")\n self.alarmStatus = self.parameterList.get(\"Alarm Status\",u.defaultKey)\n # If the alarm is alarming and we aren't in cooldown then update user status\n if self.parameterList.get(\"Alarm Status\",u.defaultKey) != \"OK\" and self.parameterList.get(\"User Notify Status\",u.defaultKey).split(' ')[0] != \"Cooldown\":\n self.userNotifyStatus = self.parameterList.get(\"Alarm Status\",u.defaultKey)\n self.parameterList[\"User Notify Status\"] = self.parameterList.get(\"Alarm Status\",u.defaultKey)\n self.userSilenceStatus = self.parameterList.get(\"User Silence Status\",u.defaultKey)\n if self.userSilenceStatus != \"Silenced\":\n self.color = u.red_color\n elif self.userSilenceStatus == \"Silenced\":\n # FIXME should be yellow here? Do these color status indicators even matter outside of the GUI tab loops?\n self.color = u.darkgrey_color # Still indicate that it is off, but not red now\n u.recentAlarmButton = self.index\n return \"Not OK\"\n else:\n #print(\"Alarm OK\")\n self.alarmStatus = self.parameterList.get(\"Alarm Status\",u.defaultKey)\n self.userNotifyStatus = self.parameterList.get(\"User Notify Status\",u.defaultKey)\n self.alarmStatus = \"OK\"\n self.color = u.lightgrey_color\n return \"OK\"\n\n","sub_path":"alarm_object.py","file_name":"alarm_object.py","file_ext":"py","file_size_in_byte":57812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"393529944","text":"import logging\nimport os\nfrom typing import Callable, Optional\nfrom urllib.parse import urlparse\n\nfrom kentik_api import KentikAPI\nfrom kentik_api.utils import get_credentials\nfrom kentik_api.utils.auth import load_credential_profile\n\nfrom kentik_synth_client import KentikSynthClient\n\nlog = logging.getLogger(\"apis\")\n\n\ndef _fail(msg: str) -> None:\n raise RuntimeError(msg)\n\n\nclass APIs:\n def __init__(\n self,\n mgmt_profile: str,\n syn_profile: str,\n proxy: Optional[str] = None,\n api_url: Optional[str] = None,\n fail: Callable[[str], None] = _fail,\n ) -> None:\n self.mgmt_profile = mgmt_profile\n self.syn_profile = syn_profile\n self.proxy = proxy\n self.api_url = api_url\n self._fail = fail\n self._mgmt_api = None\n self._syn_api = None\n log.debug(\"API: mgmt profile: %s\", self.mgmt_profile)\n log.debug(\"API: syn profile: %s\", self.syn_profile)\n log.debug(\"API: proxy: %s\", self.proxy)\n\n def _load_profile(self, profile: str) -> dict:\n home = os.environ.get(\"KTAPI_HOME\", os.environ.get(\"HOME\", \".\"))\n cfg_file = os.environ.get(\"KTAPI_CFG_FILE\", os.path.join(home, \".kentik\", profile))\n cfg = load_credential_profile(cfg_file)\n if cfg is None:\n self._fail(f\"Failed to load profile file '{cfg_file}'\")\n return cfg\n\n def _get_url(self, profile: str) -> Optional[str]:\n return os.environ.get(\"KTAPI_URL\", self._load_profile(profile).get(\"url\"))\n\n def _get_proxy(self, profile: str) -> Optional[str]:\n return os.environ.get(\"KTAPI_PROXY\", self._load_profile(profile).get(\"proxy\"))\n\n @property\n def mgmt(self):\n if not self._mgmt_api:\n if not self.mgmt_profile:\n self._fail(\"No authentication profile specified to target account\")\n if self.proxy:\n proxy = self.proxy\n else:\n proxy = self._get_proxy(self.mgmt_profile)\n if not self.api_url:\n url = self._get_url(self.mgmt_profile)\n else:\n url = self.api_url\n # KentikAPI expects URL to include path, e.g. https://api.ou1.kentik.com/api/v5\n if url:\n u = urlparse(url)\n if u.path == \"\":\n url = u._replace(path=\"/api/v5\").geturl()\n else:\n url = KentikAPI.API_URL_US\n log.debug(\"API: mgmt URL: %s\", url)\n log.debug(\"API: mgmt proxy: %s\", proxy)\n self._mgmt_api = KentikAPI(*get_credentials(self.mgmt_profile), api_url=url, proxy=proxy)\n log.debug(\"API: mgmt_api: %s\", self._mgmt_api)\n return self._mgmt_api\n\n @property\n def syn(self):\n if not self._syn_api:\n if not self.syn_profile:\n self._fail(\"No authentication profile specified (---profile option is required)\")\n if self.proxy:\n proxy = self.proxy\n else:\n proxy = self._get_proxy(self.syn_profile)\n if not self.api_url:\n url = self._get_url(self.syn_profile)\n else:\n url = self.api_url\n log.debug(\"API: syn_api URL: %s\", url)\n log.debug(\"API: syn_api proxy: %s\", proxy)\n self._syn_api = KentikSynthClient(get_credentials(self.syn_profile), url=url, proxy=proxy)\n log.debug(\"API: syn_api: %s\", self._syn_api)\n return self._syn_api\n","sub_path":"synth_tools/apis.py","file_name":"apis.py","file_ext":"py","file_size_in_byte":3498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"157419908","text":"\"\"\"\n\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom skgstat import Variogram\n\n\ndef variogram(\n coordinates,\n values,\n effective_range,\n sill,\n nugget=0,\n n_lags=15,\n binning='even',\n maxlag='median',\n model='spherical',\n estimator='cressie',\n s=None,\n plot=True,\n ax=None\n):\n \"\"\"Variogram Function\n\n Calculate a variogram from the given parameters. This function will not\n fit the theoretical function to the experimental function, but use the\n passed arguments.\n\n Parameters\n ----------\n coordinates : numpy.ndarray\n List of n-dimensional coordinates. Refer to scikit-gstat for more\n information of this parameter.\n values : numpy.ndarray\n 1D-array of observaitons. Has to match the length of the first axis\n of coordinates. Refer to scikit-gstat for more information of this\n parameter.\n effective_range : float\n Effective range of the theoretical model function. Refer to\n scikit-gstat for more information of this parameter.\n sill : sill\n Sill of the theoretical model function. Refer to scikit-gstat for\n more information of this parameter.\n nugget : float\n Nugget of the theoretical model function. Defaults to 0 (no nugget\n effect included in the model). Refer to scikit-gstat for more\n information of this parameter.\n n_lags : int\n Number of lag classes to be derived for the variogram. Refer to\n scikit-gstat for more information of this parameter.\n binning : str\n Method used for calculating the lag class edges. Can be either 'even'\n (default) or 'uniform'. 'even' will yield lag classes of same width,\n 'uniform' will assure a uniform distribution across all lag classes.\n Refer to scikit-gstat for more information of this parameter.\n maxlag : float, str, None\n Maximum separating distance, at which a point pair will still be\n included into the variogram. Can be the number itself (float > 1),\n the share of the maximum separating distance observed (0 < maxlag <\n 1), or one of 'mean', 'median' to calculate the mean or median of all\n separating distances as maxlag.\n model : str\n The theoretical variogram model. Can be one of:\n\n * spherical\n\n * exponential\n\n * gaussian\n\n * cubic\n\n * stable\n\n * matern\n\n Refer to scikit-gstat for more information of this parameter.\n estimator : str\n The semi-variance estimator to be used for the experimental\n variogram. Can be one of:\n\n * materon\n\n * cressie\n\n * dowd\n\n * genton\n\n * entropy\n\n Refer to scikit-gstat for more information of this parameter.\n s : float\n In case the model was set to matern, s is the smoothness parameter of\n the model. In case the model was set to stable, s is the shape\n parameter of the model. In all other cases, s will be ignored.\n plot : bool\n If True, the function will return a plot of the Variogram, if False,\n it will return a tuple of (bins, experimental, model).\n ax : None, matplotlib.AxesSubplot\n If None, the function will create a new matplotlib Figure. In case an\n AxesSubplot is passed, that instance will be used for plotting.\n\n Returns\n -------\n plot : matlotlib.Figure\n Will return a matplotlib Figure, if plot was set to True\n data : tuple\n Will return the tuple (bins, experimental, model) if plot was set to\n False.\n \"\"\"\n V = Variogram(coordinates=coordinates, values=values,\n estimator=estimator, model=model, maxlag=maxlag,\n n_lags=n_lags, bin_func=binning, normalize=False)\n\n # get the experimental variogram\n _bins = V.bins\n _exp = V.experimental\n\n # align the model input\n _x = np.linspace(_bins[0], _bins[-1], 100)\n\n # build the coeffs\n cof = [effective_range, sill]\n if V.model.__name__ in ('matern', 'stable'):\n cof.append(s)\n cof.append(nugget)\n\n def modelf(x):\n return V.model(x, *cof)\n\n _y = np.fromiter(map(modelf, _x), dtype=float)\n\n # plot or return\n if not plot:\n return _bins, _exp, _y\n else:\n if ax is None:\n fig, ax = plt.subplots(1, 1, figsize=(8, 6))\n else:\n fig = ax.get_figure()\n\n # plot\n ax.plot(_bins, _exp, 'Dr')\n ax.plot(_x, _y, '-g')\n ax.set_xlabel('Lag')\n ax.set_ylabel('semi-variance [%s]' % estimator)\n ax.set_title('%s variogram' % model)\n\n return fig\n","sub_path":"hydrobox/gstat.py","file_name":"gstat.py","file_ext":"py","file_size_in_byte":4737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"301670246","text":"# coding: utf-8\n\n\"\"\"\n Adobe Experience Manager OSGI config (AEM) API\n\n Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API # noqa: E501\n\n OpenAPI spec version: 1.0.0-pre.0\n Contact: opensource@shinesolutions.com\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass ComAdobeGraniteCsrfImplCSRFFilterProperties(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'filter_methods': 'ConfigNodePropertyArray',\n 'filter_enable_safe_user_agents': 'ConfigNodePropertyBoolean',\n 'filter_safe_user_agents': 'ConfigNodePropertyArray',\n 'filter_excluded_paths': 'ConfigNodePropertyArray'\n }\n\n attribute_map = {\n 'filter_methods': 'filter.methods',\n 'filter_enable_safe_user_agents': 'filter.enable.safe.user.agents',\n 'filter_safe_user_agents': 'filter.safe.user.agents',\n 'filter_excluded_paths': 'filter.excluded.paths'\n }\n\n def __init__(self, filter_methods=None, filter_enable_safe_user_agents=None, filter_safe_user_agents=None, filter_excluded_paths=None): # noqa: E501\n \"\"\"ComAdobeGraniteCsrfImplCSRFFilterProperties - a model defined in OpenAPI\"\"\" # noqa: E501\n\n self._filter_methods = None\n self._filter_enable_safe_user_agents = None\n self._filter_safe_user_agents = None\n self._filter_excluded_paths = None\n self.discriminator = None\n\n if filter_methods is not None:\n self.filter_methods = filter_methods\n if filter_enable_safe_user_agents is not None:\n self.filter_enable_safe_user_agents = filter_enable_safe_user_agents\n if filter_safe_user_agents is not None:\n self.filter_safe_user_agents = filter_safe_user_agents\n if filter_excluded_paths is not None:\n self.filter_excluded_paths = filter_excluded_paths\n\n @property\n def filter_methods(self):\n \"\"\"Gets the filter_methods of this ComAdobeGraniteCsrfImplCSRFFilterProperties. # noqa: E501\n\n\n :return: The filter_methods of this ComAdobeGraniteCsrfImplCSRFFilterProperties. # noqa: E501\n :rtype: ConfigNodePropertyArray\n \"\"\"\n return self._filter_methods\n\n @filter_methods.setter\n def filter_methods(self, filter_methods):\n \"\"\"Sets the filter_methods of this ComAdobeGraniteCsrfImplCSRFFilterProperties.\n\n\n :param filter_methods: The filter_methods of this ComAdobeGraniteCsrfImplCSRFFilterProperties. # noqa: E501\n :type: ConfigNodePropertyArray\n \"\"\"\n\n self._filter_methods = filter_methods\n\n @property\n def filter_enable_safe_user_agents(self):\n \"\"\"Gets the filter_enable_safe_user_agents of this ComAdobeGraniteCsrfImplCSRFFilterProperties. # noqa: E501\n\n\n :return: The filter_enable_safe_user_agents of this ComAdobeGraniteCsrfImplCSRFFilterProperties. # noqa: E501\n :rtype: ConfigNodePropertyBoolean\n \"\"\"\n return self._filter_enable_safe_user_agents\n\n @filter_enable_safe_user_agents.setter\n def filter_enable_safe_user_agents(self, filter_enable_safe_user_agents):\n \"\"\"Sets the filter_enable_safe_user_agents of this ComAdobeGraniteCsrfImplCSRFFilterProperties.\n\n\n :param filter_enable_safe_user_agents: The filter_enable_safe_user_agents of this ComAdobeGraniteCsrfImplCSRFFilterProperties. # noqa: E501\n :type: ConfigNodePropertyBoolean\n \"\"\"\n\n self._filter_enable_safe_user_agents = filter_enable_safe_user_agents\n\n @property\n def filter_safe_user_agents(self):\n \"\"\"Gets the filter_safe_user_agents of this ComAdobeGraniteCsrfImplCSRFFilterProperties. # noqa: E501\n\n\n :return: The filter_safe_user_agents of this ComAdobeGraniteCsrfImplCSRFFilterProperties. # noqa: E501\n :rtype: ConfigNodePropertyArray\n \"\"\"\n return self._filter_safe_user_agents\n\n @filter_safe_user_agents.setter\n def filter_safe_user_agents(self, filter_safe_user_agents):\n \"\"\"Sets the filter_safe_user_agents of this ComAdobeGraniteCsrfImplCSRFFilterProperties.\n\n\n :param filter_safe_user_agents: The filter_safe_user_agents of this ComAdobeGraniteCsrfImplCSRFFilterProperties. # noqa: E501\n :type: ConfigNodePropertyArray\n \"\"\"\n\n self._filter_safe_user_agents = filter_safe_user_agents\n\n @property\n def filter_excluded_paths(self):\n \"\"\"Gets the filter_excluded_paths of this ComAdobeGraniteCsrfImplCSRFFilterProperties. # noqa: E501\n\n\n :return: The filter_excluded_paths of this ComAdobeGraniteCsrfImplCSRFFilterProperties. # noqa: E501\n :rtype: ConfigNodePropertyArray\n \"\"\"\n return self._filter_excluded_paths\n\n @filter_excluded_paths.setter\n def filter_excluded_paths(self, filter_excluded_paths):\n \"\"\"Sets the filter_excluded_paths of this ComAdobeGraniteCsrfImplCSRFFilterProperties.\n\n\n :param filter_excluded_paths: The filter_excluded_paths of this ComAdobeGraniteCsrfImplCSRFFilterProperties. # noqa: E501\n :type: ConfigNodePropertyArray\n \"\"\"\n\n self._filter_excluded_paths = filter_excluded_paths\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ComAdobeGraniteCsrfImplCSRFFilterProperties):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"clients/python/generated/swaggeraemosgi/models/com_adobe_granite_csrf_impl_csrf_filter_properties.py","file_name":"com_adobe_granite_csrf_impl_csrf_filter_properties.py","file_ext":"py","file_size_in_byte":6988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"300032822","text":"import numpy\nimport os\n\n\nclass surface:\n\n d = {\n 'l_units': None,\n 'e_units': None,\n 's_units': None,\n 'f_units': None,\n 'a0_in': None,\n 'x_in': [1.0,0.0,0.0],\n 'y_in': [0.0,1.0,0.0],\n 'z_in': [0.0,0.0,1.0],\n 'c_in': [4,4,4],\n 'rcut': 6.5,\n 'epa': 0.0,\n 'coords_in': [],\n 'a0': None,\n 'x': [1.0,0.0,0.0],\n 'y': [0.0,1.0,0.0],\n 'z': [0.0,0.0,1.0],\n 'c': [1,1,1],\n 'coords': [],\n }\n\n @staticmethod\n def run():\n out_dir = 'out'\n surface.make_dir(out_dir)\n\n\n fh = open(\"input.in\")\n for line in fh:\n line = surface.one_space(line.strip())\n f = line.split(' ')\n if(line != \"\"):\n if(line[0] == '#'):\n if(line[0:8].upper() == \"#L_UNITS\"):\n surface.d['l_units'] = f[1]\n elif(line[0:8].upper() == \"#E_UNITS\"):\n surface.d['e_units'] = f[1]\n elif(line[0:8].upper() == \"#S_UNITS\"):\n surface.d['s_units'] = f[1]\n elif(line[0:8].upper() == \"#F_UNITS\"):\n surface.d['f_units'] = f[1]\n elif(line[0:5].upper() == \"#ALAT\"):\n surface.d['a0_in'] = float(f[1])\n elif(line[0:2].upper() == \"#X\"):\n surface.d['x_in'] = [float(f[1]), float(f[2]), float(f[3])]\n elif(line[0:2].upper() == \"#Y\"):\n surface.d['y_in'] = [float(f[1]), float(f[2]), float(f[3])]\n elif(line[0:2].upper() == \"#Z\"):\n surface.d['z_in'] = [float(f[1]), float(f[2]), float(f[3])]\n elif(line[0:2].upper() == \"#C\"):\n surface.d['c_in'] = [int(f[1]), int(f[2]), int(f[3])]\n elif(line[0:4].upper() == \"#EPA\"):\n surface.d['epa'] = float(f[1])\n else:\n if(len(f)>= 4):\n surface.d['coords_in'].append([f[0],float(f[1]),float(f[2]),float(f[3])])\n fh.close()\n \n # Change coords\n surface.d['coords'] = []\n for cx in range(surface.d['c_in'][0]):\n for cy in range(surface.d['c_in'][1]):\n for cz in range(surface.d['c_in'][2]):\n for c in surface.d['coords_in']:\n surface.d['coords'].append([c[0], (c[1] + cx) / surface.d['c_in'][0], (c[2] + cy) / surface.d['c_in'][1], (c[3] + cz) / surface.d['c_in'][2]])\n\n # Calculate new UV and a0\n C = numpy.zeros((3,3,),)\n C[0,0] = float(surface.d['c_in'][0])\n C[1,1] = float(surface.d['c_in'][1])\n C[2,2] = float(surface.d['c_in'][2])\n UV = numpy.zeros((3,3,),)\n k = ['x_in', 'y_in', 'z_in']\n for i in range(3):\n for j in range(3):\n UV[i,j] = float(surface.d[k[i]][j])\n M = numpy.matmul(C,UV)\n surface.d['a0'] = surface.d['a0_in'] * M[0,0]\n M = M / M[0,0]\n\n\n z_ext = -0.25\n for i in range(12):\n Z = numpy.zeros((3,3,),)\n Z[0,0] = 1.0\n Z[1,1] = 1.0\n Z[2,2] = 1.0 + z_ext\n Z_inv = numpy.linalg.inv(Z)\n UV = numpy.matmul(Z,M)\n\n fname = str(i)\n while(len(fname)<4):\n fname = \"0\" + fname\n\n fh = open(out_dir + '/' + fname + '.dat', 'w')\n fh.write('#L_UNITS ' + str(surface.d['l_units']) + '\\n')\n fh.write('#E_UNITS ' + str(surface.d['e_units']) + '\\n')\n fh.write('#S_UNITS ' + str(surface.d['s_units']) + '\\n')\n fh.write('#F_UNITS ' + str(surface.d['f_units']) + '\\n')\n fh.write('#ALAT ' + str(surface.d['a0']) + '\\n')\n fh.write('#X ' + str(UV[0,0]) + ' ' + str(UV[0,1]) + ' ' + str(UV[0,2]) + '\\n')\n fh.write('#Y ' + str(UV[1,0]) + ' ' + str(UV[1,1]) + ' ' + str(UV[1,2]) + '\\n')\n fh.write('#Z ' + str(UV[2,0]) + ' ' + str(UV[2,1]) + ' ' + str(UV[2,2]) + '\\n')\n fh.write('#C 1 1 1' + '\\n')\n fh.write('#RCUT ' + str(surface.d['rcut']) + '\\n')\n fh.write('#EPA ' + str(surface.d['epa']) + '\\n')\n \n for c in surface.d['coords']:\n c_coords = numpy.asarray(c[1:])\n c_moved = numpy.matmul(Z_inv, c_coords)\n\n\n fh.write(c[0] + ' ')\n fh.write(str(c_moved[0]) + ' ')\n fh.write(str(c_moved[1]) + ' ')\n fh.write(str(c_moved[2]) + ' ')\n fh.write('\\n')\n\n fh.close()\n\n z_ext = z_ext + 0.05\n\n\n\n @staticmethod\n def one_space(line, sep=\" \"):\n out = '' \n indata = 0\n last_char = None\n for char in line:\n if(indata == 1 and char != \"'\" and last_char != \"\\\\\"):\n out = out + char\n elif(indata == 1 and char == \"'\" and last_char != \"\\\\\"):\n out = out + char\n indata = 0\n elif(indata == 2 and char != '\"' and last_char != \"\\\\\"):\n out = out + char\n elif(indata == 2 and char == '\"' and last_char != \"\\\\\"):\n out = out + char\n indata = 0\n elif(indata == 0 and not (char == \" \" and last_char == \" \")):\n out = out + char\n last_char = char\n return out\n\n \n @staticmethod\n def make_dir(dir):\n dirs = dir.split(\"/\")\n try:\n dir = ''\n for i in range(len(dirs)):\n dir = dir + dirs[i]\n if(not os.path.exists(dir) and dir.strip() != ''):\n os.mkdir(dir) \n dir = dir + '/'\n return True\n except:\n return False\n\n\n\n\nsurface.run()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"extras/special_configs/surface_coords/surface.py","file_name":"surface.py","file_ext":"py","file_size_in_byte":5061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"183947728","text":"import numpy as np\nfrom PIL import Image\nfrom scipy import optimize as opt\nfrom scipy.ndimage import interpolation as inter\nimport cv2\nimport time\n\n\nclass Preprocess:\n def __init__(self):\n pass\n\n def deskew_optimized(self, image, image_shape):\n\n # Optmized script. ~98-99% correct. ~15X faster than the original.\n # image = self.image\n bin_img = 1 - \\\n np.array(Image.fromarray(image).convert('1')).astype('uint8')\n bin_img = bin_img[~np.all(bin_img == 0, axis=1)]\n bin_img = bin_img[~np.all(bin_img == 1, axis=1)]\n bin_img = bin_img[:, ~np.all(bin_img == 0, axis=0)]\n bin_img = bin_img[:, ~np.all(bin_img == 1, axis=0)]\n\n def find_score(angle):\n data = inter.rotate(bin_img, angle, reshape=False, order=0)\n hist = np.sum(data, axis=1)\n score = np.sum((hist[1:] - hist[:-1]) ** 2)\n return -1 * score\n\n best_angle = opt.fminbound(lambda x: find_score(x), -5, 5, xtol=0.1)\n\n # print('[OPT] Best rotation angle:', round(best_angle, 2))\n\n # Rotating the image\n # image = cv2.imread(image_name)\n (h, w) = image_shape[:2]\n center = (w // 2, h // 2)\n M = cv2.getRotationMatrix2D(center, best_angle, 1.0)\n rotated = cv2.warpAffine(image, M, (w, h),\n flags=cv2.INTER_CUBIC,\n borderMode=cv2.BORDER_REPLICATE)\n return rotated, round(best_angle, 2)\n\n def denoise(self, deskewed, denoise_strength):\n img = cv2.fastNlMeansDenoising(deskewed, h=denoise_strength)\n\n return (img)\n\n def set_processed_image(self, processed_image):\n self.processed_image = processed_image\n\n def preprocess2(self):\n t = time.time()\n\n # Choose one of the two -\n # out_im, angle = deskew_original('Pages/' + page_image)\n out_im, angle = deskew_optimized(self.image)\n adjusted = adjust_gamma(out_im, gamma=0.2)\n denoised_table = denoise(adjusted, denoise_strength=20)\n blured_table = cv2.bilateralFilter(denoised_table, 9, 30, 30)\n\n # cv2.imwrite(os.getcwd()+'/' + path[:-4] + '_prep_for_text.png', denoised_table)\n # cv2.imwrite('Deskewed_Pages/' + page_image[:-4] + '__deskewed.png', out_im)\n\n time_taken = str(round(time.time() - t, 2)) + 's'\n\n print('\\nDESKEWED FILENAME:', path,\n '\\nANGLE OF ROTATION:', angle,\n '\\nTIME TAKEN:', time_taken,\n '\\nDENOISED IMAGE',\n '\\nADJUSTED GAMMA') # monitor progress.\n\n return blured_table\n\n def preprocess1(path):\n t = time.time()\n\n # Choose one of the two -\n # out_im, angle = deskew_original('Pages/' + page_image)\n out_im, angle = deskew_optimized(path)\n # adjusted = adjust_gamma(image, gamma=0.2)\n denoised_table = denoise(out_im, denoise_strength=20)\n blured_table = cv2.bilateralFilter(denoised_table, 9, 30, 30)\n\n time_taken = str(round(time.time() - t, 2)) + 's'\n\n print('\\nDESKEWED FILENAME:', path,\n '\\nANGLE OF ROTATION:', angle,\n '\\nTIME TAKEN:', time_taken,\n '\\nDENOISED IMAGE',\n '\\nADJUSTED GAMMA') # monitor progress.\n return blured_table\n\n def parse(self, image, table_count, flag='BASE MODULE'):\n if flag == 'BASE MODULE':\n pass\n else:\n if table_count(image) >= 3:\n imagepp = preprocess1(path)\n else:\n imagepp = preprocess2(path)\n\n def pre_process(self, image, image_shape):\n deskewed, _ = self.deskew_optimized(image, image_shape)\n denoised = self.denoise(deskewed, 20)\n blured_table = cv2.bilateralFilter(denoised, 9, 30, 30)\n return deskewed, denoised, blured_table\n","sub_path":"ocr/ITE/scripts/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":3884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"73599731","text":"import argparse\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.nn import Sequential as Seq, Linear as Lin, ReLU\nfrom torch_geometric.data import ClusterData, ClusterLoader\nfrom torch_geometric.nn import MessagePassing\n\nfrom ogb.nodeproppred import PygNodePropPredDataset, Evaluator\n\nfrom logger import Logger\n\n\nclass GINConv(MessagePassing):\n def __init__(self, hidden_channels):\n super(GINConv, self).__init__(aggr='mean')\n\n self.mlp = Seq(Lin(hidden_channels, 2 * hidden_channels), ReLU(),\n Lin(2 * hidden_channels, hidden_channels))\n self.eps = torch.nn.Parameter(torch.Tensor([0.]))\n\n def reset_parameters(self):\n self.mlp[0].reset_parameters()\n self.mlp[2].reset_parameters()\n self.eps.data.fill_(0)\n\n def forward(self, x, edge_index, edge_attr):\n h = (1 + self.eps) * x + self.propagate(edge_index, x=x,\n edge_attr=edge_attr)\n return self.mlp(h)\n\n def message(self, x_j, edge_attr):\n return x_j + edge_attr\n\n\nclass GIN(torch.nn.Module):\n def __init__(self, in_node_channels, in_edge_channels, hidden_channels,\n out_channels, num_layers, dropout):\n super(GIN, self).__init__()\n\n self.node_encoder = Lin(in_node_channels, hidden_channels)\n self.edge_encoder = Lin(in_edge_channels, hidden_channels)\n\n self.convs = torch.nn.ModuleList()\n for _ in range(num_layers):\n self.convs.append(GINConv(hidden_channels))\n\n self.lin = Lin(hidden_channels, out_channels)\n\n self.dropout = dropout\n\n def reset_parameters(self):\n self.node_encoder.reset_parameters()\n self.edge_encoder.reset_parameters()\n for conv in self.convs:\n conv.reset_parameters()\n self.lin.reset_parameters()\n\n def forward(self, x, edge_index, edge_attr):\n x = self.node_encoder(x)\n edge_attr = self.edge_encoder(edge_attr)\n\n for conv in self.convs:\n x = conv(x, edge_index, edge_attr)\n x = F.relu(x)\n x = F.dropout(x, p=self.dropout, training=self.training)\n x = self.lin(x)\n return x\n\n\ndef train(model, loader, optimizer, device):\n model.train()\n criterion = torch.nn.BCEWithLogitsLoss()\n\n total_loss = total_examples = 0\n for data in loader:\n data = data.to(device)\n optimizer.zero_grad()\n out = model(data.x, data.edge_index, data.edge_attr)[data.train_mask]\n loss = criterion(out, data.y[data.train_mask].to(torch.float))\n loss.backward()\n optimizer.step()\n\n num_examples = data.train_mask.sum().item()\n total_loss += loss.item() * num_examples\n total_examples += num_examples\n\n return total_loss / total_examples\n\n\n@torch.no_grad()\ndef test(model, loader, evaluator, device):\n model.eval()\n\n train_masks, valid_masks, test_masks = [], [], []\n y_trues, y_preds = [], []\n\n for data in loader:\n y_trues.append(data.y.clone())\n train_masks.append(data.train_mask.clone())\n valid_masks.append(data.valid_mask.clone())\n test_masks.append(data.test_mask.clone())\n\n data = data.to(device)\n out = model(data.x, data.edge_index, data.edge_attr)\n y_preds.append(out.cpu())\n\n train_mask = torch.cat(train_masks, dim=0)\n valid_mask = torch.cat(valid_masks, dim=0)\n test_mask = torch.cat(test_masks, dim=0)\n y_true = torch.cat(y_trues, dim=0)\n y_pred = torch.cat(y_preds, dim=0)\n\n train_rocauc = evaluator.eval({\n 'y_true': y_true[train_mask],\n 'y_pred': y_pred[train_mask],\n })['rocauc']\n valid_rocauc = evaluator.eval({\n 'y_true': y_true[valid_mask],\n 'y_pred': y_pred[valid_mask],\n })['rocauc']\n test_rocauc = evaluator.eval({\n 'y_true': y_true[test_mask],\n 'y_pred': y_pred[test_mask],\n })['rocauc']\n\n return train_rocauc, valid_rocauc, test_rocauc\n\n\ndef main():\n parser = argparse.ArgumentParser(description='OGBN-Proteins (Cluster-GCN)')\n parser.add_argument('--device', type=int, default=0)\n parser.add_argument('--log_steps', type=int, default=1)\n parser.add_argument('--num_partitions', type=int, default=700)\n parser.add_argument('--num_workers', type=int, default=6)\n parser.add_argument('--num_layers', type=int, default=3)\n parser.add_argument('--hidden_channels', type=int, default=128)\n parser.add_argument('--dropout', type=float, default=0.0)\n parser.add_argument('--batch_size', type=int, default=50)\n parser.add_argument('--lr', type=float, default=0.01)\n parser.add_argument('--epochs', type=int, default=1000)\n parser.add_argument('--eval_steps', type=int, default=5)\n parser.add_argument('--runs', type=int, default=10)\n args = parser.parse_args()\n print(args)\n\n device = f'cuda:{args.device}' if torch.cuda.is_available() else 'cpu'\n device = torch.device(device)\n\n dataset = PygNodePropPredDataset(name='ogbn-proteins')\n splitted_idx = dataset.get_idx_split()\n data = dataset[0]\n\n # Convert split indices to boolean masks and add them to `data`.\n for key, idx in splitted_idx.items():\n mask = torch.zeros(data.num_nodes, dtype=torch.bool)\n mask[idx] = True\n data[f'{key}_mask'] = mask\n\n cluster_data = ClusterData(data, num_parts=args.num_partitions,\n recursive=False, save_dir=dataset.processed_dir)\n\n cluster_data.data.x = torch.ones(cluster_data.data.num_nodes, 1)\n\n loader = ClusterLoader(cluster_data, batch_size=args.batch_size,\n shuffle=True, num_workers=args.num_workers)\n\n model = GIN(cluster_data.data.x.size(-1), data.edge_attr.size(-1),\n args.hidden_channels, 112, args.num_layers,\n args.dropout).to(device)\n\n evaluator = Evaluator(name='ogbn-proteins')\n logger = Logger(args.runs, args)\n\n for run in range(args.runs):\n model.reset_parameters()\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)\n for epoch in range(1, 1 + args.epochs):\n loss = train(model, loader, optimizer, device)\n\n if epoch % args.eval_steps == 0:\n result = test(model, loader, evaluator, device)\n logger.add_result(run, result)\n\n if epoch % args.log_steps == 0:\n train_rocauc, valid_rocauc, test_rocauc = result\n print(f'Run: {run + 1:02d}, '\n f'Epoch: {epoch:02d}, '\n f'Loss: {loss:.4f}, '\n f'Train: {100 * train_rocauc:.2f}%, '\n f'Valid: {100 * valid_rocauc:.2f}% '\n f'Test: {100 * test_rocauc:.2f}%')\n\n logger.print_statistics(run)\n logger.print_statistics()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/nodeproppred/proteins/cluster_gin.py","file_name":"cluster_gin.py","file_ext":"py","file_size_in_byte":6895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"436240831","text":"from flask_app import app\nfrom flask_restful import Resource, reqparse, fields, marshal_with\nfrom flask_app.models import UserModel, RevokedTokenModel, LocationModel\nimport flask_jwt_extended as jwt\n\n\nclass SignUp(Resource):\n\n def post(self):\n \"\"\"\n This function responds to Sign Up request for '/signup' with reqparse parameters\n :param username: String\n :param password: String\n :return: 200 on success with an object {msg:String}\n\n \"\"\"\n\n # Get parameters from the request\n parser = reqparse.RequestParser()\n parser.add_argument('username', help='This field cannot be blank', required=True)\n parser.add_argument('password', help='This field cannot be blank', required=True)\n data = parser.parse_args()\n # Query the database for existing username\n if UserModel.find_by_username(data['username']):\n return {'msg': 'User {} already exists'.format(data['username'])}\n # If not try to create username with a hashed password\n new_user = UserModel(username=data['username'], password=UserModel.generate_hash(data['password']))\n try:\n # Save the username/password\n new_user.save_to_db()\n return {\n 'msg': 'User {} was created'.format(data['username']),\n }\n except:\n return {'msg': 'Something went wrong'}, 500\n\n\nclass Login(Resource):\n\n def post(self):\n\n \"\"\"\n This function responds to Sign Up request for '/login' with reqparse parameters\n :param username: String\n :param password: String\n :return: 200 on success with an object\n {\n msg:String,\n access_token:String, 15 minute session\n refresh_token:String , 30 days session\n }\n\n \"\"\"\n # Get parameters from the request\n parser = reqparse.RequestParser()\n parser.add_argument('username', help='This field cannot be blank', required=True)\n parser.add_argument('password', help='This field cannot be blank', required=True)\n data = parser.parse_args()\n try:\n # Query the database for existing username\n current_user = UserModel.find_by_username(data['username'])\n if not current_user:\n return {'msg': 'User {} doesnt exist'.format(data['username'])}\n # Verify if the hashed password in true and return jwt tokens\n if UserModel.verify_hash(data['password'], current_user.password):\n access_token = jwt.create_access_token(identity=data['username'])\n refresh_token = jwt.create_refresh_token(identity=data['username'])\n return {\n 'msg': 'Logged in as {}'.format(current_user.username),\n 'access_token': access_token,\n 'refresh_token': refresh_token\n }\n else:\n return {'msg': 'Wrong credentials'}\n except:\n return {'msg': 'Something went wrong'}, 500\n\n\nclass LogoutAccess(Resource):\n\n @jwt.jwt_required\n def post(self):\n \"\"\"\n This function responds to Sign Up request for '/login' with reqparse parameters\n :param username: String\n :param password: String\n :return: 200 on success with an object {msg:String, access_token:String, refresh_token:String}\n\n \"\"\"\n jti = jwt.get_raw_jwt()['jti']\n try:\n revoked_token = RevokedTokenModel(jti=jti)\n revoked_token.add()\n return {'msg': 'Access token has been revoked'}\n except:\n return {'msg': 'Something went wrong'}, 500\n\n\nclass LogoutRefresh(Resource):\n @jwt.jwt_refresh_token_required\n def post(self):\n jti = jwt.get_raw_jwt()['jti']\n try:\n revoked_token = RevokedTokenModel(jti=jti)\n revoked_token.add()\n return {'msg': 'Refresh token has been revoked'}\n except:\n return {'msg': 'Something went wrong'}, 500\n\n\nclass TokenRefresh(Resource):\n @jwt.jwt_refresh_token_required\n def post(self):\n current_user = jwt.get_jwt_identity()\n access_token = jwt.create_access_token(identity=current_user)\n return {'access_token': access_token}\n\n\nclass UserLocation(Resource):\n resource_fields = {\n 'location_id': fields.Integer,\n 'lon': fields.String,\n 'lat': fields.String,\n 'comments': fields.String\n }\n\n @staticmethod\n def current_user_id():\n current_user = UserModel.find_by_username(jwt.get_jwt_identity())\n return current_user.user_id\n\n @jwt.jwt_required\n @marshal_with(resource_fields)\n def post(self):\n parser = reqparse.RequestParser()\n parser.add_argument('lon', help='This field cannot be blank', required=True)\n parser.add_argument('lat', help='This field cannot be blank', required=True)\n parser.add_argument('comments', help='This field cannot be blank')\n data = parser.parse_args()\n new_location = LocationModel(user_id=self.current_user_id(), lon=data['lon'], lat=data['lat'],\n comments=data['comments'])\n\n try:\n new_location.save_to_db()\n return new_location\n except:\n return {'msg': 'Something went wrong'}, 500\n\n @jwt.jwt_required\n @marshal_with(resource_fields)\n def get(self):\n try:\n return LocationModel.read_from_db(self.current_user_id())\n except:\n return {'msg': 'Something went wrong'}, 500\n\n @jwt.jwt_required\n @marshal_with(resource_fields)\n def put(self):\n parser = reqparse.RequestParser()\n parser.add_argument('location_id', help='This field cannot be blank', required=True)\n parser.add_argument('lon', help='This field cannot be blank', required=True)\n parser.add_argument('lat', help='This field cannot be blank', required=True)\n parser.add_argument('comments', help='This field cannot be blank')\n data = parser.parse_args()\n update_location = LocationModel.get_by_location_id(data['location_id'])\n\n update_location.lon = data['lon']\n update_location.lat = data['lat']\n update_location.comments = data['comments']\n\n try:\n update_location.update_to_db()\n return update_location\n except:\n return {'msg': 'Something went wrong'}, 500\n\n @jwt.jwt_required\n @marshal_with(resource_fields)\n def delete(self):\n parser = reqparse.RequestParser()\n parser.add_argument('location_id', help='This field cannot be blank', required=True)\n data = parser.parse_args()\n\n delete_location = LocationModel.get_by_location_id(data['location_id'])\n\n try:\n delete_location.delete_from_db()\n return delete_location\n except:\n return {'msg': 'Something went wrong'}, 500\n\n\nclass SecretResource(Resource):\n resource_fields = {\n 'user_id': fields.Integer,\n 'username': fields.String\n }\n\n # @jwt.jwt_required\n # @marshal_with(resource_fields)\n # def get(self):\n # current_user = jwt.get_jwt_identity()\n # return UserModel.find_by_username(current_user)\n\n","sub_path":"flask_app/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":7535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"443899322","text":"\"\"\"postag.py\n\nCustom POS tagger\n\n\"\"\"\n\nimport nltk\nfrom nltk.corpus import brown\nfrom pickle import dump\nfrom pickle import load\n\n\nclass POSTagger(object):\n\n def __init__(self):\n brown_sentences = brown.tagged_sents(categories='news')\n size = int(len(brown_sentences) * 0.9)\n self.train_sentences = brown_sentences[:size]\n\n def open_test_model(self,category):\n open_model = open('t.pkl', 'rb')\n tags = load(open_model)\n open_model.close()\n return tags.evaluate(brown.tagged_sents(categories=category))\n\n def create_trainer(self):\n t0 = nltk.DefaultTagger('NN')\n t1 = nltk.UnigramTagger(self.train_sentences, backoff=t0) #\n t2 = nltk.BigramTagger(self.train_sentences, backoff=t1)\n t3 = nltk.TrigramTagger(self.train_sentences, backoff=t2)\n output = open('t.pkl', 'wb')\n dump(t3, output, -1)\n output.close()\n\n def begin_model_execute(self, sentence):\n input_model = open('t.pkl', 'rb')\n tagger = load(input_model)\n input_model.close()\n tokens = sentence.split()\n return tagger.tag(tokens)\n\n\n","sub_path":"assigmentFour/TextAnalysis/postag.py","file_name":"postag.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"146716501","text":"import os, pickle\n\nimport stuff10classes\n\ndef program_1():\n print(\"Enter the Production Worker's name\")\n name = input()\n print(\"Enter the Production Worker's number\")\n number = input()\n print(\"Enter the Production Worker's shift\")\n shift = input()\n print(\"Enter the Production Worker's pay rate\")\n pay = input()\n worker = stuff10classes.ProductionWorker(name, number, shift, pay)\n\n print(\"Name:\", worker.get_name())\n print(\"Number:\", worker.get_number())\n print(\"Shift:\", worker.get_shift())\n print(\"Pay:\", worker.get_pay())\n\ndef program_2():\n print(\"Enter the Shift Supervisor's name\")\n name = input()\n print(\"Enter the Shift Supervisor's number\")\n number = input()\n print(\"Enter the Shift Supervisor's salary\")\n salary = input()\n print(\"Enter the Shift Supervisor's bonus\")\n bonus = input()\n supervisor = stuff10classes.ShiftSupervisor(name, number, salary, bonus)\n\n print(\"Name:\", supervisor.get_name())\n print(\"Number:\", supervisor.get_number())\n print(\"Salary:\", supervisor.get_salary())\n print(\"Bonus:\", supervisor.get_bonus())\n\ndef program_3():\n\n def main():\n # call the load customers to get our database\n customers = load_customers()\n # welcome message\n print(\"Welcome to the customer database.\")\n print(\"What would you like to do?\")\n # while loop menu\n while True:\n print(\"\\n[L]ook up a customer by name or number\")\n print(\"[A]dd a customer entry\")\n print(\"[E]dit a customer entry\")\n print(\"[D]elete a customer entry\")\n print(\"[V]iew entire mailing list\")\n print(\"[Q]uit\")\n # get the input and call the corresponding functions\n command = input().upper()\n if command == 'L':\n look_up(customers)\n elif command == 'A':\n customers = add(customers)\n elif command == 'E':\n customers = edit(customers)\n elif command == 'D':\n customers = delete(customers)\n elif command == 'V':\n view(customers)\n elif command == 'Q':\n # save data before quitting\n save_data(customers)\n quit()\n else:\n # invalid entry, loop again\n print(\"Invalid entry, try again\")\n \n def load_customers():\n # function to load the customers dictionary from customers.dat using pickle\n # returns an empty dictionary if the file doesn't exist\n file_path = 'customers.dat'\n if os.path.exists(file_path):\n with open(file_path, 'rb') as file:\n return pickle.load(file)\n else:\n return {}\n \n def save_data(customers):\n # function to save the dictionary of customers to customers.dat using pickle\n with open('customers.dat', 'wb') as file:\n pickle.dump(customers, file)\n\n def look_up(customers):\n # function to allow user to lookup customer info using name or number\n # using name returns all matching customers\n # using number returns only the matching number\n command = 0\n while command == 0:\n print(\"1 to look up by name, 2 by number, 3 to quit\")\n try:\n command = int(input())\n if command == 1:\n print(\"Enter the name to look up\")\n # get name input, then initialize list to store matches\n name = input()\n found = []\n # loop through the values in the customers dictionary looking for matching names and add them to the list\n for cust in customers.values():\n if cust.get_name() == name:\n found.append(cust)\n # print any matching customers if found\n if len(found) > 0:\n print(found)\n else:\n # else print nothing found\n print(\"No one found with name\", name)\n elif command == 2:\n print(\"Enter the number to look up\")\n # get number input\n number = input()\n # check if the number is in the customers dictionary\n # then either print the matching entry or nothing found\n if number in customers:\n print(customers[number])\n else:\n print(\"No one found with number\", number)\n # return on quit\n elif command == 3:\n return\n else:\n # invalid entry, loop again\n print(\"Invalid entry, try again.\")\n command = 0\n except ValueError:\n # invalid entry, loop again\n print(\"Invalid entry, try again.\")\n\n def add(customers):\n # function to add a customer entry\n print(\"Enter the customer number\")\n cust_num = input()\n # make sure the customer number isn't already in use\n if cust_num in customers:\n print(\"Number already in use, please try again.\")\n customers = add(customers)\n return customers\n else:\n # get all the inputs\n print(\"Enter the customer's name\")\n name = input()\n print(\"Enter the customer's street address\")\n street_address = input()\n print(\"Enter the customer's city\")\n city = input()\n print(\"Enter the customer's state\")\n state = input()\n print(\"Enter the customer's zip code\")\n zip_code = input()\n print(\"Enter the customer's phone number\")\n phone = input()\n # input check for mailing list\n print(\"Does the customer want to be on the mailing list? (y/n)\")\n if input().lower() == 'y':\n on_mailing_list = True\n else:\n on_mailing_list = False\n # create an instance of the customer\n cust = stuff10classes.Customer(name, street_address, city, state, zip_code, phone, cust_num, on_mailing_list)\n # display the data and ask if everything looks correct before adding it to the dictionary\n print(cust)\n print(\"Is this accurate? (y/n)\")\n if input().lower() == 'y':\n customers[cust_num] = cust\n print(\"Entry added\")\n else:\n customers = add(customers)\n return customers\n \n def edit(customers):\n # function to edit customer entry\n cust_num = ''\n # while loop for input\n while cust_num == '':\n print(\"Enter the customer number, or q to quit\")\n cust_num = input()\n # break the loop on q\n if cust_num == 'q':\n break\n # if the entry is not in the dictionary, state as such\n if cust_num not in customers:\n print(\"No record found for customer number\", cust_num)\n cust_num = ''\n else:\n # print the info found and then ask for inputs\n # any blank entries result in copying the old information\n print(customers[cust_num])\n print(\"Enter the new name, or leave it blank to keep it the same.\")\n name = input()\n if name == '':\n name = customers[cust_num].get_name()\n print(\"Enter the new street address, or leave it blank to keep it the same.\")\n street_address = input()\n if street_address == '':\n street_address = customers[cust_num].get_street_address()\n print(\"Enter the new city, or leave it blank to keep it the same.\")\n city = input()\n if city == '':\n city = customers[cust_num].get_city()\n print(\"Enter the new state, or leave it blank to keep it the same.\")\n state = input()\n if state == '':\n state = customers[cust_num].get_state()\n print(\"Enter the new zip code, or leave it blank to keep it the same.\")\n zip_code = input()\n if zip_code == '':\n zip_code = customers[cust_num].get_zip_code()\n print(\"Enter the new phone number, or leave it blank to keep it the same.\")\n phone = input()\n if phone == '':\n phone = customers[cust_num].get_phone()\n # input check for mailing list\n print(\"Does the customer want to be on the mailing list? (y/n)\")\n if input().lower() == 'y':\n on_mailing_list = True\n else:\n on_mailing_list = False\n # create an instance of the class\n cust = stuff10classes.Customer(name, street_address, city, state, zip_code, phone, cust_num, on_mailing_list)\n # show the new instance and ask the user to check for accuracy, if good then update the dictionary\n print(cust)\n print(\"Is this accurate? (y/n)\")\n if input().lower() == 'y':\n customers[cust_num] = cust\n print(\"Entry updated\")\n cust_num = ''\n return customers\n \n def delete(customers):\n # function to delete a customer entry\n print(\"Enter a customer number to delete\")\n cust_num = input()\n # check if the entered num is in the dictionary\n if cust_num in customers:\n print(customers[cust_num])\n print(\"Are you sure you want to delete this entry? (y/n)\")\n # check if they are sure they want to delete, if so then delete\n if input() == 'y':\n del customers[cust_num]\n print(\"Entry deleted\")\n else:\n print(\"Entry not found\")\n return customers\n \n def view(customers):\n # function to return the maililng address of all entries that are on the mailing list\n for cust in customers.values():\n if cust.get_on_mailing_list():\n print(cust.get_mailing_address())\n\n main()\n\nprogram_3()","sub_path":"stuff10.py","file_name":"stuff10.py","file_ext":"py","file_size_in_byte":10479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"489108940","text":"\"\"\"Unit tests for landmarks space.\"\"\"\n\nimport geomstats.backend as gs\nimport geomstats.tests\nfrom geomstats.geometry.hypersphere import Hypersphere\nfrom geomstats.geometry.landmarks import Landmarks\n\n\nclass TestLandmarks(geomstats.tests.TestCase):\n\n def setUp(self):\n s2 = Hypersphere(dim=2)\n r3 = s2.embedding_space\n\n initial_point = [0., 0., 1.]\n initial_tangent_vec_a = [1., 0., 0.]\n initial_tangent_vec_b = [0., 1., 0.]\n initial_tangent_vec_c = [-1., 0., 0.]\n\n landmarks_a = s2.metric.geodesic(\n initial_point=initial_point,\n initial_tangent_vec=initial_tangent_vec_a)\n landmarks_b = s2.metric.geodesic(\n initial_point=initial_point,\n initial_tangent_vec=initial_tangent_vec_b)\n landmarks_c = s2.metric.geodesic(\n initial_point=initial_point,\n initial_tangent_vec=initial_tangent_vec_c)\n\n self.n_sampling_points = 10\n sampling_times = gs.linspace(0., 1., self.n_sampling_points)\n landmark_set_a = landmarks_a(sampling_times)\n landmark_set_b = landmarks_b(sampling_times)\n landmark_set_c = landmarks_c(sampling_times)\n\n self.n_landmark_sets = 5\n self.times = gs.linspace(0., 1., self.n_landmark_sets)\n gs.random.seed(1234)\n self.space_landmarks_in_euclidean_3d = Landmarks(\n ambient_manifold=r3, k_landmarks=self.n_sampling_points)\n self.space_landmarks_in_sphere_2d = Landmarks(\n ambient_manifold=s2, k_landmarks=self.n_sampling_points)\n self.l2_metric_s2 = self.space_landmarks_in_sphere_2d.metric\n self.l2_metric_r3 = self.space_landmarks_in_euclidean_3d.metric\n self.landmarks_a = landmark_set_a\n self.landmarks_b = landmark_set_b\n self.landmarks_c = landmark_set_c\n\n def test_belongs(self):\n result = self.space_landmarks_in_sphere_2d.belongs(self.landmarks_a)\n expected = True\n self.assertAllClose(result, expected)\n\n def test_belongs_vectorization(self):\n landmark_sets = gs.array([self.landmarks_a, self.landmarks_b])\n result = self.space_landmarks_in_sphere_2d.belongs(landmark_sets)\n expected = gs.array([True, True])\n self.assertAllClose(result, expected)\n\n def test_l2_metric_log_and_squared_norm_and_dist(self):\n \"\"\"Test that squared norm of logarithm is squared dist.\"\"\"\n tangent_vec = self.l2_metric_s2.log(\n point=self.landmarks_b, base_point=self.landmarks_a)\n log_ab = tangent_vec\n result = self.l2_metric_s2.squared_norm(\n vector=log_ab, base_point=self.landmarks_a)\n expected = self.l2_metric_s2.dist(\n self.landmarks_a, self.landmarks_b) ** 2\n\n self.assertAllClose(result, expected)\n\n def test_l2_metric_log_and_exp(self):\n \"\"\"Test that exp and log are inverse maps.\"\"\"\n tangent_vec = self.l2_metric_s2.log(\n point=self.landmarks_b, base_point=self.landmarks_a)\n result = self.l2_metric_s2.exp(\n tangent_vec=tangent_vec, base_point=self.landmarks_a)\n expected = self.landmarks_b\n\n self.assertAllClose(result, expected)\n\n @geomstats.tests.np_and_tf_only\n def test_l2_metric_inner_product_vectorization(self):\n \"\"\"Test the vectorization inner_product.\"\"\"\n n_samples = self.n_landmark_sets\n landmarks_ab = self.l2_metric_s2.geodesic(\n self.landmarks_a, self.landmarks_b)\n landmarks_bc = self.l2_metric_s2.geodesic(\n self.landmarks_b, self.landmarks_c)\n landmarks_ab = landmarks_ab(self.times)\n landmarks_bc = landmarks_bc(self.times)\n\n tangent_vecs = self.l2_metric_s2.log(\n point=landmarks_bc, base_point=landmarks_ab)\n\n result = self.l2_metric_s2.inner_product(\n tangent_vecs, tangent_vecs, landmarks_ab)\n\n self.assertAllClose(gs.shape(result), (n_samples,))\n\n @geomstats.tests.np_and_tf_only\n def test_l2_metric_dist_vectorization(self):\n \"\"\"Test the vectorization of dist.\"\"\"\n n_samples = self.n_landmark_sets\n landmarks_ab = self.l2_metric_s2.geodesic(\n self.landmarks_a, self.landmarks_b)\n landmarks_bc = self.l2_metric_s2.geodesic(\n self.landmarks_b, self.landmarks_c)\n landmarks_ab = landmarks_ab(self.times)\n landmarks_bc = landmarks_bc(self.times)\n\n result = self.l2_metric_s2.dist(\n landmarks_ab, landmarks_bc)\n self.assertAllClose(gs.shape(result), (n_samples,))\n\n @geomstats.tests.np_and_tf_only\n def test_l2_metric_exp_vectorization(self):\n \"\"\"Test the vectorization of exp.\"\"\"\n landmarks_ab = self.l2_metric_s2.geodesic(\n self.landmarks_a, self.landmarks_b)\n landmarks_bc = self.l2_metric_s2.geodesic(\n self.landmarks_b, self.landmarks_c)\n landmarks_ab = landmarks_ab(self.times)\n landmarks_bc = landmarks_bc(self.times)\n\n tangent_vecs = self.l2_metric_s2.log(\n point=landmarks_bc, base_point=landmarks_ab)\n\n result = self.l2_metric_s2.exp(\n tangent_vec=tangent_vecs, base_point=landmarks_ab)\n self.assertAllClose(gs.shape(result), gs.shape(landmarks_ab))\n\n @geomstats.tests.np_and_tf_only\n def test_l2_metric_log_vectorization(self):\n \"\"\"Test the vectorization of log.\"\"\"\n landmarks_ab = self.l2_metric_s2.geodesic(\n self.landmarks_a, self.landmarks_b)\n landmarks_bc = self.l2_metric_s2.geodesic(\n self.landmarks_b, self.landmarks_c)\n landmarks_ab = landmarks_ab(self.times)\n landmarks_bc = landmarks_bc(self.times)\n\n tangent_vecs = self.l2_metric_s2.log(\n point=landmarks_bc, base_point=landmarks_ab)\n\n result = tangent_vecs\n self.assertAllClose(gs.shape(result), gs.shape(landmarks_ab))\n\n @geomstats.tests.np_and_tf_only\n def test_l2_metric_geodesic(self):\n \"\"\"Test the geodesic method of L2Metric.\"\"\"\n landmarks_ab = self.l2_metric_s2.geodesic(\n self.landmarks_a, self.landmarks_b)\n landmarks_ab = landmarks_ab(self.times)\n\n result = landmarks_ab\n expected = []\n for k in range(self.n_sampling_points):\n geod = self.l2_metric_s2.ambient_metric.geodesic(\n initial_point=self.landmarks_a[k, :],\n end_point=self.landmarks_b[k, :])\n expected.append(geod(self.times))\n expected = gs.stack(expected, axis=1)\n\n self.assertAllClose(result, expected)\n","sub_path":"tests/tests_geomstats/test_landmarks.py","file_name":"test_landmarks.py","file_ext":"py","file_size_in_byte":6568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"356893249","text":"# Copyright (C) 2014-2015 Codethink Limited\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along\n# with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n#\n# =*= License: GPL-2 =*=\n\nimport os\nfrom definitions import Definitions\nimport cache\nimport repos\nimport app\nimport buildsystem\nimport sandbox\nfrom subprocess import check_output\nfrom subprocess import call\n\n\ndef assemble(target):\n '''Assemble dependencies and contents recursively until target exists.'''\n if cache.get_cache(target):\n return\n\n defs = Definitions()\n this = defs.get(target)\n\n with app.timer(this, 'Starting assembly'):\n with sandbox.setup(this):\n for it in this.get('build-depends', []):\n dependency = defs.get(it)\n assemble(dependency)\n sandbox.install(this, dependency)\n\n for it in this.get('contents', []):\n component = defs.get(it)\n if component.get('build-mode') == 'bootstrap':\n continue\n assemble(component)\n sandbox.install(this, component)\n\n if this.get('build-mode') != 'bootstrap':\n sandbox.ldconfig(this)\n else:\n app.log(this, \"No ldconfig because bootstrap mode is engaged\")\n\n build(this)\n\n if this.get('devices'):\n sandbox.create_devices(this)\n cache.cache(this)\n# sandbox.remove(this)\n\n\ndef build(this):\n '''Actually create an artifact and add it to the cache\n\n This is what actually runs ./configure, make, make install (for example)\n By the time we get here, all dependencies for 'this' have been assembled.\n '''\n\n app.log(this, 'Start build')\n defs = Definitions()\n if this.get('repo'):\n repos.checkout(this['name'], this['repo'], this['ref'], this['build'])\n\n get_build_system_commands(defs, this)\n for build_step in buildsystem.build_steps:\n if this.get(build_step):\n app.log(this, 'Running', build_step)\n for command in this.get(build_step, []):\n sandbox.run_sandboxed(this, command)\n\n\ndef get_build_system_commands(defs, this):\n '''Get commands specified in this, plus commmands implied by build_system\n\n If bs is unspecified and all steps are empty, detect bs & use its commands\n If bs is specified, use its commands for empty steps\n\n This logic is rather convoluted, because there are examples of morph files\n where build-system is unspecified. It boils down to:\n if bs is specified, or all steps are empty, fill any empty steps\n '''\n\n build_system = None\n for bs in buildsystem.build_systems:\n if this.get('build-system') == bs.name:\n build_system = bs\n\n if not build_system:\n for build_step in buildsystem.build_steps:\n if this.get(build_step):\n return\n\n files = check_output(['ls', this['build']]).decode(\"utf-8\").splitlines()\n build_system = buildsystem.detect_build_system(files)\n\n for build_step in buildsystem.build_steps:\n if this.get(build_step, None) is None:\n if build_system.commands.get(build_step):\n this[build_step] = build_system.commands.get(build_step)\n","sub_path":"assembly.py","file_name":"assembly.py","file_ext":"py","file_size_in_byte":3808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"623397663","text":"import unittest\nfrom google.appengine.ext import testbed\nimport webapp2\nfrom webapp2_extras import json\nimport main\n\n\nclass BaseTest(unittest.TestCase):\n def setUp(self):\n self.testbed = testbed.Testbed()\n self.testbed.activate()\n self.testbed.init_datastore_v3_stub()\n self.testbed.init_memcache_stub()\n self.testbed.init_channel_stub()\n self.testbed.init_xmpp_stub()\n self.testbed.init_logservice_stub()\n self.testbed.init_modules_stub()\n self.testbed.init_app_identity_stub()\n\n def tearDown(self):\n self.testbed.deactivate()\n\n @staticmethod\n def pinAuth():\n request = webapp2.Request.blank('/authentication/pin')\n response = request.get_response(main.app)\n result = json.decode(response.body)\n data = result['data']\n device = data['device']\n game = data['game']\n pin = data['pin']\n channel_token = data['channel_token']\n return device, game, pin, channel_token\n\n @staticmethod\n def pinAssociate(pin):\n request = webapp2.Request.blank('/authentication/pin/associate', POST={'pin': pin})\n response = request.get_response(main.app)\n result = json.decode(response.body)\n data = result['data']\n device = data['device']\n game = data['game']\n channel_token = data['channel_token']\n return device, game, channel_token\n\n\nclass StaticPageTest(BaseTest):\n \"\"\" Naive sanity check of static web pages\n \"\"\"\n\n def testMainPage(self):\n request = webapp2.Request.blank('/')\n response = request.get_response(main.app)\n\n self.assertEqual(response.status_int, 200)\n # TODO assert body\n\n\n def testControlsPage(self):\n request = webapp2.Request.blank('/controls')\n response = request.get_response(main.app)\n\n self.assertEqual(response.status_int, 200)\n # TODO assert body\n\n\nclass PinAuthenticationTest(BaseTest):\n \"\"\" Basic test of pin authentication\n \"\"\"\n\n def testCreatePin(self):\n request = webapp2.Request.blank('/authentication/pin')\n response = request.get_response(main.app)\n\n self.assertEqual(response.status_int, 200)\n\n result = json.decode(response.body)\n pin = None\n try:\n pin = result['data']['pin']\n except KeyError:\n self.fail(\"Result doesn't contain ['data']['pin']\")\n expected = {\n 'data': {\n 'device': '1D',\n 'game': 1,\n 'pin': pin,\n 'channel_token': ''\n },\n 'actions': {\n 'progress': '/games/1/progress'\n }\n }\n self.assertEqual(expected, result)\n self.assertEqual(len(pin), 5, \"Pin should be 5 characters long\")\n\n\n def testAssociatePin(self):\n device, game, pin, channel_token = BaseTest.pinAuth()\n\n request = webapp2.Request.blank('/authentication/pin/associate', POST={'pin': pin})\n response = request.get_response(main.app)\n\n self.assertEqual(response.status_int, 200)\n\n result = json.decode(response.body)\n expected = {\n 'data': {\n 'device': '1M',\n 'game': 1,\n 'channel_token': ''\n },\n 'actions': {\n 'input': '/games/1/input'\n }\n }\n self.assertEqual(expected, result)\n\n\n def testAssociateInexistentPin(self):\n request = webapp2.Request.blank('/authentication/pin/associate')\n request.method = 'POST'\n response = request.get_response(main.app)\n\n self.assertEqual(response.status_int, 500)\n\n def testAlreadyAssociatedPin(self):\n device_desktop, game, pin, channel_token_desktop = BaseTest.pinAuth()\n device_mobile, game, channel_token_mobile = BaseTest.pinAssociate(pin)\n\n request = webapp2.Request.blank('/authentication/pin/associate', POST={'pin': pin})\n response = request.get_response(main.app)\n\n self.assertEqual(response.status_int, 500)\n\n\nclass GameEndPointsTest(BaseTest):\n def setUp(self):\n super(GameEndPointsTest, self).setUp()\n self.device_desktop, self.game, pin, self.channel_token_desktop = BaseTest.pinAuth()\n self.device_mobile, self.game, self.channel_token_mobile = BaseTest.pinAssociate(pin)\n\n def tearDown(self):\n super(GameEndPointsTest, self).tearDown()\n self.device_desktop = None\n self.game = None\n self.pin = None\n self.channel_token_desktop = None\n\n def testSendInput(self):\n request = webapp2.Request.blank(\n '/games/{game_id}/input&device={device}'.format(game_id=self.game, device=self.device_mobile),\n POST={'test': 'test'})\n response = request.get_response(main.app)\n\n self.assertEqual(response.status_int, 200)","sub_path":"tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":4887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"495304034","text":"from flask import Blueprint, request\nfrom donare.core import db, app\nfrom sqlalchemy import and_\nfrom donare.core.api import limiter\nfrom flask_login import login_required, current_user\nfrom donare.models import Post, User, BloodType, Comment, Like, Notification\nfrom donare.lib.api.helper import api_response\nfrom donare.lib.notifications import notify_like, notify_comment\nimport datetime\n\nposts = Blueprint('donare.blueprints.posts', __name__)\nCONTENT_TYPE_JSON = \"application/json\"\n\n\ndef logged_user(): # pragma: no cover\n if current_user.is_anonymous():\n return abort(401)\n return str(current_user.id)\n\n\n@posts.route('user//post', methods=['POST'])\n@login_required\ndef create_post(user_id):\n message = request.form.get('message', False)\n blood_type = request.form.get('blood_type', False)\n latitude = request.form.get('latitude', False)\n longitude = request.form.get('longitude', False)\n\n if user_id != current_user.id:\n return api_response(True, \"You are not the owner of this account\", 400)\n\n if not message:\n return api_response(True, \"Parameters not supplied\", 400)\n\n if not 1 < len(message) < 160:\n return api_response(True, \"Length not valid\", 400)\n\n if not User.query.get(user_id):\n return api_response(True, \"Invalid user\", 400)\n\n post = Post(user_id=user_id, message=message, post_type_id=2)\n\n if latitude and longitude:\n post.latitude = latitude\n post.longitude = longitude\n\n if blood_type:\n bt_query = BloodType.query.filter(BloodType.name == blood_type).first()\n if not bt_query:\n return api_response(True, \"Wrong blood type\", 400)\n post.blood_type_id = bt_query.id\n post.post_type_id = 1\n\n db.session.add(post)\n db.session.commit()\n\n response = post.to_serializable()\n return api_response(False, \"Created\", 200, response)\n\n\n@posts.route('post/', methods=['PUT'])\n@login_required\ndef update_post(post_id):\n message = request.form.get('message', False)\n blood_type = request.form.get('blood_type', False)\n\n if not message:\n return api_response(True, \"Parameters not supplied\", 400)\n\n if not 1 < len(message) < 160:\n return api_response(True, \"Length not valid\", 400)\n\n post = Post.query.get(post_id)\n\n if not post:\n return api_response(True, \"Invalid post\", 400)\n\n if post.user_id != current_user.id:\n return api_response(True, \"You are not the owner of this post\", 400)\n\n post.message = message\n post.post_type_id = 2\n if blood_type:\n bt_query = BloodType.query.filter(BloodType.name == blood_type).first()\n if not bt_query:\n return api_response(True, \"Wrong blood type\", 400)\n post.blood_type_id = bt_query.id\n post.post_type_id = 1\n\n post.updated_at = datetime.datetime.now()\n db.session.add(post)\n db.session.commit()\n\n response = post.to_serializable()\n return api_response(False, \"Updated\", 200, response)\n\n\n@posts.route('post/', methods=['GET'])\n@limiter.limit(\"10 per second\", key_func=logged_user)\ndef get_post(id):\n post = Post.query.get(id)\n if not post:\n return api_response(True, \"invalid post\", 400)\n\n if post.deleted_at:\n return api_response(True, \"post deleted\", 400)\n\n return api_response(False, \"Success\", 200, post.to_serializable())\n\n\n@posts.route('user//posts', methods=['GET'])\n@login_required\ndef get_posts(user_id):\n\n if not User.query.get(user_id):\n return api_response(True, \"invalid user\", 400)\n\n post_q = Post.query.filter(and_(Post.user_id == user_id,\n Post.deleted_at.is_(None)))\n response = [u.to_serializable() for u in post_q]\n return api_response(False, \"Success\", 200, response)\n\n\n@posts.route('feed', methods=['GET'])\n@login_required\ndef get_feed():\n \"\"\"gets a paginated list of posts\"\"\"\n\n newer_post_id = request.args.get('newer_post_id', 0, type=int)\n older_post_id = request.args.get('older_post_id', 0, type=int)\n posts_per_page = app.config.get('PAGINATION_LIMIT')\n post_q = Post.query.filter(Post.deleted_at.is_(None))\n\n if newer_post_id > 0:\n post_q = post_q.filter(Post.id > newer_post_id)\n elif older_post_id > 0:\n post_q = post_q.filter(Post.id < older_post_id)\n\n post_q = post_q.order_by(Post.created_at.desc()).limit(posts_per_page).all()\n response = [u.to_serializable() for u in post_q]\n return api_response(False, \"Success\", 200, response)\n\n\n@posts.route('post/', methods=['DELETE'])\n@limiter.limit(\"10 per second\", key_func=logged_user)\n@login_required\ndef delete_post(id):\n post = Post.query.get(id)\n if not post:\n return api_response(True, \"invalid post\", 400)\n\n if post.user_id != current_user.id:\n return api_response(True, \"You are not the owner of this post\", 400)\n\n post.deleted_at = datetime.datetime.now()\n db.session.add(post)\n db.session.commit()\n\n return api_response(False, \"post deleted\", 200, response={\"id\": id})\n\n\n@posts.route('post//comment', methods=['POST'])\n@login_required\ndef create_comment(post_id):\n comment_str = request.form.get('comment', False)\n\n if not comment_str:\n return api_response(True, \"Parameters not supplied\", 400)\n\n if not 1 < len(comment_str) < 160:\n return api_response(True, \"Length not valid\", 400)\n\n if not Post.query.get(post_id):\n return api_response(True, \"Invalid post\", 400)\n\n comment = Comment(current_user.id, post_id, comment_str)\n db.session.add(comment)\n db.session.commit()\n\n notify_comment(comment)\n response = comment.to_serializable()\n return api_response(False, \"Created\", 200, response)\n\n\n@posts.route('post//comment/', methods=['PUT'])\n@login_required\ndef update_comment(post_id, comment_id):\n comment_str = request.form.get('comment', False)\n\n if not comment_str:\n return api_response(True, \"Parameters not supplied\", 400)\n\n if not 1 < len(comment_str) < 160:\n return api_response(True, \"Length not valid\", 400)\n\n if not Post.query.get(post_id):\n return api_response(True, \"Invalid post\", 400)\n\n comment = Comment.query.get(comment_id)\n if not comment:\n return api_response(True, \"Invalid comment\", 400)\n\n if comment.user_id != current_user.id:\n return api_response(True, \"You are not the owner of this account\", 400)\n\n comment.text = comment_str\n comment.updated_at = datetime.datetime.now()\n db.session.add(comment)\n db.session.commit()\n\n response = comment.to_serializable()\n return api_response(False, \"Updated\", 200, response)\n\n\n@posts.route('comment/', methods=['DELETE'])\n@limiter.limit(\"10 per second\", key_func=logged_user)\n@login_required\ndef delete_comment(id):\n comment = Comment.query.get(id)\n if not comment:\n return api_response(True, \"invalid comment\", 400)\n\n if comment.user_id != current_user.id:\n return api_response(True, \"You are not the owner of this comment\", 400)\n\n comment.updated_at = datetime.datetime.now()\n comment.deleted_at = datetime.datetime.now()\n db.session.add(comment)\n db.session.commit()\n\n return api_response(False, \"comment deleted\", 200, response={\"id\": id})\n\n\n@posts.route('post//comments', methods=['GET'])\n@login_required\ndef get_comments(post_id):\n \"\"\"gets a paginated list of comments\"\"\"\n\n if not Post.query.get(post_id):\n return api_response(True, \"Invalid post\", 400)\n\n newer_comment_id = request.args.get('newer_comment_id', 0, type=int)\n older_comment_id = request.args.get('older_comment_id', 0, type=int)\n limit = app.config.get('PAGINATION_LIMIT')\n comments_q = Comment.query.filter(and_(Comment.post_id == post_id,\n Comment.deleted_at.is_(None)))\n if newer_comment_id > 0:\n comments_q = comments_q.filter(Comment.id > newer_comment_id)\n elif older_comment_id > 0:\n comments_q = comments_q.filter(Comment.id < older_comment_id)\n\n comments_q = comments_q.order_by(Comment.id.desc()).limit(limit).all()\n response = [u.to_serializable() for u in comments_q]\n return api_response(False, \"Success\", 200, response)\n\n\n@posts.route('post//like', methods=['POST'])\n@login_required\ndef toggle_like(post_id):\n is_liked = request.form.get('is_liked', None, type=int)\n\n if not Post.query.get(post_id):\n return api_response(True, \"Invalid post\", 400)\n\n like_q = Like.query.filter(and_(Like.post_id == post_id,\n Like.user_id == current_user.id))\n like_f = like_q.first()\n\n if not like_f and is_liked is not None and not is_liked:\n return api_response(True, \"already disliked\", 400)\n\n if like_f and is_liked is not None and is_liked:\n return api_response(True, \"already liked\", 400)\n\n response_msg = \"liked\"\n if not like_f: # like does not exist\n like = Like(current_user.id, post_id)\n db.session.add(like)\n db.session.commit()\n notify_like(like)\n else: # like exists\n notif_q = Notification.query.filter(and_(Notification.post_id == post_id,\n Notification.contact_user_id == current_user.id)).first()\n if notif_q:\n db.session.delete(notif_q)\n db.session.delete(like_f)\n db.session.commit()\n response_msg = \"disliked\"\n\n return api_response(False, response_msg, 200)\n\n\n@posts.route('post//likes', methods=['GET'])\n@login_required\ndef get_likes(post_id):\n \"\"\"gets a paginated list of likes\"\"\"\n\n if not Post.query.get(post_id):\n return api_response(True, \"Invalid post\", 400)\n\n likes_q = (Like.query.filter(Like.post_id == post_id)\n .order_by(Like.id.desc()).all())\n\n response = [u.to_serializable() for u in likes_q]\n return api_response(False, \"Success\", 200, response)\n","sub_path":"web/donare/blueprints/api/posts.py","file_name":"posts.py","file_ext":"py","file_size_in_byte":9999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"109579016","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nT = 2\r\ntempo = 6000\r\n\r\nL = 100\r\nN = L*L\r\n\r\nS = np.ones(N, dtype=int)\r\nS = 2*np.random.randint(2, size=N)-1\r\nmag = np.zeros(tempo, dtype=int)\r\n\r\nfor t in np.arange(0,tempo):\r\n\tdel_E = 0\r\n\tfor n in np.arange(0, N):\r\n\t\ti = int(np.random.random_sample()*N)\r\n\t\tx = i%L\r\n\t\ty = (i - i%L)/L\r\n\r\n\t\tdel_E = 2*S[int(i)]*(S[int(x + L * ((y+1)%L))] + S[int(((x+1)%L) + L * y)] )\r\n\r\n\t\tif del_E <= 0 or np.random.random_sample() < np.exp(-del_E/T):\r\n\t\t\tS[i] = -S[i]\r\n\r\n\tmag[t] = np.sum(S)*np.exp(-del_E/T)\r\n\r\ny = mag\r\nx = np.arange(0,tempo)\r\nplt.plot(x,y)\r\nplt.show()\r\n\t\t\r\n","sub_path":"Semana 7/grafico.py","file_name":"grafico.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"181817407","text":"import os\nimport devfx.exceptions as exps\n\nclass path(object):\n \"\"\"----------------------------------------------------------------\n \"\"\"\n @classmethod\n def exists(cls, path):\n exists = os.path.exists(path)\n return exists\n\n \"\"\"----------------------------------------------------------------\n \"\"\"\n @classmethod\n def current(cls):\n current = os.getcwd()\n return current\n\n \"\"\"----------------------------------------------------------------\n \"\"\"\n @classmethod\n def absolute(cls, path):\n return os.path.abspath(path)\n\n @classmethod\n def is_absolute(cls, path):\n return os.path.isabs(path)\n\n \"\"\"----------------------------------------------------------------\n \"\"\"\n @classmethod\n def head(cls, path):\n (head, tail) = os.path.split(path)\n return head\n\n @classmethod\n def tail(cls, path):\n (head, tail) = os.path.split(path)\n return tail\n\n \"\"\"----------------------------------------------------------------\n \"\"\"\n @classmethod\n def is_file(cls, path):\n is_file = os.path.isfile(path)\n return is_file\n\n @classmethod\n def is_directory(cls, path):\n is_directory = os.path.isdir(path)\n return is_directory\n\n \"\"\"----------------------------------------------------------------\n \"\"\"\n @classmethod\n def size(cls, path):\n if(os.path.isdir(path)):\n size = 0\n for (root, directorynames, filenames) in os.walk(path):\n for filename in filenames:\n size += os.path.getsize(os.path.join(root, filename))\n return size\n elif os.path.isfile(path):\n size = os.path.getsize(path)\n return size\n else:\n raise exps.NotSupportedError()\n\n \"\"\"----------------------------------------------------------------\n \"\"\"\n @classmethod\n def join(cls, path, *paths):\n path = os.path.join(path, *paths)\n return path\n\n\n\n\n","sub_path":"solution/devfx/os/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"220374869","text":"# -*- coding: utf-8 -*-\n# numkit.integration test cases\n# Part of GromacsWrapper\n# Copyright (c) Oliver Beckstein \n# Published under the Modified BSD Licence.\n\n\"\"\"\n===================================\n Test cases for numkit.fitting\n====================================\n\n\"\"\"\nimport numkit.fitting\n\nimport numpy as np\nfrom numpy.testing import assert_equal, assert_almost_equal, assert_allclose\n\nimport pytest\n\n@pytest.fixture(scope=\"module\")\ndef linear_data(m=-2.8, t=123.45, sigma=1.5):\n def f(x):\n return m*x + t\n # make random numbers consistent\n np.random.seed(2018)\n X = np.linspace(-20, 20, 100)\n dY = sigma*np.random.standard_normal(size=len(X))\n Y = f(X) + dY\n return X, Y, dY\n\n@pytest.fixture(scope=\"module\")\ndef exp_decay_data(a=2.30785, sigma=1.5):\n def f(x):\n return np.exp(-a*x)\n # make random numbers consistent\n np.random.seed(2018)\n X = np.linspace(-4, 10, 100)\n dY = sigma*np.random.standard_normal(size=len(X))\n Y = f(X) + dY\n return X, Y, dY\n\n\n@pytest.fixture(scope=\"module\")\ndef gaussian_data(mu=-4.2, s=0.455, a=8.0, sigma=0.5):\n def f(x):\n return a/(np.sqrt(2*np.pi*s**2)) * np.exp(-(x-mu)**2/(2*s**2))\n # make random numbers consistent\n np.random.seed(2018)\n X = np.linspace(-10, 2, 100)\n dY = sigma*np.random.standard_normal(size=len(X))\n Y = f(X) + dY\n return X, Y, dY\n\n\n\n@pytest.fixture(scope=\"module\")\ndef linfit_noerror(linear_data):\n X, Y, _ = linear_data\n return numkit.fitting.linfit(X, Y)\n\n@pytest.fixture(scope=\"module\")\ndef linfit_witherror(linear_data):\n X, Y, dY = linear_data\n return numkit.fitting.linfit(X, Y, dy=dY)\n\n@pytest.mark.parametrize(\"quantity,expected\", [\n (\"intercept\", 123.29089673580293),\n (\"slope\", -2.8087043835295797),\n (\"sigma_intercept\", 0.1389869156801219),\n (\"sigma_slope\", 0.011916849634869048),\n (\"parameter_correlation\", 0),\n (\"chi_square\", 189.3101547566785),\n (\"Q\", 1.0)])\ndef test_linfit_noerror(linfit_noerror, quantity, expected):\n assert_almost_equal(linfit_noerror[quantity], expected)\n\n@pytest.mark.parametrize(\"quantity,expected\", [\n (\"intercept\", 123.4425486304815),\n (\"slope\", -2.8047542762556232),\n (\"sigma_intercept\", 0.007963180881154172),\n (\"sigma_slope\", 0.0025757387307418587),\n (\"parameter_correlation\", 0.7171768191864278),\n (\"chi_square\", 96.28302496281943),\n (\"Q\", 0.5301523165173313)])\ndef test_linfit_witherror(linfit_witherror, quantity, expected):\n assert_almost_equal(linfit_witherror[quantity], expected)\n\n\n@pytest.fixture(scope=\"class\")\ndef FitLin(linear_data):\n X, Y, _ = linear_data\n return numkit.fitting.FitLin(X, Y, parameters=(1, 0))\n\nclass TestFitLin(object):\n ref_x = np.linspace(-9.3, 5.7, 5)\n ref_y = np.array([149.4118475, 138.8792061, 128.3465646,\n 117.8139232, 107.2812817])\n\n def test_parameters(self, FitLin):\n assert_almost_equal(FitLin.parameters, [-2.8087044, 123.2908967])\n\n def test_fitting(self, FitLin):\n Y = FitLin.fit(self.ref_x)\n assert_almost_equal(Y, self.ref_y)\n\n\n@pytest.fixture(scope=\"class\")\ndef FitExp(exp_decay_data):\n X, Y, _ = exp_decay_data\n return numkit.fitting.FitExp(X, Y, parameters=(1.0,))\n\nclass TestFitExp(object):\n ref_x = np.linspace(-5, 5, 5)\n ref_y = np.array([1.0267685e+05, 3.2043229e+02, 1.0000000e+00,\n 3.1207841e-03, 9.7392934e-06])\n\n def test_parameters(self, FitExp):\n assert_almost_equal(FitExp.parameters, [2.3078684])\n\n def test_fitting(self, FitExp):\n Y = FitExp.fit(self.ref_x)\n assert_allclose(Y, self.ref_y)\n\ndef test_FitGauss(gaussian_data):\n X, Y, _ = gaussian_data\n fit = numkit.fitting.FitGauss(X, Y, parameters=(-2, 1.0, 5.0))\n assert_almost_equal(fit.parameters, [-4.2093312, 0.4403894, 7.6803708])\n\n","sub_path":"src/numkit/tests/test_fitting.py","file_name":"test_fitting.py","file_ext":"py","file_size_in_byte":3851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"619243190","text":"#!/usr/bin/env python\n### Change the IP address if any changes in NFS server.\n### by Sam 24/06/13\n\nimport time\nimport serial\n\nser = serial.Serial('/dev/ttyUSB0',115200)\nser.write(\"setenv serverip_fixed 192.168.1.1\\r\\n\")\ntime.sleep(1)\nser.write(\"setenv set_ip 'run initphy;sleep 3;setenv autoload no;dhcp\\r\\n\")\ntime.sleep(1)\nser.write(\"setenv serverip ${serverip_fixed}'\\r\\n\")\ntime.sleep(1)\nser.write(\"setenv nfsload 'nfs 0xc0700000 ${serverip}:/home/nfs/case_a3/rootfs/boot/uImage'\\r\\n\")\ntime.sleep(1)\nser.write(\"setenv nfsroot '/home/nfs/case_a3/rootfs'\\r\\n\")\ntime.sleep(1)\n\nser.write(\"setenv set_bootargs_nfs 'setenv bootargs ${bootargs_nfs} nfsroot=${serverip}:${nfsroot} ethaddr=${ethaddr}'\\r\\n\")\ntime.sleep(1)\nser.write(\"run nfsboot\\r\\n\")\ntime.sleep(1)\nser.close()\n\n","sub_path":"nfs_boot.py","file_name":"nfs_boot.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"14147562","text":"def onum(num):\r\n\tprevnum =0\r\n\tfor i in range(num):\r\n\t\tprint(prevnum+i)\r\n\t\tprevnum=i\r\n\r\nprint(onum(10))\r\n\r\ndef evenstr(mystr):\r\n\tcount =0\r\n\r\n\tfor i in mystr:\r\n\t\tif count%2==0:\r\n\t\t\tprint(i)\r\n\t\tcount+=1\r\n\r\nprint(evenstr(\"pavan\"))\r\n\r\ndef removechars(mystr,num):\r\n\r\n\treturn mystr[num::]\r\n\r\nprint(removechars(\"pavan\",2))\r\n\r\nmylist=[1,2,34,55,64,2]\r\nif mylist[0] == mylist[len(mylist)-1]:\r\n\tprint(\"True\")\r\nelse:\r\n\tprint(\"False\")\r\n\r\ndef findname(mystr,name):\r\n\tcount=0\r\n\tfor i in range(len(mystr)):\r\n\t\tif mystr[i:i+4]== name:\r\n\t\t\tcount+=1\r\n\r\n\treturn count\r\n\r\nprint(findname(\"Emma is a writer, Emma speaks english\", \"Emma\"))\r\n\r\ndef patter(rows):\r\n\r\n\tfor i in range(1,rows+1):\r\n\r\n\t\tfor j in range(1,i+1):\r\n\r\n\t\t\tprint(i,end=\" \")\r\n\t\tprint()\r\n\r\npatter(5)\r\n","sub_path":"basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"604145296","text":"from flask import Flask, request, jsonify, abort\nfrom flask_cors import CORS, cross_origin\nimport jaydebeapi\nimport jpype\nimport time\nimport datetime\nimport pytz\n\n# Flask configuration\napp = Flask(__name__)\ncors = CORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\nmethods = ('GET', 'POST')\n\n\n# 获取数据库连接\ndef get_conn():\n if jpype.isJVMStarted() and not jpype.isThreadAttachedToJVM():\n jpype.attachThreadToJVM()\n jpype.java.lang.Thread.currentThread().setContextClassLoader(jpype.java.lang.ClassLoader.getSystemClassLoader())\n conn = jaydebeapi.connect(\"com.sybase.jdbc3.jdbc.SybDriver\",\n \"jdbc:sybase:Tds:127.0.0.1:4100?charset=cp936\",\n [\"Username\", \"Password\"],\n \"/opt/simple_json_flask_omnibus/jconn3d.jar\")\n return conn\n\n\n# 时间戳转换为本地时间\ndef timestamp_to_local(timestamp_int, local_format='%Y-%m-%d %H:%M:%S.%f'):\n # local_format \"%Y-%m-%d %H:%M:%S\"\n local_time = time.localtime(timestamp_int)\n return time.strftime(local_format, local_time)\n\n\n# UTC时间转换为时间戳 2019-08-02T02:34:32.370Z\ndef utc_to_local(utc_time_str, utc_format='%Y-%m-%dT%H:%M:%S.%fZ'):\n # 时区: pytz.country_timezones('cn')\n local_tz = pytz.timezone('Asia/Shanghai')\n # 格式: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior\n local_format = \"%Y-%m-%d %H:%M:%S.%f\"\n utc_dt = datetime.datetime.strptime(utc_time_str, utc_format)\n local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)\n time_str = local_dt.strftime(local_format) # UTC时间转本地时间\n return int(time.mktime(time.strptime(time_str, local_format)))\n\n\n# 本地时间转换为UTC\ndef local_to_utc(local_ts, utc_format='%Y-%m-%dT%H:%M:%S.%fZ'):\n local_tz = pytz.timezone('Asia/Shanghai')\n local_format = \"%Y-%m-%d %H:%M:%S.%f\"\n time_str = time.strftime(local_format, time.localtime(local_ts))\n dt = datetime.datetime.strptime(time_str, local_format)\n local_dt = local_tz.localize(dt, is_dst=None)\n utc_dt = local_dt.astimezone(pytz.utc)\n return utc_dt.strftime(utc_format)\n\n\n@app.route('/', methods=methods)\n@cross_origin()\ndef hello_world():\n # print(request.headers, request.get_json())\n return 'python omnibus grafana datasource'\n\n\n@app.route('/search', methods=methods)\n@cross_origin()\ndef find_metrics():\n # print(request.headers, request.get_json())\n return jsonify(['N_APPNAME:节点一', 'Severity:4'])\n\n\n@app.route('/query', methods=methods)\n@cross_origin(max_age=600)\ndef query_metrics():\n sql_customize = \"select to_int(LastOccurrence)*1000,N_APPNAME,N_NODEIP,N_OBJ_NAME,N_SummaryCN,Severity \" \\\n \"from alerts.status \" \\\n \"where N_CURRENTSTATUS='NEW' \"\\\n \"and Severity in (4,5)\"\n order_by = \" order by Severity asc,LastOccurrence asc\"\n sql_all = \"select to_int(LastOccurrence)*1000,N_APPNAME,N_NODEIP,N_OBJ_NAME,N_SummaryCN,Severity \" \\\n \"from alerts.status \" \\\n \"where N_CURRENTSTATUS='NEW' \" \\\n \"and Severity in (4,5) order by Severity asc,LastOccurrence asc\"\n sql_conditions = []\n # print(request.headers, request.get_json())\n req = request.get_json()\n\n timestamps_from = utc_to_local(req['range']['from'])\n timestamps_to = utc_to_local(req['range']['to'])\n time_condition = ' and LastOccurrence between \\'' + str(timestamps_from) + '\\' and \\'' + str(timestamps_to) + '\\' '\n\n if req['targets'][0].get('target', '') == 'all':\n sql_customize = sql_all\n else:\n for target in req['targets']:\n if \":\" not in target.get('target', ''):\n abort(404, Exception(\"输入格式错误,参考样例: N_APPNAME:节点一, Severity:4\"))\n # req_type = target.get('type', 'table') # Grafana panel 请求类型需为 table,而不是 timeseries\n field, value = target['target'].split(':', 1)\n if field == 'Severity':\n sql_conditions.append(field + '=' + value + ' ')\n else:\n sql_conditions.append(field + '=\\'' + value + '\\'')\n # 拼接SQL语句\n for condition in sql_conditions:\n sql_customize = sql_customize + \" and \" + condition\n # sql_customize = sql_customize + time_condition + order_by # 实际未使用时间查询条件\n sql_customize = sql_customize + order_by \n\n print(sql_customize)\n \n query_results = []\n try:\n conn = get_conn()\n curs = conn.cursor()\n curs.execute(sql_customize)\n query_results = curs.fetchall()\n except Exception as e:\n print(e)\n abort(404, Exception(\"查询失败,请检查输入条件!\"))\n finally:\n curs.close()\n conn.close()\n\n res = [\n {\n \"columns\": [\n {\"text\": \"Time\", \"type\": \"time\"}, # 返回第一列数据必须为Time字段,数据类型为time,实际数据为 timestamp 毫秒数*1000\n {\"text\": \"所属节点\", \"type\": \"string\"},\n {\"text\": \"IP地址\", \"type\": \"string\"},\n {\"text\": \"主机名\", \"type\": \"string\"},\n {\"text\": \"告警内容\", \"type\": \"string\"},\n {\"text\": \"级别\", \"type\": \"number\"}\n ],\n \"rows\": query_results,\n \"type\": \"table\"\n }\n ]\n\n return jsonify(res)\n\n\n@app.route('/annotations', methods=methods)\n@cross_origin(max_age=600)\ndef query_annotations():\n print(request.headers, request.get_json())\n req = request.get_json()\n results = []\n pass\n\n return jsonify(results)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=3003)\n","sub_path":"simple_json_backend.py","file_name":"simple_json_backend.py","file_ext":"py","file_size_in_byte":5771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"641486874","text":"#!/usr/bin/env python3\n\nimport argparse\nimport re\nimport sys\n\nfrom os import access, R_OK\nfrom random import randrange\nfrom sys import argv\n\n\n\"\"\"\nScript designed to pick up a random problem for the undecided developer.\n\"\"\"\n\n\nclass ProblemReader:\n \"\"\"\n ProblemReader reads all the suggested problem assignments from a\n designated file, such as README.md.\n \"\"\"\n START = re.compile(\"\\s*?
    \")\n END = re.compile(\"\\s*?
\")\n LINE = re.compile(\"\\s*?
  • \\s?(.+)\")\n\n def __init__(self, filename):\n if not access(filename, R_OK):\n raise ValueError(\n \"File \\\"%s\\\" does not exist or is not readable\" % filename\n )\n\n self.filename = filename\n\n def __iter__(self):\n return self._iterator()\n\n def _iterator(self):\n \"\"\"\n ProblemReader scans the given file top-to-bottom. When it encounters\n the
      tag, it starts recording the suggested problems, stopping\n when it reaches
    . It handles carefully pathological cases, such\n as before
      , missing
        etc.\n \"\"\"\n inside = False\n\n with open(self.filename, \"r\") as inputfile:\n for l in inputfile:\n if not inside and self.END.match(l):\n raise ValueError(\n \"
      tag comes before
        tag in %s or
          is \"\n \"missing\" % self.filename\n )\n if self.START.match(l):\n inside = True\n continue\n elif self.END.match(l):\n inside = False\n break\n\n if inside:\n match = self.LINE.match(l)\n\n if match:\n yield match.group(1)\n\n # We left the loop never meeting the
        tag\n if inside:\n print(\n \"[%s] WARNING: Ending tag
      never met in %s\" %\n (argv[0], self.filename), file=sys.stderr\n )\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Choose a suggested problem\")\n parser.add_argument(\n \"--src\", action=\"store\", type=str,\n dest=\"source_filename\", metavar=\"\", default=\"README.md\",\n help=\"Source file name where to extract problem tracks from \"\n \"(Markdown format).\"\n )\n args = parser.parse_args()\n\n try:\n p = ProblemReader(args.source_filename)\n except ValueError:\n print(\n \"No file named %s exists or is readable\" %\n args.source_filename, file=sys.stderr\n )\n exit(1)\n problems = tuple(p)\n # randrange() does not include the endpoint\n choice = randrange(0, len(problems))\n\n print(\"And your assigned choice is...\\n\\t\\t\\t*** %s ***\"\n % problems[choice])\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"problem_picker.py","file_name":"problem_picker.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"340873923","text":"#\n# @lc app=leetcode.cn id=32 lang=python3\n#\n# [32] 最长有效括号\n#\n\n# @lc code=start\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n if len(s)<2:\n return 0\n n = len(s)\n dp = [0]*n\n if s[0]=='(' and s[1]==')':\n dp[1] = 2\n for i in range(2,n):\n if s[i]=='(':\n continue\n if s[i]==')' and s[i-1]=='(':\n dp[i] = dp[i-2] + 2\n elif s[i]==')' and s[i-1]==')':\n if i-dp[i-1]-1>=0 and s[i-dp[i-1]-1]=='(':\n if i-dp[i-1]-2<0:\n dp[i] = dp[i-1] + 2\n else:\n dp[i] = dp[i-1] + dp[i-dp[i-1]-2] + 2\n return max(dp)\n# @lc code=end\n\n","sub_path":"Week_06/32.最长有效括号.py","file_name":"32.最长有效括号.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"118924791","text":"import pandas as pd\r\ndf = pd.read_csv(\"student.csv\")\r\n\r\ndf.head()\r\ndf.tail()\r\ndf.columns\r\n\r\ndf['name']\r\ndf[['name', 'regid', 'avg']]\r\ndf['newcol'] = df['phy'] + df['chem'] + df['bio'] + df['math']\r\n\r\n\r\ndf.loc(0)\r\ndf.iloc(0)\r\ndf.iloc[[7,1,2,3]]\r\n\r\ndf.drop('newcol', axis=1, inplace=True)\r\ndf.drop([2,3,4])\r\n\r\ndf['newcol'] = df[['phy', 'chem', 'math', 'bio']].mean(axis=1)\r\ndf['avg'] = df[['phy', 'chem', 'math', 'bio']].mean(axis=1)\r\n\r\ndf['rank'] = df['avg'].rank()\r\ndf['rank'] = df['avg'].rank(method='dense', ascending=False)\r\n\r\nimport matplotlib.pyplot as plt\r\nplt.bar(df['regid'], df['avg'], color='m')\r\nplt.show()\r\n\r\nwith pd.ExcelWriter('report.xlsx') as writer:\r\n df.to_excel(writer)\r\n","sub_path":"day_05/pandas_ex/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"291830965","text":"# required python version: 3.6+\n\nimport os\nimport sys\nimport src.load_data as load_data\nfrom src import plot_data\nfrom src import layer\nfrom src.network import NeuralNetwork_Dumpable as NN\nimport src.network as network\nimport matplotlib.pyplot as plt\nimport numpy\nimport os\n\n# format of data\n# disitstrain.txt contains 3000 lines, each line 785 numbers, comma delimited\n\nfull_path = os.path.realpath(__file__)\npath, filename = os.path.split(full_path)\ndata_filepath = '../data'\ndata_train_filename = 'digitstrain.txt'\ndata_valid_filename = 'digitsvalid.txt'\ndata_test_filename = 'digitstest.txt'\n\ndata_train_filepath = os.path.join(path, data_filepath, data_train_filename)\ndata_valid_filepath = os.path.join(path, data_filepath, data_valid_filename)\ndata_test_filepath = os.path.join(path, data_filepath, data_test_filename)\n\nprint('start initializing...')\nnetwork.init_nn(random_seed=1099)\n\nlearning_rates = [0.02]\nmomentums = [0.9]\n\nregularizers = [0.00001]\nx_train, y_train = load_data.load_from_path(data_train_filepath)\nx_valid, y_valid = load_data.load_from_path(data_valid_filepath)\n\nfor i2 in range(len(regularizers)):\n for i3 in range(len(momentums)):\n for i4 in range(len(learning_rates)):\n layers = [layer.Linear(784, 100),\n layer.BN(100, 100),\n layer.Sigmoid(100, 100),\n layer.Linear(100, 100),\n layer.BN(100, 100),\n layer.Sigmoid(100, 100),\n layer.SoftmaxLayer(100, 10)]\n name = 'network2' + '-' + str(i2) + '-' + str(i3) + '-' + str(i4) + '.dump'\n myNN = NN(layers, learning_rate=learning_rates[i4], regularizer=regularizers[i2], momentum=momentums[i3])\n myNN.train(x_train, y_train, x_valid, y_valid, epoch=300, batch_size=32)\n","sub_path":"script/script_1_5_two_hidden.py","file_name":"script_1_5_two_hidden.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"52036597","text":"import arcade\n\n# constants def\nSCREEN_WIDTH = 800\nSCREEN_HEIGHT = 900\nCELL_SIZE = 30\nSCREEN_COLOR = arcade.color.WHITE\nCELL_LINE_COLOR = arcade.color.GRAY_BLUE\nCOLOR_RED = arcade.color.RED\n\n\ndef draw_cells():\n for i in range(SCREEN_HEIGHT // CELL_SIZE):\n arcade.draw_line(0, i * CELL_SIZE, SCREEN_WIDTH, i * CELL_SIZE, CELL_LINE_COLOR)\n for j in range(SCREEN_WIDTH // CELL_SIZE):\n if j == SCREEN_WIDTH // CELL_SIZE - 4:\n tmp_color = COLOR_RED\n tmp_size = 4\n else:\n tmp_color = CELL_LINE_COLOR\n tmp_size = 1\n arcade.draw_line(j * CELL_SIZE, 0, j * CELL_SIZE, SCREEN_HEIGHT, tmp_color, tmp_size)\n\n\narcade.open_window(SCREEN_WIDTH, SCREEN_HEIGHT, 'Title window')\narcade.set_background_color(SCREEN_COLOR)\n\narcade.start_render()\ndraw_cells()\narcade.draw_circle_outline(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2,\n CELL_SIZE * 2, COLOR_RED, 3)\n\n\n\n\narcade.finish_render()\n\narcade.run()","sub_path":"IT_1.py","file_name":"IT_1.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"605427794","text":"import os\nresults_file = open(\"results.txt\", \"w\")\nip_list = []\nlen(ip_list)\nfor ip in range(1,256):\n ip_list.append(\"192.168.1.\" + str(ip))\nlen(ip_list)\nip_list[0]\nfor ip in ip_list:\n response = os.popen(f\"ping {ip} -n 1\").read()\n if \"Received = 1\" and \"Approximate\" in response:\n results_file.write(f\"UP {ip} Ping Successful\" + \"\\n\")\n else: \n results_file.write(f\"Down {ip} Ping Unsuccessful\" + \"\\n\")\nresults_file.close()\n\n#cat ./results.txt","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"394300763","text":"import pygame,pygame.mixer,sys, random\nfrom pygame.locals import *\npygame.mixer.init()\npygame.init()\n\n# Defining colors with RGB values\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\ngrey = (25, 25, 25)\n\n# Setting Game Window\nScreen_Width = 1280\nScreen_Height = 720\nGame_Window = pygame.display.set_mode([Screen_Width, Screen_Height])\npygame.display.set_caption(\"Pong\")\n\n# Game Variables\nclock = pygame.time.Clock()\nFPS = 60 \nfont = pygame.font.SysFont(\"footlight\", 40) \nball_speedx = 6\nball_speedy = 6 \nplayer_speed = 0\n\n# Rectangles\nGame_over_png = pygame.image.load(\"over.png\").convert_alpha()\nGameover_rect = Game_over_png.get_rect(center = (100, 100))\nBall = pygame.Rect(Screen_Width/2 - 10, Screen_Height/2 - 10, 20, 20)\nPlayer = pygame.Rect(-15, Screen_Height/2 - 40, 20, 80)\nOpponent = pygame.Rect( Screen_Width - 5, Screen_Height/2 - 40, 20, 80)\n\n\ndef main_game():\n speedx = 4\n speedy = 4\n global ball_speedx, ball_speedy, player_speed\n while True:\n Game_Window.fill(grey)\n pygame.draw.ellipse(Game_Window, white, Ball)\n pygame.draw.rect(Game_Window, white, Player)\n pygame.draw.rect(Game_Window, white, Opponent)\n pygame.draw.aaline(Game_Window, white, (Screen_Width/2, 0), (Screen_Width/2, Screen_Height))\n\n # Ball Speed\n Ball.x += ball_speedx\n Ball.y += ball_speedy\n\n # Ball Animation\n if Ball.bottom > Screen_Height or Ball.top < 0:\n ball_speedy *= -1\n\n if Ball.right > Screen_Width or Ball.left < 0:\n Game_Window.blit(Game_over_png, Gameover_rect)\n Gameover_rect.x += speedx\n Gameover_rect.y += speedy\n\n if Gameover_rect.bottom > Screen_Height or Gameover_rect.top < 0:\n speedy *= -1\n if Gameover_rect.right > Screen_Width or Gameover_rect.left < 0:\n speedx *= -1\n \n # Collision\n if Ball.colliderect(Player):\n pygame.mixer.Sound(\"3.wav\").play()\n ball_speedx *= -1\n\n if Ball.colliderect(Opponent):\n pygame.mixer.Sound(\"3.wav\").play()\n ball_speedx *= -1\n\n\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n if event.type == pygame.KEYDOWN:\n if event.key == K_UP:\n player_speed -= 10\n if event.key == K_DOWN:\n player_speed += 10\n\n if event.type == pygame.KEYUP:\n if event.key == K_UP:\n player_speed = 0\n if event.key == K_DOWN:\n player_speed = 0\n\n Player.y += player_speed\n\n # Player\n if Player.top < 0:\n Player.y = 0\n\n if Player.bottom > Screen_Height:\n Player.y = 640\n\n # Opponent\n if Ball.y > Opponent.y:\n Opponent.bottom += 7\n\n if Ball.y < Opponent.y:\n Opponent.top -= 7\n\n if Opponent.top < 0:\n Opponent.y = 0\n\n if Opponent.bottom > Screen_Height:\n Opponent.y = 640\n \n\n pygame.display.update()\n clock.tick(FPS)\n\n\nmain_game()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"629109869","text":"# coding=utf-8\nimport tensorflow as tf\nfrom Project.models import model_base as base\n\n\nclass Model02(base.Model):\n def __init__(self, image_store, dataset_name, epoc_count=2000, init_w=tf.ones):\n base.Model.__init__(\n self,\n image_store=image_store,\n model_name='model2_' + dataset_name,\n epoc_count=epoc_count,\n init_w=init_w)\n\n def build_y(self, x):\n input_dims = \\\n [\n self.img_rows() * self.img_cols() * self.img_depth(),\n 200,\n 100,\n 50,\n 25\n ]\n output_dims = \\\n [\n 200,\n 100,\n 50,\n 25,\n self.image_store.img_classifications\n ]\n weight_init = \\\n [\n self.create_two__dddd_guassian_distribution,\n self.init_w,\n self.init_w,\n self.init_w,\n self.init_w\n ]\n\n with tf.name_scope(\"hidden\"):\n for i in range(len(input_dims)):\n x = self.create_cnn_layer(\n layer_name=\"layer-{0}\".format(i),\n input_tensor=x,\n input_dim=input_dims[i],\n output_dim=output_dims[i],\n weight_initial_distribution_fn=weight_init[i])\n\n return x\n","sub_path":"Studies/UP/MIT/COS801/PyCharm/Project/models/model_02.py","file_name":"model_02.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"445641564","text":"file1 = open(\"basic1.txt\", \"w\")\n\nfile1.write(\"Hello Python!\")\n\nfile1.close()\n\nwith open(\"basic2.txt\", \"w\") as file2:\n file2.write(\"Hello Python!\")\n\nwith open(\"basic2.txt\", \"r\") as file:\n contents = file.read()\nprint(contents)\n\nimport random\n\nhanguls = list(\"가나다라마바사아자차카타파하\")\n\nwith open(\"info.txt\", \"w\") as file:\n for i in range(1000):\n name = random.choice(hanguls) + random.choice(hanguls)\n weight = random.randrange(40, 100)\n height = random.randrange(140, 200)\n\n file.write(\"{}, {}, {}\\n\".format(name, weight, height))\n\nwith open(\"info.txt\", \"r\") as file:\n for line in file:\n\n (name, weight, height) = line.strip().split(\", \")\n\n if (not name) or (not weight) or (not height):\n continue\n\n bmi = int(weight) / ((int(height) / 100) ** 2)\n bmi = round(bmi, 2)\n result = \"\"\n if 25 <= bmi:\n result = \"Overweight\"\n elif 18.5 <= bmi:\n result = \"Average\"\n else:\n result = \"Underweight\"\n\n print('\\n'.join([\n \"Name: {}\",\n \"Weight: {}\",\n \"Height: {}\",\n \"BMI: {}\",\n \"Result: {}\"\n ]).format(name, weight, height, bmi, result))\n print()\n\n\n","sub_path":"file_read_write.py","file_name":"file_read_write.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"533657526","text":"\"\"\"Bla.\"\"\"\n\nfrom rest_framework import serializers\nimport kappagate\nfrom ..serializers import FileSerializer\nfrom ..base import AsyncWorker, StartJobView\nfrom ..tools import (\n matplotlib_figure_to_svg_base64_data,\n records_from_data_files,\n)\nimport tatapov\n\n\nclass serializer_class(serializers.Serializer):\n \"\"\"Serializer.\"\"\"\n\n overhangs = serializers.CharField(allow_blank=True)\n construct = FileSerializer(allow_null=True)\n temperature = serializers.CharField()\n incubation = serializers.CharField()\n\n\nclass worker_class(AsyncWorker):\n def work(self):\n data = self.data\n overhangs = [\n s.strip().upper()\n for s in data.overhangs.split(\",\")\n if len(s.strip())\n ]\n if overhangs == []:\n record = records_from_data_files([data.construct])[0].upper()\n slots = kappagate.construct_record_to_slots(record, backbone_annotations=(\"\",))\n overhangs = [o for s in slots for o in s if set(o) <= set(\"ATGC\")]\n\n temperature, incubation = data.temperature, data.incubation\n data = tatapov.annealing_data[temperature][incubation]\n subset = tatapov.data_subset(data, overhangs, add_reverse=True)\n ax, _ = tatapov.plot_data(subset, figwidth=2 + 0.5 * len(overhangs))\n ax.figure.tight_layout()\n fig_data = matplotlib_figure_to_svg_base64_data(\n ax.figure, bbox_inches=\"tight\"\n )\n return {\"figure_data\": fig_data, \"success\": True}\n\n\nclass ViewOverhangsCrosstalkView(StartJobView):\n serializer_class = serializer_class\n worker_class = worker_class\n","sub_path":"backend/app/views/view_overhangs_crosstalk/ViewOverhangsCrosstalk.py","file_name":"ViewOverhangsCrosstalk.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"607969381","text":"from django.urls import path\n\nfrom .views import (\n ExchangesAPIView, HomeAPIView, MiningAPIView, TeamAPIView,\n TranslationsView, WalletsAPIView, PostDetailView, PostListView,\n RecentPosts, TagsDetailView, TagsListView, FinancialReportAPIView,\n WalletsColdStackingAPIView, AdvisorTeamAPIView, PartnerAPIView\n)\n\nurlpatterns = [\n path('team/', TeamAPIView.as_view()),\n path('mining/', MiningAPIView.as_view()),\n path('wallets/', WalletsAPIView.as_view()),\n path('wallets-cold-stacking/', WalletsColdStackingAPIView.as_view()),\n path('exchanges/', ExchangesAPIView.as_view()),\n path('home/', HomeAPIView.as_view()),\n path('translations//', TranslationsView.as_view()),\n path('tags/', TagsListView.as_view()),\n path('tags//', TagsDetailView.as_view()),\n path('posts/recent/', RecentPosts.as_view()),\n path('posts//', PostDetailView.as_view()),\n path('posts/', PostListView.as_view()),\n path('financial/', FinancialReportAPIView.as_view()),\n path('advisor-team/', AdvisorTeamAPIView.as_view()),\n path('partners/', PartnerAPIView.as_view())\n]\n","sub_path":"back/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"73224520","text":"import random, time, itertools, thread\nfrom collections import defaultdict\nfrom machine import Machine, VirtualMachine\nfrom datacenter import DataCenter\nfrom test import *\n\nclass PairwiseServer(Server):\n # Place all of our users' VMs around the network greedily\n def start(self):\n self.vms = [VirtualMachine(self.user, i) for i in range(self.n)]\n self.B = sparse_B(self.vms, self.max_data, 5)\n\n for vm in self.vms:\n vm.activate(self.B)\n vm.on_transfer_complete = self.on_complete # set callback\n \n # sort the VMs by total data to transfer\n sorted_vms = sorted(self.vms, key=lambda v: -sum(v.transfers.values()))\n\n # try all machines in order\n m = 0\n for v in sorted_vms:\n # try to place in the first available spot\n while not self.dc.place(v, m):\n m = (m + 1) % self.dc.NUM_MACHINES \n\n self.dc.draw_status()\n self.finished = False\n\n # keep updating until everything's finished\n def loop(self):\n self.dc.user_time(self.user)\n\n # We are finished when all of our users' VMs are done\n self.finished = True\n for vm in self.vms:\n if vm.ip in dc.VMs:\n self.finished = False\n\n if self.finished or not self.vms:\n return\n\n # choose a random pair\n vm1 = random.choice(self.vms)\n choices = [v for v in vm1.transfers if v in self.vms]\n if choices:\n vm2 = random.choice(choices)\n else:\n return\n\n # find machine\n self.dc.pause()\n machines = [m for m in range(DataCenter.NUM_MACHINES) \n if self.dc.machine_occupancy(m) >= 2]\n self.dc.unpause()\n\n m = random.choice(machines)\n\n # remove from old machines\n if vm1.ip in self.dc.VMs:\n self.dc.remove(vm1.ip)\n if vm2.ip in self.dc.VMs:\n self.dc.remove(vm2.ip)\n\n # place\n self.dc.place(vm1, m)\n self.dc.place(vm2, m)\n\n\nif __name__ == '__main__':\n # first, place random users around the network with very large connections\n dc = DataCenter()\n fill_datacenter(dc, 20, 10, 10**7)\n dc.draw_status()\n time.sleep(1) # Wait one second\n\n # initialize everything\n servers = [PairwiseServer(i, 20, dc=dc, max_data=100000) for i in range(10)]\n\n dc.pause()\n for server in servers:\n server.start()\n dc.unpause()\n\n # loop through and update every server\n while len([s for s in servers if not s.finished]):\n dc.draw_status()\n for s in servers:\n if not s.finished:\n s.loop()\n time.sleep(1)\n","sub_path":"pairs_test.py","file_name":"pairs_test.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"610535022","text":"from collections import OrderedDict\n\nfrom expander import ExpanderSerializerMixin\nfrom rest_framework import serializers\nfrom rest_framework_gis.serializers import GeoFeatureModelSerializer\n\nfrom hikster.helpers import mixins, functions\nfrom .models import (\n Trail,\n TrailImage,\n Activity,\n TrailActivity,\n TrailSection,\n Event,\n EventTrailSection,\n)\nfrom hikster.location.serializers import LocationSerializer\nfrom hikster.utils.serializers import ImageSerializerBase\n\n\nclass ActivitySerializer(serializers.ModelSerializer):\n class Meta:\n model = Activity\n fields = (\"id\", \"name\")\n\n\nclass TrailActivitySerializer(serializers.ModelSerializer):\n class Meta:\n model = TrailActivity\n fields = [\"activity\", \"difficulty\", \"duration\"]\n\n\nclass TrailSectionSerializer(\n ExpanderSerializerMixin,\n mixins.IncludeFieldsMixin,\n mixins.ExcludeFieldsMixin,\n serializers.ModelSerializer,\n):\n class Meta:\n model = TrailSection\n exclude = (\"objectid\",)\n\n\nclass IntegerListField(serializers.ListField):\n child = serializers.CharField()\n\n\nclass TrailImageSerializer(ImageSerializerBase):\n class Meta:\n model = TrailImage\n exclude = [\"id\", \"trail\"]\n\n\nclass TrailSerializer(\n ExpanderSerializerMixin,\n mixins.IncludeFieldsMixin,\n mixins.ExcludeFieldsMixin,\n serializers.ModelSerializer,\n):\n id = serializers.IntegerField(source=\"trail_id\", required=False, read_only=True)\n object_type = serializers.ReadOnlyField()\n url = serializers.HyperlinkedIdentityField(view_name=\"trail-detail\", read_only=True)\n location_name = serializers.CharField(read_only=True, source=\"location.name\")\n activities = TrailActivitySerializer(many=True)\n banner = serializers.SerializerMethodField(read_only=True)\n difficulty = serializers.CharField(read_only=True)\n duration = serializers.CharField(read_only=True)\n\n class Meta:\n model = Trail\n exclude = [\"trail_sections\"]\n expandable_fields = {\n \"images\": (TrailImageSerializer, (), {\"many\": True}),\n \"location\": LocationSerializer,\n }\n\n def get_banner(self, obj):\n if obj.banner and obj.banner.image:\n return self.context[\"request\"].build_absolute_uri(obj.banner.image.url)\n return \"\"\n\n def validate(self, attrs):\n if not attrs[\"name\"] or not attrs[\"description\"]:\n raise serializers.ValidationError(\n \"Veuillez entrer un nom ou une description pour votre sentier.\"\n )\n return attrs\n\n def create(self, validated_data):\n images = validated_data.pop(\"images\", None)\n region = validated_data.pop(\"region\", None)\n location = validated_data.pop(\"location\", None)\n activities = validated_data.pop(\"activities\", None)\n\n # We save the new location as usual\n TrailClass = self.Meta.model\n trail = TrailClass(**validated_data)\n\n if location and location is not None:\n trail.location = location\n\n if region and region is not None:\n trail.region = region\n\n trail.save()\n\n if images:\n trail.images = functions.save_nested(images, TrailImageSerializer)\n\n if activities:\n for activity in activities:\n try:\n TrailActivity.objects.get(trail=trail, activity=activity)\n except TrailActivity.DoesNotExist:\n TrailActivity.objects.create(trail=trail, activity=activity)\n\n user = self.context[\"request\"].user\n trail.owner.add(user.trailadmin)\n\n return trail\n\n def update(self, trail: Trail, validated_data: OrderedDict):\n images = validated_data.pop(\"images\", None)\n location = validated_data.pop(\"location\", None)\n region = validated_data.pop(\"region\", None)\n activities = validated_data.pop(\"activities\", None)\n\n trail_id = trail.trail_id\n\n for key, value in validated_data.items():\n setattr(trail, key, value)\n\n # check whether the trail already exists in Event model as an event or not\n # if it does, delete it and trigger will create a new one\n if Event.objects.filter(event_id=trail_id).exists():\n EventTrailSection.objects.filter(evnt=trail.trail_id).delete()\n\n # Save foreign key related fields\n # Different from normal nested relations: we just have to link it to a currently existing model\n if location and location is not None:\n trail.location = location\n\n if region and region is not None and region.type == 10:\n trail.region = region\n\n trail.save()\n\n if activities:\n trail.activities.delete()\n for activity in activities:\n try:\n TrailActivity.objects.get(trail=trail, activity=activity)\n except TrailActivity.DoesNotExist:\n TrailActivity.objects.create(trail=trail, activity=activity)\n\n # Save nested representations\n if images:\n if not trail.images.all().exists():\n trail.images = functions.save_nested(images, TrailImageSerializer)\n else:\n existing_img = set(trail.images.values_list(\"id\", flat=True))\n img_to_update = set([image[\"id\"] for image in images if \"id\" in image])\n\n # If the ids are in the the remainder of the diff between the existing img and the img to update\n # it means we've deleted it in the ui\n trail.images.filter(id__in=existing_img - img_to_update).delete()\n\n # We save the new images as usual, which equals to adding it to the existing ones after clearing the\n for image in images:\n img = TrailImage(**image)\n img.save()\n trail.images.add(img)\n else:\n trail.images.all().delete()\n\n return trail\n\n\nclass Trail3DSerializer(GeoFeatureModelSerializer):\n class Meta:\n model = Trail\n geo_field = \"shape\"\n fields = (\"trail_id\", \"shape\")\n\n\n#################################################################\n# Add Event and Event TrailSection #\n#################################################################\n\n\nclass EventSerializer(serializers.ModelSerializer):\n class Meta:\n model = Event\n fields = \"__all__\"\n\n\nclass EventTrailSectionSerializer(serializers.ModelSerializer):\n def __init__(self, *args, **kwargs):\n many = kwargs.pop(\"many\", True)\n super(EventTrailSectionSerializer, self).__init__(many=many, *args, **kwargs)\n\n class Meta:\n model = EventTrailSection\n fields = \"__all__\"\n","sub_path":"hike/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":6783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"622076073","text":"import cv2 as cv\nimport numpy as np\nfrom scipy.spatial.distance import cdist\nimport math\nimport os\nimport shutil\nimport time\nfrom libs.trackers.iou_tracker import IOUTracker\nfrom libs.loggers.loggers import Logger\nfrom tools.environment_score import mx_environment_scoring_consider_crowd\nfrom tools.objects_post_process import extract_violating_objects\nfrom libs.utils import visualization_utils\nfrom libs.utils.camera_calibration import get_camera_calibration_path\nfrom libs.uploaders.s3_uploader import S3Uploader\nimport logging\nimport functools\n\nlogger = logging.getLogger(__name__)\n\n\nclass Distancing:\n\n def __init__(self, config, source, live_feed_enabled=True):\n self.config = config\n self.detector = None\n self.device = self.config.get_section_dict('Detector')['Device']\n\n self.live_feed_enabled = live_feed_enabled\n self.log_time_interval = float(self.config.get_section_dict(\"Logger\")[\"TimeInterval\"]) # Seconds\n\n self.classifier = None\n self.classifier_img_size = None\n self.face_mask_classifier = None\n\n self.running_video = False\n self.tracker = IOUTracker(\n max_lost=int(self.config.get_section_dict(\"PostProcessor\")[\"MaxLost\"]),\n iou_threshold=float(self.config.get_section_dict(\"PostProcessor\")[\"TrackerIOUThreshold\"]),\n min_detection_confidence=0.2,\n max_detection_confidence=1.0\n )\n self.camera_id = self.config.get_section_dict(source)['Id']\n self.logger = Logger(self.config, self.camera_id)\n self.image_size = [int(i) for i in self.config.get_section_dict('Detector')['ImageSize'].split(',')]\n self.default_dist_method = self.config.get_section_dict('PostProcessor')[\"DefaultDistMethod\"]\n\n if self.config.get_section_dict(source)[\"DistMethod\"]:\n self.dist_method = self.config.get_section_dict(source)[\"DistMethod\"]\n else:\n self.dist_method = self.default_dist_method\n\n self.dist_threshold = self.config.get_section_dict(\"PostProcessor\")[\"DistThreshold\"]\n self.resolution = tuple([int(i) for i in self.config.get_section_dict('App')['Resolution'].split(',')])\n self.birds_eye_resolution = (200, 300)\n\n if self.dist_method == \"CalibratedDistance\":\n calibration_file = get_camera_calibration_path(\n self.config, self.config.get_section_dict(source)[\"Id\"])\n try:\n with open(calibration_file, \"r\") as file:\n self.h_inv = file.readlines()[0].split(\" \")[1:]\n self.h_inv = np.array(self.h_inv, dtype=\"float\").reshape((3, 3))\n except FileNotFoundError:\n logger.error(\"The specified 'CalibrationFile' does not exist\")\n logger.info(f\"Falling back using {self.default_dist_method}\")\n self.dist_method = self.default_dist_method\n\n # config.ini uses minutes as unit\n self.screenshot_period = float(self.config.get_section_dict(\"App\")[\"ScreenshotPeriod\"]) * 60\n self.bucket_screenshots = config.get_section_dict(\"App\")[\"ScreenshotS3Bucket\"]\n self.uploader = S3Uploader(self.config)\n self.screenshot_path = os.path.join(self.config.get_section_dict(\"App\")[\"ScreenshotsDirectory\"], self.camera_id)\n if not os.path.exists(self.screenshot_path):\n os.makedirs(self.screenshot_path)\n\n if \"Classifier\" in self.config.get_sections():\n self.face_threshold = float(self.config.get_section_dict(\"Classifier\").get(\"MinScore\", 0.75))\n\n def __process(self, cv_image):\n \"\"\"\n return object_list list of dict for each obj,\n obj[\"bbox\"] is normalized coordinations for [x0, y0, x1, y1] of box\n \"\"\"\n\n # Resize input image to resolution\n cv_image = cv.resize(cv_image, self.resolution)\n\n resized_image = cv.resize(cv_image, tuple(self.image_size[:2]))\n rgb_resized_image = cv.cvtColor(resized_image, cv.COLOR_BGR2RGB)\n tmp_objects_list = self.detector.inference(rgb_resized_image)\n \n [w, h] = self.resolution\n detection_scores = []\n class_ids = []\n detection_bboxes = []\n faces = []\n # Get the classifier of detected face\n for itm in tmp_objects_list:\n if 'face' in itm.keys() and self.classifier is not None:\n face_bbox = itm['face'] # [ymin, xmin, ymax, xmax]\n if face_bbox is not None:\n xmin, xmax = np.multiply([face_bbox[1], face_bbox[3]], self.resolution[0])\n ymin, ymax = np.multiply([face_bbox[0], face_bbox[2]], self.resolution[1])\n croped_face = cv_image[\n int(ymin):int(ymin) + (int(ymax) - int(ymin)),\n int(xmin):int(xmin) + (int(xmax) - int(xmin))\n ]\n\n # Resizing input image\n croped_face = cv.resize(croped_face, tuple(self.classifier_img_size[:2]))\n croped_face = cv.cvtColor(croped_face, cv.COLOR_BGR2RGB)\n # Normalizing input image to [0.0-1.0]\n croped_face = np.array(croped_face) / 255.0\n faces.append(croped_face)\n # Prepare tracker input\n box = itm[\"bbox\"]\n x0 = box[1]\n y0 = box[0]\n x1 = box[3]\n y1 = box[2]\n detection_scores.append(itm['score'])\n class_ids.append(int(itm['id'].split('-')[0]))\n detection_bboxes.append((int(x0 * w), int(y0 * h), int(x1 * w), int(y1 * h)))\n faces = np.array(faces)\n face_mask_results, scores = self.classifier.inference(faces)\n\n tracks = self.tracker.update(detection_bboxes, class_ids, detection_scores)\n tracked_objects_list = []\n idx = 0\n for obj in tmp_objects_list:\n if self.classifier is not None and 'face' in obj.keys():\n if obj['face'] is not None and scores[idx] > self.face_threshold:\n obj['face_label'] = face_mask_results[idx]\n idx = idx + 1\n else:\n obj['face_label'] = -1\n box = obj[\"bbox\"]\n x0 = box[1]\n y0 = box[0]\n x1 = box[3]\n y1 = box[2]\n obj[\"centroid\"] = [(x0 + x1) / 2, (y0 + y1) / 2, x1 - x0, y1 - y0]\n obj[\"bbox\"] = [x0, y0, x1, y1]\n obj[\"centroidReal\"] = [(x0 + x1) * w / 2, (y0 + y1) * h / 2, (x1 - x0) * w, (y1 - y0) * h]\n obj[\"bboxReal\"] = [x0 * w, y0 * h, x1 * w, y1 * h]\n for track in tracks:\n track_count, trackid, class_id_o, centroid, track_bbox, track_info = track\n selected_box = [int(x0 * w), int(y0 * h), int(x1 * w), int(y1 * h)]\n if functools.reduce(lambda x, y: x and y, map(lambda p, q: p == q, selected_box, track_bbox), True):\n obj[\"tracked_id\"] = trackid\n obj[\"track_info\"] = track_info\n tracked_objects_list.append(obj)\n\n # objects_list, distancings = self.calculate_distancing(tmp_objects_list)\n objects_list, distancings = self.calculate_distancing(tracked_objects_list)\n anonymize = self.config.get_section_dict('PostProcessor')['Anonymize'] == \"true\"\n if anonymize:\n cv_image = self.anonymize_image(cv_image, objects_list)\n return cv_image, objects_list, distancings\n\n def gstreamer_writer(self, feed_name, fps, resolution):\n \"\"\"\n This method creates and returns an OpenCV Video Writer instance. The VideoWriter expects its `.write()` method\n to be called with a single frame image multiple times. It encodes frames into live video segments and produces\n a video segment once it has received enough frames to produce a 5-seconds segment of live video.\n The video segments are written on the filesystem. The target directory for writing segments is determined by\n `video_root` variable. In addition to writing the video segments, the VideoWriter also updates a file named\n playlist.m3u8 in the target directory. This file contains the list of generated video segments and is updated\n automatically.\n This instance does not serve these video segments to the client. It is expected that the target video directory\n is being served by a static file server and the clientside HLS video library downloads \"playlist.m3u8\". Then,\n the client video player reads the link for video segments, according to HLS protocol, and downloads them from\n static file server.\n\n :param feed_name: Is the name for video feed. We may have multiple cameras, each with multiple video feeds (e.g. one\n feed for visualizing bounding boxes and one for bird's eye view). Each video feed should be written into a\n separate directory. The name for target directory is defined by this variable.\n :param fps: The HLS video player on client side needs to know how many frames should be shown to the user per\n second. This parameter is independent from the frame rate with which the video is being processed. For example,\n if we set fps=60, but produce only frames (by calling `.write()`) per second, the client will see a loading\n indicator for 5*60/30 seconds and then 5 seconds of video is played with fps 60.\n :param resolution: A tuple of size 2 which indicates the resolution of output video.\n \"\"\"\n encoder = self.config.get_section_dict('App')['Encoder']\n video_root = f'/repo/data/processor/static/gstreamer/{feed_name}'\n\n shutil.rmtree(video_root, ignore_errors=True)\n os.makedirs(video_root, exist_ok=True)\n\n playlist_root = f'/static/gstreamer/{feed_name}'\n if not playlist_root.endswith('/'):\n playlist_root = f'{playlist_root}/'\n # the entire encoding pipeline, as a string:\n pipeline = f'appsrc is-live=true ! {encoder} ! mpegtsmux ! hlssink max-files=15 ' \\\n f'target-duration=5 ' \\\n f'playlist-root={playlist_root} ' \\\n f'location={video_root}/video_%05d.ts ' \\\n f'playlist-location={video_root}/playlist.m3u8 '\n\n out = cv.VideoWriter(\n pipeline,\n cv.CAP_GSTREAMER,\n 0, fps, resolution\n )\n\n if not out.isOpened():\n raise RuntimeError(\"Could not open gstreamer output for \" + feed_name)\n return out\n\n def process_live_feed(self, cv_image, objects, distancings, violating_objects, out, out_birdseye):\n dist_threshold = float(self.config.get_section_dict(\"PostProcessor\")[\"DistThreshold\"])\n birds_eye_window = np.zeros(self.birds_eye_resolution[::-1] + (3,), dtype=\"uint8\")\n class_id = int(self.config.get_section_dict('Detector')['ClassID'])\n\n output_dict = visualization_utils.visualization_preparation(objects, distancings, dist_threshold)\n category_index = {class_id: {\n \"id\": class_id,\n \"name\": \"Pedestrian\",\n }} # TODO: json file for detector config\n face_index = {\n 0: \"YES\",\n 1: \"NO\",\n -1: \"N/A\",\n }\n # Draw bounding boxes and other visualization factors on input_frame\n visualization_utils.visualize_boxes_and_labels_on_image_array(\n cv_image,\n output_dict[\"detection_boxes\"],\n output_dict[\"detection_classes\"],\n output_dict[\"detection_scores\"],\n output_dict[\"detection_colors\"],\n output_dict[\"tacked_ids\"],\n category_index,\n instance_masks=output_dict.get(\"detection_masks\"),\n use_normalized_coordinates=True,\n line_thickness=3,\n face_labels=output_dict[\"face_labels\"],\n face_index=face_index\n )\n # TODO: Implement perspective view for objects\n birds_eye_window = visualization_utils.birds_eye_view(\n birds_eye_window, output_dict[\"detection_boxes\"], output_dict[\"violating_objects\"])\n try:\n fps = self.detector.fps\n except:\n # fps is not implemented for the detector instance\"\n fps = None\n\n # Put fps to the frame\n # region\n # -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_-\n txt_fps = 'Frames rate = ' + str(fps) + '(fps)' # Frames rate = 95 (fps)\n # (0, 0) is the top-left (x,y); normalized number between 0-1\n origin = (0.05, 0.93)\n visualization_utils.text_putter(cv_image, txt_fps, origin)\n # -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_-\n # endregion\n\n # Put environment score to the frame\n # region\n # -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_-\n env_score = mx_environment_scoring_consider_crowd(len(objects), len(violating_objects))\n txt_env_score = 'Env Score = ' + str(env_score) # Env Score = 0.7\n origin = (0.05, 0.98)\n visualization_utils.text_putter(cv_image, txt_env_score, origin)\n # -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_- -_-\n # endregion\n\n out.write(cv_image)\n out_birdseye.write(birds_eye_window)\n\n def process_video(self, video_uri):\n if self.device == 'Jetson':\n from libs.detectors.jetson.detector import Detector\n self.detector = Detector(self.config)\n elif self.device == 'EdgeTPU':\n from libs.detectors.edgetpu.detector import Detector\n from libs.classifiers.edgetpu.classifier import Classifier\n self.detector = Detector(self.config)\n if \"Classifier\" in self.config.get_sections():\n self.classifier = Classifier(self.config)\n self.classifier_img_size = [int(i) for i in\n self.config.get_section_dict(\"Classifier\")[\"ImageSize\"].split(\",\")]\n elif self.device == 'Dummy':\n from libs.detectors.dummy.detector import Detector\n self.detector = Detector(self.config)\n elif self.device in ['x86', 'x86-gpu']:\n from libs.detectors.x86.detector import Detector\n from libs.classifiers.x86.classifier import Classifier\n self.detector = Detector(self.config)\n if \"Classifier\" in self.config.get_sections():\n self.classifier = Classifier(self.config)\n self.classifier_img_size = [int(i) for i in\n self.config.get_section_dict(\"Classifier\")[\"ImageSize\"].split(\",\")]\n\n if self.device != 'Dummy':\n print('Device is: ', self.device)\n print('Detector is: ', self.detector.name)\n print('image size: ', self.image_size)\n\n input_cap = cv.VideoCapture(video_uri)\n fps = max(25, input_cap.get(cv.CAP_PROP_FPS))\n\n if (input_cap.isOpened()):\n logger.info(f'opened video {video_uri}')\n else:\n logger.error(f'failed to load video {video_uri}')\n return\n\n self.running_video = True\n # enable logging gstreamer Errors (https://stackoverflow.com/questions/3298934/how-do-i-view-gstreamer-debug-output)\n os.environ['GST_DEBUG'] = \"*:1\"\n if self.live_feed_enabled:\n out, out_birdseye = (\n self.gstreamer_writer(feed, fps, resolution)\n for (feed, resolution) in (\n (self.camera_id, self.resolution),\n (self.camera_id + '-birdseye', self.birds_eye_resolution)\n )\n )\n\n dist_threshold = float(self.config.get_section_dict(\"PostProcessor\")[\"DistThreshold\"])\n frame_num = 0\n start_time = time.time()\n last_processed_time = time.time()\n while input_cap.isOpened() and self.running_video:\n _, cv_image = input_cap.read()\n if np.shape(cv_image) != ():\n if not self.live_feed_enabled and (time.time() - last_processed_time < self.log_time_interval):\n continue\n cv_image, objects, distancings = self.__process(cv_image)\n violating_objects = extract_violating_objects(distancings, dist_threshold)\n if self.live_feed_enabled:\n self.process_live_feed(cv_image, objects, distancings, violating_objects, out, out_birdseye)\n last_processed_time = time.time()\n frame_num += 1\n if frame_num % 100 == 1:\n logger.info(f'processed frame {frame_num} for {video_uri}')\n # Save a screenshot only if the period is greater than 0, a violation is detected, and the minimum period\n # has occured\n if (self.screenshot_period > 0) and (time.time() > start_time + self.screenshot_period) and (\n len(violating_objects) > 0):\n start_time = time.time()\n self.capture_violation(f\"{start_time}_violation.jpg\", cv_image)\n self.save_screenshot(cv_image)\n else:\n continue\n self.logger.update(objects, distancings)\n input_cap.release()\n if self.live_feed_enabled:\n out.release()\n out_birdseye.release()\n del self.detector\n self.running_video = False\n\n def stop_process_video(self):\n self.running_video = False\n\n def calculate_distancing(self, objects_list):\n \"\"\"\n this function post-process the raw boxes of object detector and calculate a distance matrix\n for detected bounding boxes.\n post processing is consist of:\n 1. omitting large boxes by filtering boxes which are bigger than the 1/4 of the size the image.\n 2. omitting duplicated boxes by applying an auxilary non-maximum-suppression.\n 3. apply a simple object tracker to make the detection more robust.\n\n params:\n object_list: a list of dictionaries. each dictionary has attributes of a detected object such as\n \"id\", \"centroid\" (a tuple of the normalized centroid coordinates (cx,cy,w,h) of the box) and \"bbox\" (a tuple\n of the normalized (xmin,ymin,xmax,ymax) coordinate of the box)\n\n returns:\n object_list: the post processed version of the input\n distances: a NxN ndarray which i,j element is distance between i-th and l-th bounding box\n\n \"\"\"\n new_objects_list = self.ignore_large_boxes(objects_list)\n new_objects_list = self.non_max_suppression_fast(new_objects_list,\n float(self.config.get_section_dict(\"PostProcessor\")[\n \"NMSThreshold\"]))\n tracked_boxes = self.tracker.update(new_objects_list)\n new_objects_list = [tracked_boxes[i] for i in tracked_boxes.keys()]\n for i, item in enumerate(new_objects_list):\n item[\"id\"] = item[\"id\"].split(\"-\")[0] + \"-\" + str(i)\n distances = self.calculate_box_distances(new_objects_list)\n\n return new_objects_list, distances\n\n @staticmethod\n def ignore_large_boxes(object_list):\n\n \"\"\"\n filtering boxes which are biger than the 1/4 of the size the image\n params:\n object_list: a list of dictionaries. each dictionary has attributes of a detected object such as\n \"id\", \"centroid\" (a tuple of the normalized centroid coordinates (cx,cy,w,h) of the box) and \"bbox\" (a tuple\n of the normalized (xmin,ymin,xmax,ymax) coordinate of the box)\n returns:\n object_list: input object list without large boxes\n \"\"\"\n large_boxes = []\n for i in range(len(object_list)):\n if (object_list[i][\"centroid\"][2] * object_list[i][\"centroid\"][3]) > 0.25:\n large_boxes.append(i)\n updated_object_list = [j for i, j in enumerate(object_list) if i not in large_boxes]\n return updated_object_list\n\n @staticmethod\n def non_max_suppression_fast(object_list, overlapThresh):\n\n \"\"\"\n omitting duplicated boxes by applying an auxilary non-maximum-suppression.\n params:\n object_list: a list of dictionaries. each dictionary has attributes of a detected object such\n \"id\", \"centroid\" (a tuple of the normalized centroid coordinates (cx,cy,w,h) of the box) and \"bbox\" (a tuple\n of the normalized (xmin,ymin,xmax,ymax) coordinate of the box)\n\n overlapThresh: threshold of minimum IoU of to detect two box as duplicated.\n\n returns:\n object_list: input object list without duplicated boxes\n \"\"\"\n # if there are no boxes, return an empty list\n boxes = np.array([item[\"centroid\"] for item in object_list])\n corners = np.array([item[\"bbox\"] for item in object_list])\n if len(boxes) == 0:\n return []\n if boxes.dtype.kind == \"i\":\n boxes = boxes.astype(\"float\")\n # initialize the list of picked indexes\n pick = []\n cy = boxes[:, 1]\n cx = boxes[:, 0]\n h = boxes[:, 3]\n w = boxes[:, 2]\n x1 = corners[:, 0]\n x2 = corners[:, 2]\n y1 = corners[:, 1]\n y2 = corners[:, 3]\n area = (h + 1) * (w + 1)\n idxs = np.argsort(cy + (h / 2))\n while len(idxs) > 0:\n last = len(idxs) - 1\n i = idxs[last]\n pick.append(i)\n xx1 = np.maximum(x1[i], x1[idxs[:last]])\n yy1 = np.maximum(y1[i], y1[idxs[:last]])\n xx2 = np.minimum(x2[i], x2[idxs[:last]])\n yy2 = np.minimum(y2[i], y2[idxs[:last]])\n\n w = np.maximum(0, xx2 - xx1 + 1)\n h = np.maximum(0, yy2 - yy1 + 1)\n # compute the ratio of overlap\n overlap = (w * h) / area[idxs[:last]]\n # delete all indexes from the index list that have\n idxs = np.delete(idxs, np.concatenate(([last],\n np.where(overlap > overlapThresh)[0])))\n updated_object_list = [j for i, j in enumerate(object_list) if i in pick]\n return updated_object_list\n\n def calculate_distance_of_two_points_of_boxes(self, first_point, second_point):\n\n \"\"\"\n This function calculates a distance l for two input corresponding points of two detected bounding boxes.\n it is assumed that each person is H = 170 cm tall in real scene to map the distances in the image (in pixels) to\n physical distance measures (in meters).\n\n params:\n first_point: (x, y, h)-tuple, where x,y is the location of a point (center or each of 4 corners of a bounding box)\n and h is the height of the bounding box.\n second_point: same tuple as first_point for the corresponding point of other box\n\n returns:\n l: Estimated physical distance (in centimeters) between first_point and second_point.\n\n\n \"\"\"\n\n # estimate corresponding points distance\n [xc1, yc1, h1] = first_point\n [xc2, yc2, h2] = second_point\n\n dx = xc2 - xc1\n dy = yc2 - yc1\n\n lx = dx * 170 * (1 / h1 + 1 / h2) / 2\n ly = dy * 170 * (1 / h1 + 1 / h2) / 2\n\n l = math.sqrt(lx ** 2 + ly ** 2)\n\n return l\n\n def calculate_box_distances(self, nn_out):\n\n \"\"\"\n This function calculates a distance matrix for detected bounding boxes.\n Three methods are implemented to calculate the distances, the first one estimates distance with a calibration matrix\n which transform the points to the 3-d world coordinate, the second one estimates distance of center points of the\n boxes and the third one uses minimum distance of each of 4 points of bounding boxes.\n\n params:\n object_list: a list of dictionaries. each dictionary has attributes of a detected object such as\n \"id\", \"centroidReal\" (a tuple of the centroid coordinates (cx,cy,w,h) of the box) and \"bboxReal\" (a tuple\n of the (xmin,ymin,xmax,ymax) coordinate of the box)\n\n returns:\n distances: a NxN ndarray which i,j element is estimated distance between i-th and j-th bounding box in real scene (cm)\n\n \"\"\"\n if self.dist_method == \"CalibratedDistance\":\n world_coordinate_points = np.array([self.transform_to_world_coordinate(bbox) for bbox in nn_out])\n if len(world_coordinate_points) == 0:\n distances_asarray = np.array([])\n else:\n distances_asarray = cdist(world_coordinate_points, world_coordinate_points)\n\n else:\n distances = []\n for i in range(len(nn_out)):\n distance_row = []\n for j in range(len(nn_out)):\n if i == j:\n l = 0\n else:\n if (self.dist_method == 'FourCornerPointsDistance'):\n lower_left_of_first_box = [nn_out[i][\"bboxReal\"][0], nn_out[i][\"bboxReal\"][1],\n nn_out[i][\"centroidReal\"][3]]\n lower_right_of_first_box = [nn_out[i][\"bboxReal\"][2], nn_out[i][\"bboxReal\"][1],\n nn_out[i][\"centroidReal\"][3]]\n upper_left_of_first_box = [nn_out[i][\"bboxReal\"][0], nn_out[i][\"bboxReal\"][3],\n nn_out[i][\"centroidReal\"][3]]\n upper_right_of_first_box = [nn_out[i][\"bboxReal\"][2], nn_out[i][\"bboxReal\"][3],\n nn_out[i][\"centroidReal\"][3]]\n\n lower_left_of_second_box = [nn_out[j][\"bboxReal\"][0], nn_out[j][\"bboxReal\"][1],\n nn_out[j][\"centroidReal\"][3]]\n lower_right_of_second_box = [nn_out[j][\"bboxReal\"][2], nn_out[j][\"bboxReal\"][1],\n nn_out[j][\"centroidReal\"][3]]\n upper_left_of_second_box = [nn_out[j][\"bboxReal\"][0], nn_out[j][\"bboxReal\"][3],\n nn_out[j][\"centroidReal\"][3]]\n upper_right_of_second_box = [nn_out[j][\"bboxReal\"][2], nn_out[j][\"bboxReal\"][3],\n nn_out[j][\"centroidReal\"][3]]\n\n l1 = self.calculate_distance_of_two_points_of_boxes(lower_left_of_first_box,\n lower_left_of_second_box)\n l2 = self.calculate_distance_of_two_points_of_boxes(lower_right_of_first_box,\n lower_right_of_second_box)\n l3 = self.calculate_distance_of_two_points_of_boxes(upper_left_of_first_box,\n upper_left_of_second_box)\n l4 = self.calculate_distance_of_two_points_of_boxes(upper_right_of_first_box,\n upper_right_of_second_box)\n\n l = min(l1, l2, l3, l4)\n elif (self.dist_method == 'CenterPointsDistance'):\n center_of_first_box = [nn_out[i][\"centroidReal\"][0], nn_out[i][\"centroidReal\"][1],\n nn_out[i][\"centroidReal\"][3]]\n center_of_second_box = [nn_out[j][\"centroidReal\"][0], nn_out[j][\"centroidReal\"][1],\n nn_out[j][\"centroidReal\"][3]]\n\n l = self.calculate_distance_of_two_points_of_boxes(center_of_first_box,\n center_of_second_box)\n distance_row.append(l)\n distances.append(distance_row)\n distances_asarray = np.asarray(distances, dtype=np.float32)\n return distances_asarray\n\n def transform_to_world_coordinate(self, bbox):\n \"\"\"\n This function will transform the center of the bottom line of a bounding box from image coordinate to world\n coordinate via a homography matrix\n Args:\n bbox: a dictionary of a coordinates of a detected instance with \"id\",\n \"centroidReal\" (a tuple of the centroid coordinates (cx,cy,w,h) of the box) and \"bboxReal\" (a tuple\n of the (xmin,ymin,xmax,ymax) coordinate of the box) keys\n\n Returns:\n A numpy array of (X,Y) of transformed point\n\n \"\"\"\n floor_point = np.array([int((bbox[\"bboxReal\"][0] + bbox[\"bboxReal\"][2]) / 2), bbox[\"bboxReal\"][3], 1])\n floor_world_point = np.matmul(self.h_inv, floor_point)\n floor_world_point = floor_world_point[:-1] / floor_world_point[-1]\n return floor_world_point\n\n def anonymize_image(self, img, objects_list):\n \"\"\"\n Anonymize every instance in the frame.\n \"\"\"\n h, w = img.shape[:2]\n for box in objects_list:\n xmin = max(int(box[\"bboxReal\"][0]), 0)\n xmax = min(int(box[\"bboxReal\"][2]), w)\n ymin = max(int(box[\"bboxReal\"][1]), 0)\n ymax = min(int(box[\"bboxReal\"][3]), h)\n ymax = (ymax - ymin) // 3 + ymin\n roi = img[ymin:ymax, xmin:xmax]\n roi = self.anonymize_face(roi)\n img[ymin:ymax, xmin:xmax] = roi\n return img\n\n @staticmethod\n def anonymize_face(image):\n \"\"\"\n Blur an image to anonymize the person's faces.\n \"\"\"\n (h, w) = image.shape[:2]\n kernel_w = int(w / 3)\n kernel_h = int(h / 3)\n if kernel_w % 2 == 0:\n kernel_w = max(1, kernel_w - 1)\n if kernel_h % 2 == 0:\n kernel_h = max(1, kernel_h - 1)\n return cv.GaussianBlur(image, (kernel_w, kernel_h), 0)\n\n # TODO: Make this an async task?\n def capture_violation(self, file_name, cv_image):\n self.uploader.upload_cv_image(self.bucket_screenshots, cv_image, file_name, self.camera_id)\n\n def save_screenshot(self, cv_image):\n dir_path = f'{self.screenshot_path}/default.jpg'\n if not os.path.exists(dir_path):\n logger.info(f\"Saving default screenshot for {self.camera_id}\")\n cv.imwrite(f'{self.screenshot_path}/default.jpg', cv_image)\n","sub_path":"libs/distancing.py","file_name":"distancing.py","file_ext":"py","file_size_in_byte":30711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"633652373","text":"from room import Room\nfrom player import Player\nfrom world import World\n\nimport random\nfrom ast import literal_eval\n\n# Load world\nworld = World()\n\n\n# You may uncomment the smaller graphs for development and testing purposes.\n# map_file = \"maps/test_line.txt\"\n# map_file = \"maps/test_cross.txt\"\n# map_file = \"maps/test_loop.txt\"\n# map_file = \"maps/test_loop_fork.txt\"\nmap_file = \"maps/main_maze.txt\"\n\n# Loads the map into a dictionary\nroom_graph=literal_eval(open(map_file, \"r\").read())\nworld.load_graph(room_graph)\n\n# Print an ASCII map\nworld.print_rooms()\n\nplayer = Player(world.starting_room)\n\n# Fill this out with directions to walk\n# traversal_path = ['n', 'n']\n\n\n## BFT to traverse all rooms\n## keep track of how many moves to traverse\ntraversal_path = []\n## a dictionary of all the rooms we have visited\nvisited = {}\n## path array\npath = []\n## reverse directions to get back out of a room\ndirections = {'n': 's', 's': 'n', 'e': 'w', 'w': 'e'}\n\n# append the current room to the visited dictionary\n# \"getExists\" to navigate throughout the world\nvisited[player.current_room.id] = player.current_room.get_exits()\n\n## loop till player have visited all the rooms\nwhile len(visited) < len(room_graph) - 1:\n ## check if the player's room is not in visited\n if player.current_room.id not in visited:\n ## add it to the visited dictionary\n ## remove the previous set of exists and replace it with the current rooms exists\n visited[player.current_room.id] = player.current_room.get_exits()\n previous_direction = path[-1]\n visited[player.current_room.id].remove(previous_direction)\n\n ## up until this point we have a BFT\n ## however we need to find ALL rooms.\n ## find num of rooms\n ## check is len(visited) >= len(rooms)\n\n ## while the len of the visited rooms directions are 0.\n ## Reached end, or a dead end\n\n while len(visited[player.current_room.id]) == 0:\n ## backtrack/pop path return to previous direction\n previous_direction = path.pop()\n traversal_path.append(previous_direction)\n ## travel function from player class allows to move to the previous room\n player.travel(previous_direction)\n\n ## find the current rooms get_exits and then we find the last value on that list with pop\n move = visited[player.current_room.id].pop(0)\n ## we then append it to the path since its the direction we want to go\n traversal_path.append(move)\n ## we append it to the path so we can record the room we just visited\n path.append(directions[move])\n ## move direction with the players function travel. will be backtracking via the direction dictionary at top\n player.travel(move)\n\n\n\n# TRAVERSAL TEST - DO NOT MODIFY\nvisited_rooms = set()\nplayer.current_room = world.starting_room\nvisited_rooms.add(player.current_room)\n\nfor move in traversal_path:\n player.travel(move)\n visited_rooms.add(player.current_room)\n\nif len(visited_rooms) == len(room_graph):\n print(f\"TESTS PASSED: {len(traversal_path)} moves, {len(visited_rooms)} rooms visited\")\nelse:\n print(\"TESTS FAILED: INCOMPLETE TRAVERSAL\")\n print(f\"{len(room_graph) - len(visited_rooms)} unvisited rooms\")\n\n\n\n#######\n# UNCOMMENT TO WALK AROUND\n#######\nplayer.current_room.print_room_description(player)\nwhile True:\n cmds = input(\"-> \").lower().split(\" \")\n if cmds[0] in [\"n\", \"s\", \"e\", \"w\"]:\n player.travel(cmds[0], True)\n elif cmds[0] == \"q\":\n break\n else:\n print(\"I did not understand that command.\")","sub_path":"adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"252074360","text":"import pickle\nimport numpy as np\nimport random\nimport os.path\nfrom pref_gen import *\nfrom configure import *\n\n##def make_requests(region_lst, arrival_rate, interval, total_time, zipf_lst):\n## req_lst = list()\n## t = 0\n## while t < total_time:\n## req_num = np.random.poisson(arrival_rate, size = len(region_lst))\n## for r_idx in range(len(region_lst)):\n## cnt_dict = dict()\n## if req_num[r_idx] != 0:\n## n = req_num[r_idx]\n## samples = zipf_lst[r_idx].get_sample(size=n)\n## for sample in samples:\n## cnt_dict[sample] = cnt_dict.get(sample, 0)+1\n## req_lst.append((t, region_lst[r_idx].id, sample)) #(t, region_id, content)\n## a = sorted(cnt_dict.items(), key=lambda x: x[1], reverse=True)\n#### print(a)\n##\n#### for i in range(req_num[r_idx]):\n#### req_lst.append((t, region_lst[r_idx].id, zipf_lst[r_idx].get_sample())) #(t, region_id, content)\n## t += interval\n## req_lst.sort(key=lambda x: x[0])\n## return req_lst\n\ndef make_requests(region_lst, request_rate, zipf_lst):\n req_lst = [[] for _ in range(len(region_lst))]\n\n req_num = np.random.poisson(request_rate, size = len(region_lst))\n for r_idx in range(len(region_lst)):\n if req_num[r_idx] != 0:\n n = req_num[r_idx]\n samples = zipf_lst[r_idx].get_sample(size=n)\n req_lst[r_idx] = samples\n return req_lst\n\ndef save_requests(file, req_lst):\n with open(os.path.join(file), 'wb') as f:\n pickle.dump(req_lst, f)\n print(\"Success to save the requests\")\n \ndef load_requests(file):\n with open(os.path.join(file), 'rb') as f:\n print(\"Success to load the requests\")\n return pickle.load(f)\n\ndef make_preference(region_num, type_num, contents_num, zipf_param, user_density, user_num):\n region_lst = [PrefGenerator(i) for i in range(region_num)]\n base_type_lst = region_lst[0].make_pref_type(type_num, contents_num, zipf_param) #make type\n region_lst[0].user_density = user_density[0]\n for i in range(1, region_num):\n region_lst[i].set_pref_type(base_type_lst)\n region_lst[i].user_density = user_density[i]\n\n pref_lst = list()\n for region in region_lst:\n d = dict() #user preference history\n for i in range(user_num):\n user = User(i)\n record_history(region, i, d)\n # user_type, pdf, cdf = region.make_user_pref(type_weight=add_noise(region.user_density, 0.0001))\n # user.set_char(region, user_type, pdf, cdf)\n region.add_user(user)\n pref_lst.append(d)\n return region_lst, pref_lst\n\ndef record_history(region, user_id, d):\n for t in range(time_period):\n user_type, pdf, cdf = region.make_user_pref(type_weight=add_noise(region.user_density, 0.0001))\n if user_id in d.keys():\n d[user_id].append((user_type, pdf, cdf))\n else:\n d[user_id] = [(user_type, pdf, cdf)]\n \n \ndef save_preference(file, pref):\n with open(os.path.join(file), 'wb') as f:\n pickle.dump(pref, f)\n print(\"Success to save the preference\")\n\ndef load_preference(file):\n with open(os.path.join(file), 'rb') as f:\n print(\"Success to load the preference\")\n return pickle.load(f)\n\n \n","sub_path":"req_gen.py","file_name":"req_gen.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"497619824","text":"import datetime\nfrom flask import render_template, flash, redirect, url_for, request\nfrom flask_login import current_user, login_user, logout_user, login_required\nfrom flask_mail import Mail, Message\nfrom app import app, db\nfrom app.forms import LoginForm, AddVehicle, RegistrationForm, OilChangeForm, AddAvailability, ScheduleAppointment, \\\n EditAppointmentForm, DeleteAppointmentForm, ReviewMechanic, Suggestions\nfrom app.models import User, Car, Availability, Schedules, Reviews, Mechanic_Ratings, Recommendations\nfrom flask import Flask\n\napp.config['DEBUG'] = True\napp.config['TESTING'] = False\napp.config['MAIL_SERVER'] = 'smtp.gmail.com'\napp.config['MAIL_PORT'] = 587\napp.config['MAIL_USE_TLS'] = True\napp.config['MAIL_USE_SSL'] = False\n# app.config['MAIL_DEBUG'] = True\napp.config['MAIL_USERNAME'] = 'groupbsoftwareengineering1166@gmail.com'\napp.config['MAIL_PASSWORD'] = 'SoftwareEngineering1166'\napp.config['MAIL_DEFAULT_SENDER'] = 'groupbsoftwareengineering1166@gmail.com'\napp.config['MAIL_MAX_EMAILS'] = None\n# app.config['MAIL_SUPPRESS_SEND'] = False\napp.config['MAIL_ASCII_ATTACHMENTS'] = False\n\nmail = Mail(app)\n\n\ndef appointment_reminder():\n appointments = Schedules.query.all()\n users = User.query.all()\n\n with app.app_context():\n for x in appointments:\n diff = x.appointment_date - datetime.date.today()\n for i in users:\n if diff.days == 3 and i.user == x.user and i.role == 'Car Owner':\n msg = Message('Appointment Reminder Notification', recipients=[i.email])\n msg.html = 'Hello, You have an appointment scheduled in 3 days. We hope to see you!'\n mail.send(msg)\n if diff.days < 1 and i.user == x.user and i.role == 'Car Owner':\n msg = Message('Follow up for oil change appointment', recipients=[i.email])\n msg.body = 'Hello, I hope your appointment went well. If you could please take the brief survey ' \\\n 'and review your mechanic we would highly appreciate it.'\n msg.html = 'Hello, I hope your appointment went well. If you could please take the brief survey ' \\\n 'and review your mechanic we would highly appreciate it.' \\\n ' Click here to access review'\n mail.send(msg)\n if diff.days < 1 and x.mechanic == i.user and i.role == 'Mechanic':\n msg = Message('Follow up for oil change appointment', recipients=[i.email])\n msg.body = 'Hello, I hope your appointment went well. If you could please take the brief survey ' \\\n 'and review your mechanic we would highly appreciate it.'\n msg.html = 'Hello, I hope your appointment went well. If you could please take a second to ' \\\n 'suggest other repairs that the customer may need we would highly appreciate it.' \\\n ' Click here to access ' \\\n 'review '\n mail.send(msg)\n\n return app\n\n\nappointment_reminder()\n\n\n@app.route('/')\n@app.route('/index')\n@login_required\ndef index():\n cars = Car.query.all()\n appointments = Schedules.query.all()\n return render_template('index.html', title='Home',cars=cars, appointments=appointments)\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n if form.validate_on_submit():\n\n user = User.query.filter_by(user=form.user.data).first()\n\n if user.role == 'Car Owner' and user.check_password(form.password.data):\n login_user(user, remember=form.remember_me.data)\n return redirect(url_for('index'))\n elif user.role == 'Mechanic' and user.check_password(form.password.data):\n login_user(user, remember=form.remember_me.data)\n return redirect(url_for('mechanicDashboard'))\n return render_template('login.html', title='Sign In', form=form)\n\n\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('index'))\n\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = RegistrationForm()\n if form.validate_on_submit():\n user = User(user=form.user.data, email=form.email.data, role=form.role.data)\n user.set_password(form.password.data)\n db.session.add(user)\n db.session.commit()\n flash('You are now signed up to use our App!')\n return redirect(url_for('login'))\n return render_template('register.html', title='Register', form=form)\n\n\n@app.route('/user/')\ndef user(user):\n user = User.query.filter_by(user=user).first_or_404()\n cars = [\n {'owner': user, 'car_vin': 'Test post #1'},\n {'owner': user, 'car_vin': 'Test post #2'}\n ]\n return render_template('user.html', user=user, cars=cars)\n\n\n@app.route('/addVehicle', methods=['GET', 'POST'])\ndef RegisterCar():\n form = AddVehicle()\n if form.validate_on_submit():\n car = Car(user=current_user.user, car_vin=form.car_vin.data, make=form.make.data, model=form.model.data,\n color=form.color.data, mileage=form.mileage.data)\n db.session.add(car)\n db.session.commit()\n flash('You have added a car to use in our App!')\n return redirect(url_for('index'))\n return render_template('addVehicle.html', title='Add Vehicle', form=form)\n\n\n@app.route('/addAvailability', methods=['GET', 'POST'])\ndef addAvailability():\n form = AddAvailability()\n if form.validate_on_submit():\n time = Availability(user=current_user.user, date=form.date.data, start_time=form.start_time.data,\n end_time=form.end_time.data)\n db.session.add(time)\n db.session.commit()\n return redirect(url_for('mechanicDashboard'))\n return render_template('Mechanic_AvaialablityForm.html', title='Add availability', form=form)\n\n\n@app.route('/ScheduleAppointment', methods=['GET', 'POST'])\ndef Schedule():\n form = ScheduleAppointment()\n availabilities = Availability.query.all()\n mechanics = User.query.filter_by(role=\"Mechanic\")\n if form.validate_on_submit():\n appointments = Schedules.query.all()\n for x in appointments:\n\n if x.appointment_date == form.date.data and x.appointment_time == form.start_time.data and \\\n x.mechanic == form.mechanic.data:\n return redirect(url_for('Schedule'))\n for i in availabilities:\n if i.user == form.mechanic.data and i.date == form.date.data and (form.start_time.data < i.start_time or\n form.start_time.data > i.end_time):\n return redirect(url_for('Schedule'))\n for i in availabilities:\n if i.user == form.mechanic.data and i.date == form.date.data and (\n form.start_time.data < i.start_time or form.start_time.data > i.end_time):\n return redirect(url_for('Schedule'))\n meeting = Schedules(user=current_user.user, mechanic=form.mechanic.data, appointment_date=form.date.data,\n appointment_time=form.start_time.data, vehicle=form.vehicle.data,\n appointment_type=form.appointment_type.data)\n db.session.add(meeting)\n db.session.commit()\n return redirect(url_for('index'))\n\n return render_template('ScheduleAppointment.html', title='Schedule Appointment', form=form, mechanics=mechanics)\n\n\n@app.route('/EditAppointment', methods=['GET', 'POST'])\ndef editAppointment():\n form = EditAppointmentForm()\n if form.validate_on_submit():\n appointments = Schedules.query.all()\n for x in appointments:\n if x.appointment_date == form.date.data and x.appointment_time == form.start_time.data:\n return render_template('EditApt.html', title='Edit Appointment', form=form)\n elif current_user.user == x.user and form.date.data == x.appointment_date:\n x.appointment_time = form.start_time.data\n db.session.commit()\n return redirect(url_for('index'))\n\n return render_template('EditApt.html', title='Edit Appointment', form=form)\n\n\n@app.route('/DeleteAppointment', methods=['GET', 'POST'])\ndef deleteAppointment():\n form = DeleteAppointmentForm()\n if form.validate_on_submit():\n appointments = Schedules.query.all()\n for x in appointments:\n if x.appointment_date == form.date.data and x.appointment_time == form.start_time.data and x.mechanic == form.mechanic.data and x.vehicle == form.car.data:\n db.session.delete(x)\n db.session.commit()\n return redirect(url_for('index'))\n\n return render_template('delete_appointment.html', title='Edit Appointment', form=form)\n\n\n@app.route('/DisplayAvailability', methods=['GET', 'POST'])\ndef DisplayAvailabilities():\n availabilities = Availability.query.all()\n appointments = Schedules.query.all()\n return render_template('DisplayMechanicAvailability.html',\n availabilities=availabilities, appointments=appointments)\n\n\n@app.route('/oil_change', methods=['GET', 'POST'])\n@login_required\ndef OilChange():\n form = OilChangeForm()\n cars = Car.query.all()\n if form.validate_on_submit(): # if submit button is pressed\n for x in cars:\n if x.user == current_user.user and x.model == form.car.data:\n difference = form.update_miles.data - x.mileage\n x.miles_until_oil_change = 5000 - difference\n x.mileage = form.update_miles.data\n db.session.commit()\n print(difference)\n if difference < 5000:\n return redirect(url_for('index'))\n elif difference >= 5000:\n msg = Message('Oil Change Reminder Notification', recipients=[current_user.email])\n msg.body = 'Hi, Its time for you to schedule your next car maintenance appointment as your oil needs to ' \\\n 'be changed! '\n msg.html = 'This is a Reminder Notification '\n mail.send(msg)\n return redirect(url_for('Schedule'))\n\n return render_template('oil_change.html', title='Oil Change', form=form, cars=cars)\n\n\n@app.route('/mechanicDashboard')\n@login_required\ndef mechanicDashboard():\n appointments = Schedules.query.all()\n return render_template('mechanicDashboard.html', title='Mechanic Dashboard', appointments=appointments)\n\n\n@app.route('/review_appointment', methods=['GET', 'POST'])\n@login_required\ndef rate_mechanic():\n form = ReviewMechanic()\n all_reviews = Reviews.query.order_by(Reviews.mechanic)\n all_averages = Mechanic_Ratings.query.all()\n if form.validate_on_submit():\n total = 0\n total_reviews = []\n review_made = Reviews(mechanic=form.mechanic.data, comment=form.comments.data, rating=form.rating.data,\n user=current_user.user)\n db.session.add(review_made)\n\n for x in all_reviews:\n if x.mechanic == form.mechanic.data:\n total_reviews += [x.rating]\n\n for x in total_reviews:\n total += x\n avg = total / len(total_reviews)\n print(avg)\n\n if Mechanic_Ratings.query.first() is None:\n mechanic_reviews = Mechanic_Ratings(mechanic=form.mechanic.data, average=round(avg, 2))\n db.session.add(mechanic_reviews)\n else:\n for j in all_averages:\n if Mechanic_Ratings.query.filter_by(mechanic=form.mechanic.data) is None:\n if j.mechanic == form.mechanic.data:\n print(\"2nd if\")\n j.average = round(avg, 2)\n else:\n print(\"else\")\n mechanic_reviews = Mechanic_Ratings(mechanic=form.mechanic.data, average=round(avg, 2))\n db.session.add(mechanic_reviews)\n db.session.commit()\n\n return redirect(url_for('view_rating'))\n return render_template('MechanicRating.html', title='Review Mechanic', form=form)\n\n\n@app.route('/view_reviews')\n@login_required\ndef view_rating():\n mechanics_ratings = Mechanic_Ratings.query.all()\n all_reviews = Reviews.query.all()\n users = User.query.filter_by(role='Mechanic')\n return render_template('DisplayRatings.html', title='Mechanic Reviews', mechanics_ratings=mechanics_ratings,\n all_reviews=all_reviews, users=users)\n\n\n@app.route('/suggest_recommendations', methods=['GET', 'POST'])\n@login_required\ndef suggest_recommendations():\n form = Suggestions()\n if form.validate_on_submit():\n recommendations_suggested = Recommendations(user=form.user.data, Tire_rotations=form.Tire_rotations.data,\n Registration_update=form.Registration_update.data,\n Change_break=form.Change_break.data, Car_Wash=form.Car_Wash.data,\n Oil_change=form.Oil_change.data)\n db.session.add(recommendations_suggested)\n db.session.commit()\n\n return redirect(url_for('mechanicDashboard'))\n\n return render_template('Suggestions.html', title='Recommendations', form=form)\n\n\n@app.route('/suggested_recommendations', methods=['GET', 'POST'])\n@login_required\ndef recommendations():\n recommendations_made = Recommendations.query.all()\n return render_template('Suggestions_Proposed.html', title='Recommendations Made',\n recommendations_made=recommendations_made)\n","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":13942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"243631679","text":"import boto3\r\nimport requests\r\nimport argparse\r\n\r\namplify_client = boto3.client('amplify')\r\n\r\ndef list_apps(app_name):\r\n apps = amplify_client.list_apps()['apps']\r\n for app in apps:\r\n if app['name'] == app_name:\r\n return app['appId']\r\n \r\n return None\r\n\r\ndef create_app(app_name):\r\n resp = amplify_client.create_app(name=app_name)\r\n return resp['app']['appId']\r\n\r\ndef create_branch(app_id, branch_name):\r\n try:\r\n resp = amplify_client.get_branch(appId=app_id, branchName=branch_name)\r\n except:\r\n resp = amplify_client.create_branch(appId=app_id, branchName=branch_name)\r\n\r\ndef create_deployment(app_id, branch_name):\r\n resp = amplify_client.create_deployment(appId=app_id, branchName=branch_name)\r\n return resp['jobId'],resp['zipUploadUrl']\r\n\r\ndef upload_payload(upload_url, deployment_loc):\r\n f = open(deployment_loc, 'rb')\r\n headers = {\"Content-Type\": \"application/zip\"}\r\n resp = requests.put(upload_url, data=f.read(), headers=headers)\r\n print(resp)\r\n\r\ndef start_deployment(app_id, branch_name, job_id):\r\n resp = amplify_client.start_deployment(appId=app_id, branchName=branch_name, jobId=job_id)\r\n return resp['jobSummary']['status']\r\n\r\n\r\n \r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(description='AWS Amplify App Build Script')\r\n parser.add_argument('--app-name', help='Amplify App Name', default='amplify-deploy', dest='app_name')\r\n parser.add_argument('--branch-name', help='Amplify Branch Name', default='main', dest='branch_name')\r\n parser.add_argument('--dep-loc', help='Deployment package location', default='deployment.zip', dest='dep_loc')\r\n args = parser.parse_args()\r\n\r\n app_id = list_apps(app_name=args.app_name)\r\n if app_id is None:\r\n app_id = create_app(app_name=args.app_name)\r\n \r\n \r\n \r\n create_branch(app_id=app_id, branch_name=args.branch_name)\r\n job_id, upload_url = create_deployment(app_id=app_id, branch_name=args.branch_name)\r\n\r\n upload_payload(upload_url=upload_url, deployment_loc=args.dep_loc)\r\n start_deployment(app_id=app_id, branch_name=args.branch_name, job_id=job_id)\r\n \r\n \r\n","sub_path":"amplify-build.py","file_name":"amplify-build.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"505674279","text":"#!/usr/bin/env python3 \nimport cgitb , cgi\nimport mysql.connector\nimport base64\nimport common\ncgitb.enable()\n\nform = cgi.FieldStorage()\nname=''\ndescription=''\nprice=0\nuser_id=common.getUserIDCookie()\nimageEncode=''\n\nif \"name\" in form:\n name = form[\"name\"].value\nif \"description\" in form:\n description = form[\"description\"].value\nif \"price\" in form:\n price = form[\"price\"].value\nif \"image\" in form:\n image = form[\"image\"].value\n imageEncode = base64.b64encode(image)\n \ncommon.printHeader()\n\ndef sellResult(name, description, price, image, user_id):\n \n #insert into products\n insert_sql = 'insert into products (name, description, price, image) values (%s, %s, %s, %s)'\n cnx = common.openDatabaseConnection()\n cursorb = cnx.cursor()\n cursorb.execute(insert_sql, (name, description, price, image))\n cnx.commit()\n cursorb.close()\n \n #insert into sells \n # LAST_INSERT_ID function for a specific client is the value generated by that client only. \n # This ensures that each client can obtain its own unique ID.\n last_insert_sql = 'SELECT LAST_INSERT_ID()'\n cursorb = cnx.cursor()\n cursorb.execute(last_insert_sql)\n row = cursorb.fetchone()\n product_id = row[0]\n cursorb.close()\n \n insert_sql = 'insert into sells (product_id, user_id) values (%s, %s)'\n cnx = common.openDatabaseConnection()\n cursorb = cnx.cursor()\n cursorb.execute(insert_sql, (product_id, user_id))\n cnx.commit()\n cursorb.close()\n \n print('Thank you for selling your product.')\n print(\"\")\n common.closeDatabaseConnection(cnx)\n\n\nsellResult(name, description, price, imageEncode, user_id)\n \ncommon.printFooter()\n ","sub_path":"cgi-bin/sellresult.py","file_name":"sellresult.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"606166138","text":"from harris_response import *\nimport skimage.transform as skt\n\n\nclass Stitcher(object):\n\n def __init__(self, image_1, image_2):\n\n self.images = [image_1, image_2]\n\n def find_keypoints(self, image, n_keypoints):\n\n \"\"\"\n Step 1: This method locates features that are \"good\" for matching. To do this we will implement the Harris\n corner detector\n \"\"\"\n\n filter_shape = (5, 5)\n\n # Compute smoothed harris response\n out = convolve(compute_harris_response(image, filter_shape),\n Filter.make_gauss(filter_shape, 2)) # Smooth results\n\n # Find some good features to match\n # form: [u, v]\n x, y = anms_fast(h=out, n=n_keypoints)\n\n # Return the locations\n # form: [u, v]\n return x, y\n\n def generate_descriptors(self, img, l=21):\n \"\"\"\n Step 2: After identifying relevant keypoints, we need to come up with a quantitative description of the\n neighborhood of that keypoint, so that we can match it to keypoints in other images.\n \"\"\"\n u, v = self.find_keypoints(img, 100)\n\n ofs = l // 2\n\n d_out = []\n u_out = []\n v_out = []\n\n m = len(img)\n n = len(img[0])\n\n # check for u and v to be same dimensions\n for i in range(len(u)):\n\n c_x = v[i]\n c_y = u[i]\n\n # If we cannot get a description for key point, throw it out\n if c_x + ofs > m or c_x - ofs < 0 or c_y + ofs > n or c_y - ofs < 0:\n continue\n\n sub = img[v[i] - ofs: v[i] + ofs + 1, u[i] - ofs: u[i] + ofs + 1]\n if sub.shape[0] == l and sub.shape[1] == l:\n u_out.append(u[i])\n v_out.append(v[i])\n d_out.append(sub)\n\n return np.stack(d_out), np.asarray(u_out, dtype=int), np.asarray(v_out, dtype=int)\n\n def D_hat(self, d):\n return (d - d.mean()) / np.std(d)\n\n def error(self, d1, d2):\n return np.sum((d1 - d2) ** 2)\n\n def match_keypoints(self, r=0.7):\n \"\"\"\n Step 3: Compare keypoint descriptions between images, identify potential matches, and filter likely\n mismatches\n \"\"\"\n\n d1, u1, v1 = self.generate_descriptors(self.images[0], 0)\n d2, u2, v2 = self.generate_descriptors(self.images[1], 1)\n\n match_out = []\n value_list = []\n for i, D1 in enumerate(d1):\n\n smallest = np.inf\n index2_smallest = 0\n smallest2 = np.inf\n index2_smallest2 = 0\n D1_hat = (D1 - np.mean(D1)) / np.std(D1)\n value = 0\n value2 = 0\n\n for j, D2 in enumerate(d2):\n D2_hat = (D2 - np.mean(D2)) / np.std(D2)\n E = np.sum(np.square(D1_hat - D2_hat))\n if E < smallest: # best match\n smallest = E\n value = E\n index2_smallest = j\n np.delete(d1, index2_smallest, 0)\n np.delete(d2, index2_smallest, 0)\n\n for j, D2 in enumerate(d2):\n\n D2_hat = (D2 - np.mean(D2)) / np.std(D2)\n E = np.sum(np.square(D1_hat - D2_hat))\n\n if E < smallest2: # the second best match\n smallest2 = E\n value2 = E\n index2_smallest = j\n\n if value < (r * value2):\n match_out.append((u1[i], v1[i], u2[index2_smallest], v2[index2_smallest]))\n value_list.append(value)\n\n return np.asarray(match_out)\n\n def find_homography(self, uv, uv2):\n \"\"\"\n Step 4: Find a linear transformation (of various complexities) that maps pixels from the second image to\n pixels in the first image\n \"\"\"\n\n if uv.shape != uv2.shape:\n raise ValueError(\"X and X_prime must have matching shapes\")\n if uv.shape[0] < 4:\n raise ValueError(\"Not enough points\")\n\n # matches = np.column_stack(uv, uv2)\n\n A = np.zeros((2 * len(uv), 9))\n\n for i in range(len(uv)):\n A[2 * i, :] = [0, 0, 0, -uv[i, 0], -uv[i, 1], -1, uv2[i, 1] * uv[i, 0], uv2[i, 1] * uv[i, 1], uv2[i, 1]]\n A[2 * i + 1, :] = [uv[i, 0], uv[i, 1], 1, 0, 0, 0, -uv2[i, 0] * uv[i, 0], -uv2[i, 0] * uv[i, 1], -uv2[i, 0]]\n\n # print(A)\n U, Sigma, Vt = np.linalg.svd(A)\n\n H = Vt[-1, :].reshape((3, 3))\n H /= H[2, 2]\n\n return H\n\n def RANSAC(self, number_of_iterations=10, n=10, r=3, d=8):\n\n H_best = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n num_inliers = 0\n\n matches = self.match_keypoints() # matches should be of the form [u1, v1, u2, v2]\n\n for i in range(number_of_iterations):\n # 1. Select a random sample of length n from the matches\n np.random.shuffle(matches)\n sub = matches[0:n, :]\n test = matches[n:, :]\n\n # 2. Compute a homography based on these points using the methods given above\n H = self.find_homography(sub[:, 0:2], sub[:, 2:])\n\n # 3. Apply this homography to the remaining points that were not randomly selected\n test_p = test[:, 0:2]\n test_p = np.column_stack((test_p, np.ones(len(test_p))))\n uv_p = (H @ test_p.T).T\n test_u = uv_p[:, 0] / uv_p[:, 2]\n test_v = uv_p[:, 1] / uv_p[:, 2]\n\n # 4. Compute the residual between observed and predicted feature locations\n R = np.zeros_like(test_u)\n for i in range(len(test_p)):\n R[i] = np.sqrt((test_u[i] - test[i, 2]) ** 2 + (test_v[i] - test[i, 3]) ** 2)\n\n # 5. Flag predictions that lie within a predefined distance r from observations as inliers\n inl = np.zeros_like(R)\n for i in range(len(inl)):\n if R[i] < r:\n inl[i] = 1\n else:\n inl[i] = 0\n num_inl = np.sum(inl)\n\n # 6. If number of inliers is greater than the previous best\n # and greater than a minimum number of inliers d,\n # 7. update H_best\n # 8. update list_of_inliers\n if num_inl > num_inliers:\n if num_inl > d:\n H_best = H\n num_inliers = num_inl\n\n return H_best, num_inliers\n\n def stitch(self):\n \"\"\"\n Step 5: Transform second image into local coordinate system of first image, and (perhaps) perform blending\n to avoid obvious seams between images.\n \"\"\"\n H_best = self.RANSAC(10, 10, 3, 8)\n\n im1 = self.images[0]\n im2 = self.images[1]\n\n transform = skt.ProjectiveTransform(H_best)\n im_2_warped = skt.warp(im2, transform, output_shape=(im1.shape[0], im1.shape[1] + (int(im1.shape[1] * 0.4))))\n\n im1t = np.zeros_like(im_2_warped)\n\n for v in range(im1.shape[0]):\n for u in range(im1.shape[1]):\n if im1[v, u] != 0:\n im1t[v, u] = im1[v, u]\n\n img_out = np.zeros_like(im_2_warped)\n\n for v in range(img_out.shape[0]):\n for u in range(img_out.shape[1]):\n if im1t[v, u] == 0 and im_2_warped[v, u] == 0:\n img_out[v, u] = 0\n\n elif im1t[v, u] != 0 and im_2_warped[v, u] == 0:\n img_out[v, u] = im1[v, u]\n elif im1t[v, u] == 0. and im_2_warped[v, u] != 0:\n img_out[v, u] = im_2_warped[v, u]\n else:\n img_out[v, u] = (im_2_warped[v, u] + im1[v, u]) / 2\n\n return img_out\n","sub_path":"Stitcher.py","file_name":"Stitcher.py","file_ext":"py","file_size_in_byte":7662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"269112487","text":"from chocs import HttpRequest, HttpResponse, HttpStatus, HttpMethod\nfrom chocs.message import JsonBody\nfrom chocs.middleware import MiddlewareHandler\n\n\ndef check_json_request(request: HttpRequest, next: MiddlewareHandler) -> HttpResponse:\n if request.method in (\n HttpMethod.POST,\n HttpMethod.PUT,\n HttpMethod.PATCH,\n ) and not isinstance(request.parsed_body, JsonBody):\n return HttpResponse(\n HttpStatus.BAD_REQUEST, \"Request must be valid json request.\"\n )\n\n return next(request)\n\n\n__all__ = [\"check_json_request\"]\n","sub_path":"chinook/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"133261257","text":"import boto3\nfrom botocore.exceptions import ClientError\nimport logging\n\n\nclass Switcher(object):\n def indirect(self, state):\n method = getattr(self, state, lambda: None)\n return method()\n\n def start(self):\n return 'self.client.start_instances(InstanceIds=self.ids_list)'\n\n def stop(self):\n return 'self.client.stop_instances(InstanceIds=self.ids_list)'\n\n def reboot(self):\n return 'self.client.reboot_instances(InstanceIds=self.ids_list)'\n\n def terminate(self):\n return 'self.client.terminate_instances(InstanceIds=self.ids_list)'\n\n\nclass EC2StatusChanger:\n \"\"\"\n This class is for changing statuses of ec2 instanses in regions.\n It takes parameters\n 'region','current status', 'new status'\n \"\"\"\n def __init__(self, region, current_status, new_status):\n self.region = region\n self.current_status = current_status\n self.new_status = new_status\n self.client = boto3.client('ec2', region_name=self.region)\n self.ids_list = []\n self.change_status()\n\n def get_instances_id(self):\n my_filter = [\n {\n 'Name': 'instance-state-name',\n 'Values': [\n self.current_status,\n ]\n },\n ]\n try:\n response = self.client.describe_instances(Filters=my_filter)\n except ClientError as e:\n logging.error(e)\n for instance in response['Reservations']:\n for keys in instance['Instances']:\n self.ids_list.append(keys['InstanceId'])\n\n def change_status(self):\n self.get_instances_id()\n state_switcher = Switcher()\n command = state_switcher.indirect(self.new_status)\n if not command:\n raise ValueError('Invalid State')\n print(command)\n try:\n eval(command)\n except ClientError as e:\n logging.error(e)\n\n\nif __name__ == \"__main__\":\n EC2StatusChanger('us-east-2', 'stopped', 'terminate')\n\n","sub_path":"python/module8/ec2_status.py","file_name":"ec2_status.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"110118678","text":"def make_sandwich(order_list):\n print(\"샌드위치를 만들겠습니다.\")\n for i in order_list:\n print(\"%s 추가합니다\"%i)\n print(\"\\n여기 주문하신 샌드위치 만들었습니다. 맛있게 드세요.\")\n\n\ndef input_ingredient(message):\n if message == 1:\n order_list = []\n while True:\n order = input(\"안녕하세요. 원하시는 재료를 입력하세요: \")\n if order == \"종료\":\n print()\n break\n else:\n order_list.append(order)\n make_sandwich(order_list)\n\n\nwait_message = int(input(\"안녕하세요. 저희 가게에 방문해 주세서 감사합니다.\\n1. 주문\\n2. 종료\\n입력 : \"))\ninput_ingredient(wait_message)","sub_path":"01_jumptopy/Jump_to_Python/chap04/20180509(수)/sandwich.py","file_name":"sandwich.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"552655807","text":"#!/usr/bin/env python\n\nimport subprocess\nimport rospy\nfrom std_msgs.msg import String\nimport Tkinter as tk\n\n\n\ndef interface_graphique():\n\troot = tk.Tk()\n\tcanvas1 = tk.Canvas(root, width = 400, height = 300)\n\tcanvas1.pack()\n\tresultatTb = tk.Entry (root)\n\tcanvas1.create_window(200, 140, window=resultatTb)\n\tdef lancer_launch():\n\t\tsubprocess.check_call('roslaunch panda_moveit_config demo.launch rviz_tutorial:=true', shell=True)\n\tbutton1 = tk.Button(text='lancer fichier launch 1', command=lancer_launch)\n\tcanvas1.create_window(200, 180, window=button1)\n\tdef lancer_commande():\n\t\tsubprocess.check_call('rosrun moveit_tutorials move_group_python_interface_tutorial.py', shell=True)\n\tbutton2 = tk.Button(text='lancer commande robot', command=lancer_commande)\n\tcanvas1.create_window(200, 220, window=button2)\n\troot.mainloop()\n\n\t\n\nrospy.init_node(\"interface_graphique\")\n\ninterface_graphique()\n#pub = rospy.Publisher(\"T_Ordre_interface_graphique\", String, queue_size=1)\n#sub = rospy.Subscriber(\"T_reception_interface_graphique\", String, interface_graphique)\nrospy.spin()\n","sub_path":"src/EsquisseIG.py","file_name":"EsquisseIG.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"107756085","text":"#!/usr/bin/python3\n\"\"\" Place Module for HBNB project \"\"\"\nfrom models.base_model import BaseModel, Base\nfrom sqlalchemy import Column, Integer, String, ForeignKey, Float, Table\nfrom sqlalchemy.orm import relationship, backref\nimport os\nimport models\n\n\nplace_amenity = Table('place_amenity', Base.metadata,\n Column('place_id', String(60),\n ForeignKey('places.id'),\n primary_key=True, nullable=False),\n Column('amenity_id', String(60),\n ForeignKey('amenities.id'),\n primary_key=True, nullable=False))\n\n\nclass Place(BaseModel, Base):\n \"\"\" A place to stay \"\"\"\n __tablename__ = 'places'\n if os.getenv('HBNB_TYPE_STORAGE') == 'db':\n city_id = Column(String(60), ForeignKey('cities.id'), nullable=False)\n user_id = Column(String(60), ForeignKey('users.id'), nullable=False)\n name = Column(String(128), nullable=False)\n description = Column(String(1024), nullable=True)\n number_rooms = Column(Integer, nullable=False, default=0)\n number_bathrooms = Column(Integer, nullable=False, default=0)\n max_guest = Column(Integer, nullable=False, default=0)\n price_by_night = Column(Integer, nullable=False, default=0)\n latitude = Column(Float, nullable=True)\n longitude = Column(Float, nullable=True)\n reviews = relationship('Review', cascade='all, delete',\n backref='place')\n amenities = relationship('Amenity',\n secondary='place_amenity',\n viewonly=False)\n else:\n city_id = \"\"\n user_id = \"\"\n name = \"\"\n description = \"\"\n number_rooms = 0\n number_bathrooms = 0\n max_guest = 0\n price_by_night = 0\n latitude = 0.0\n longitude = 0.0\n amenity_ids = []\n\n @property\n def reviews(self):\n '''\n returns the list of Review instances with place_id equals to\n the current Place.id => It will be the FileStorage relationship\n between Place and Review\n '''\n reviews_return = []\n for k, v in models.storage.all().items():\n if v.___class__.__name__ == 'Review':\n if v.place_id == self.id:\n reviews_return.append(v)\n return reviews_return\n\n @property\n def amenities(self):\n '''\n Returns the list of Amenity instances based\n on the attribute amenity_ids that contains all\n Amenity.id linked to the Place\n '''\n reviews_return = []\n for k, v in models.storage.all().items():\n if v.___class__.__name__ == 'Amenity':\n if v.place_id == self.id:\n reviews_return.append(v)\n return reviews_return\n\n @amenities.setter\n def amenities(self, obj=None):\n if isinstance(obj, Amenity):\n self.amenity_ids.append(obj.id)\n","sub_path":"models/place.py","file_name":"place.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"359078613","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nclass Visualizer:\n def __init__(self, xlim=30):\n self.fig = plt.figure()\n self.axs = None\n self.plots = None\n self.xs = None\n self.ys = None\n self.last_x = -1\n self.xlim=xlim\n\n self.ymin=0\n self.ymax=0\n\n self.m = -1\n\n def getFigure(self):\n return self.fig\n\n def initDraw(self, m):\n self.xs = ( [], [] )\t# xdata, pred_xdata\n self.ys = [ ([], []) for _ in xrange(m) ] # ydata, pred_ydata\n self.axs = []\n self.plots = []\n\n # create axes and plots\n for i in xrange(m):\n ax = self.fig.add_subplot(m,1,i+1)\n plot_y = ax.plot(self.xs[0], self.ys[i][0], \"b.-\")[0]\n plot_y_pred = ax.plot(self.xs[1], self.ys[i][1], \"r.-\")[0]\n self.axs.append(ax)\n self.plots.append([plot_y, plot_y_pred])\n\n self.m = m\n plt.draw()\n\n def append(self, y, y_pred=None):\n if len(y) != self.m:\n self.initDraw(len(y))\n\n x = self.last_x + 1\n xdata, x_preddata = self.xs\n xdata.append(x)\n if y_pred is not None:\n x_preddata.append(x)\n self.last_x = x\n\n for i in xrange(len(self.axs)):\n ydata, pred_ydata = self.ys[i]\n ydata.append(y[i])\n self.ymin = min(self.ymin, y[i])\n self.ymax = max(self.ymax, y[i])\n if y_pred is not None:\n pred_ydata.append(y_pred[i])\n self.ymin = min(self.ymin, y_pred[i])\n self.ymax = max(self.ymax, y_pred[i])\n\n self.update()\n\n def update(self):\n for i in xrange(len(self.axs)):\n self.plots[i][0].set_data(self.xs[0], self.ys[i][0])\n self.plots[i][1].set_data(self.xs[1], self.ys[i][1])\n self.axs[i].set_xlim(self.last_x-self.xlim, self.last_x)\n self.axs[i].set_ylim(self.ymin, self.ymax)\n self.axs[i].autoscale_view(scalex=False,scaley=True)\n\n plt.draw()","sub_path":"fully_connected/realtime/visualizer.py","file_name":"visualizer.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"176536731","text":"from movement import decryptScheduleFile\nfrom preliminaries import getListOfSectionsCompleted\nfrom classes.pair import Pair\nfrom classes.section import Section\nimport Formigueiro as Formigueiro\nimport random\nimport operator\nimport pandas as pd\nimport time\n# import ray\n\n### TAKES IN SCHEDULE_FILE ###\n### ASSIGN PAIRS A PAIR ID ###\n### TRY SAME SCHEDULE WITH DIFFERENT PAIR NUM-ID Mappings ###\n\n# ray.init()\n\n\n# @ray.remote\n# def f(x):\n# return x * x\n\n\n# futures = [f.remote(i) for i in range(4)]\n# print(ray.get(futures))\n\n\nclass BRIDGEInstance():\n ##### FOR NOW ----> IT WILL BE ONLY ONE SECTION #####\n def __init__(self, section, prev_meetings_matrix, listScheduleRounds, refMatrix):\n self.numRounds = len(listScheduleRounds.rounds)\n self.numPairs = len(section.pairs)\n self.pairs = section.pairs,\n self.pairNums = section.listPairNums\n self.listScheduleRounds = listScheduleRounds\n self.prev_meetings_matrix = prev_meetings_matrix\n self.refMatrix = refMatrix\n self.fitness_best = self.get_theoretical_best_fitness()\n self.fitness_worst = self.get_theoretical_worst_fitness()\n\n def getPairNumbersSet(self):\n V = set([])\n for num in self.pairNums:\n V.add(num)\n return V\n\n def getIdsToBeAssignedSet(self):\n U = set([])\n for id in range(1, self.numPairs+1):\n U.add(id)\n return U\n\n def getMeetingMatrix(self):\n return self.prev_meetings_matrix\n\n def compute_meeting_factor(self, meeting_matrix):\n meeting_factor = 0\n for pair1 in self.pairNums:\n for pair2 in self.pairNums:\n cell_value = meeting_matrix.at[pair1, pair2] ** 3\n meeting_factor += cell_value\n return meeting_factor\n\n def compute_theoretical_best_meeting_matrix(self, meeting_history_matrix, numRounds):\n theoretical_optimum_matrix = meeting_history_matrix.copy()\n for pair_num in self.pairNums:\n for i in range(0, numRounds):\n column = theoretical_optimum_matrix[[pair_num]].copy()\n column.drop([pair_num], axis=0, inplace=True)\n pair_id_least_meetings = column.idxmin()\n theoretical_optimum_matrix[pair_num][int(\n pair_id_least_meetings)] += 4\n theoretical_optimum_matrix[int(\n pair_id_least_meetings)][pair_num] += 4\n fitness = self.compute_meeting_factor(theoretical_optimum_matrix)\n print(f'\\nTheoretical OPTIMUM Matrix: {fitness/fitness}')\n print(theoretical_optimum_matrix)\n return theoretical_optimum_matrix\n\n def get_theoretical_best_fitness(self):\n fitness = 0\n if(self.numPairs % 2 == 0):\n matrix = self.compute_theoretical_best_meeting_matrix(\n self.prev_meetings_matrix, self.numRounds)\n fitness = self.compute_meeting_factor(matrix)\n else:\n # TODO: Still need to do\n pass\n return fitness\n\n def compute_theoretical_worst_meeting_matrix(self, meeting_history_matrix, numRounds):\n theoretical_worst_matrix = meeting_history_matrix.copy()\n for pair_num in self.pairNums:\n for i in range(0, numRounds):\n column = theoretical_worst_matrix[[pair_num]].copy()\n column.drop([pair_num], axis=0, inplace=True)\n pair_id_least_meetings = column.idxmax()\n theoretical_worst_matrix[pair_num][int(\n pair_id_least_meetings)] += 4\n theoretical_worst_matrix[int(\n pair_id_least_meetings)][pair_num] += 4\n fitness = self.compute_meeting_factor(theoretical_worst_matrix)\n print(f'\\nTheoretical WORST Matrix: {fitness/self.fitness_best}')\n print(theoretical_worst_matrix)\n return theoretical_worst_matrix\n\n def get_theoretical_worst_fitness(self):\n fitness = 0\n if(self.numPairs % 2 == 0):\n matrix = self.compute_theoretical_worst_meeting_matrix(\n self.prev_meetings_matrix, self.numRounds)\n fitness = self.compute_meeting_factor(matrix)\n else:\n # TODO: Still need to do\n pass\n return fitness\n\n def computePairAssignmentCost(self, id, num, rest):\n # ID is in schedule\n # NUM is pair natural number\n # Component is tuple(id, num)\n register = dict(rest)\n # print(f'Register: {register}')\n # print(f'Next Assignment Attempted: ID: {id} to Pair NUM: {num}')\n if len(register) == 0:\n # This has to be the largest value possible\n # Ideal value is 0.01\n return 64\n else:\n cost = 0.01\n # print(f'Checking against register...')\n for assignment in register.items():\n assID = assignment[0]\n assNum = assignment[1]\n # print(f'Existing Assignment: ID: {assID} - NUM: {assNum}')\n if(self.refMatrix[id][assID] != 0):\n # print(f'In Schedule ID: {assID} meets {id}')\n cost += self.prev_meetings_matrix[num][assNum]\n # print(f'Cost of assignment {id} for Pair Num: {num}')\n # print(f'Total Cost of Assignment: ID: {id} -- NUM: {num}')\n # print(f'Cost of this Pair Assignment is: {cost}')\n return cost\n\n # return a fitness value in range(1, 2)\n def compute_fitness(self, x):\n # SOLUTION COMPONENTS IS LIST: [(id, num), (id, num)]\n sample_solution_matrix = self.prev_meetings_matrix.copy()\n register = dict(x)\n for round in self.listScheduleRounds.rounds:\n for meeting in round.getTablePairs():\n # single meeting in schedule file\n pair1num = register[int(meeting[0])]\n pair2num = register[int(meeting[1])]\n sample_solution_matrix[pair1num][pair2num] += 4\n sample_solution_matrix[pair2num][pair1num] += 4\n meeting_factor = self.compute_meeting_factor(sample_solution_matrix)\n # Get overhead\n return meeting_factor / self.fitness_best\n\n\nclass BRIDGEAnt(Formigueiro.ACS_Ant):\n # THIS WILL RECEIVE A BRIDGE INSTANCE --- AN INSTANCE OF THE MEETING MATRIX + WAITING VECTOR (if applicable)\n def __init__(self, instance, **kwargs):\n self.instance = instance\n\n super().__init__(**kwargs)\n\n # OVERRIDE with FITNESS VALUE\n # Compute the generated schedule onto a new meeting matrix\n # Compute the FITNESS VALUE in Respect to the Theoretical Best???\n def getSolutionValue(self):\n # SOLUTION COMPONENTS IS LIST: [(id, num), (id, num)]\n return self.instance.compute_fitness(self.getSolutionComponents())\n\n def getComponentCost(self, component):\n # Component is tuple(id, num)\n return self.instance.computePairAssignmentCost(*component, self.getSolutionComponents())\n\n def constructSolution(self):\n # Set of NUMS\n V = self.instance.getPairNumbersSet()\n U = self.instance.getIdsToBeAssignedSet()\n L = set([])\n P = set([])\n while L != V:\n remaining_ids = [id for id in U - P]\n id = random.choice(remaining_ids)\n P.add(id)\n components = [(id, num) for num in V - L]\n _, num = self.makeDecision(components)\n L.add(num)\n\n\nmeeting_history_file = 'bridge_schedules/data2021_pre_balanced/meeting history april 2021'\npre_schedule_file = 'bridge_schedules/data2021_pre_balanced/48 pairs_(3 sections,no_waiting_table)'\npath_to_schedule = 'bridge_schedules/schedules/mpx-16-8-6-6-0.asc'\n\n\ndef computeTheoreticalNumberingMatrix(section, listOfRounds):\n # Compute a reference matrix\n series_rows = pd.Series(range(1, len(section.pairs)+1))\n series_cols = pd.Series(range(1, len(section.pairs)+1))\n # CREATE DATA-FRAME BASED ON COMBINED MEETINGS\n df = pd.DataFrame(series_rows.apply(\n lambda x: series_cols.apply(lambda y: 0)))\n df.index = series_rows\n df.columns = series_cols\n for round in listOfRounds.rounds:\n for meeting in round.getTablePairs():\n # single meeting in schedule file\n pair1id = int(meeting[0])\n pair2id = int(meeting[1])\n df[pair1id][pair2id] += 4\n df[pair2id][pair1id] += 4\n print('Theoretical Assignment Reference Matrix is:')\n print(df)\n return df\n\n\ndef compute_final_meeting_matrix_from_solution(listRounds, meeting_matrix, assignments):\n # SOLUTION COMPONENTS IS LIST: [(id, num), (id, num)]\n sample_solution_matrix = meeting_matrix.copy()\n register = dict(assignments)\n for round in listRounds.rounds:\n for meeting in round.getTablePairs():\n # single meeting in schedule file\n pair1num = register[int(meeting[0])]\n pair2num = register[int(meeting[1])]\n sample_solution_matrix[pair1num][pair2num] += 4\n sample_solution_matrix[pair2num][pair1num] += 4\n # Get overhead\n return sample_solution_matrix\n\n\ndef getPairByNum(section, num):\n for pair in section.pairs:\n if pair.num == num:\n return pair\n\n\ndef getPairsFromNUM(assignments):\n register = dict(assignments)\n defin = {}\n for ass in register.items():\n pair = getPairByNum(ass[1])\n defin[ass[0]] = (pair.player1, pair.player2)\n return defin\n\n\ndef compute_all_sections():\n listRounds = decryptScheduleFile(path_to_schedule)\n listOfSections = getListOfSectionsCompleted(\n meeting_history_file, pre_schedule_file, False)\n for section in listOfSections.sections:\n prev_meetings_matrix = section.meetings_matrix.copy()\n referenceMatrix = computeTheoreticalNumberingMatrix(\n section, listRounds)\n # GENERATE INSTANCE OF THE PROBLEM\n instance = BRIDGEInstance(\n section, prev_meetings_matrix, listRounds, referenceMatrix)\n obj, components = Formigueiro.Solve(\n antCls=BRIDGEAnt, instance=instance, numIterations=1000, numAnts=22, alpha=1, beta=1)\n section.setBestFitnessReached(obj)\n res = components\n res.sort(key=operator.itemgetter(0))\n section.setAssignments(res)\n print(\n f'THEORETICAL BEST FITNESS: {instance.fitness_best/instance.fitness_best}')\n print(f'Fitness Overhead: {obj}')\n print(\n f'THEORETICAL WORST FITNESS: {instance.fitness_worst/instance.fitness_best}')\n res = components\n res.sort(key=operator.itemgetter(0))\n print(f'\\nThe assignments are: {res}\\n')\n # Show Results\n for section in listOfSections.sections:\n print(f'Section Fitness: {section.best_fitness}')\n print(f'Assignments: {section.assignments}')\n final_matrix = compute_final_meeting_matrix_from_solution(\n listRounds, section.meetings_matrix.copy(), section.assignments)\n print(f'Final Matrix\\n{final_matrix}')\n\n\nstart_time = time.time()\ncompute_all_sections()\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\n# def getPairByNum(num):\n# for pair in section.pairs:\n# if pair.num == num:\n# return pair\n\n\n# def getPairsFromNUM(assignments):\n# register = dict(assignments)\n# defin = {}\n# for ass in register.items():\n# pair = getPairByNum(ass[1])\n# defin[ass[0]] = (pair.player1, pair.player2)\n# return defin\n\n\n# print(\n# f'THEORETICAL BEST FITNESS: {instance.fitness_best/instance.fitness_best}')\n# print(f'Fitness Overhead: {obj}')\n# print(\n# f'THEORETICAL WORST FITNESS: {instance.fitness_worst/instance.fitness_best}')\n\n# res = components\n# res.sort(key=operator.itemgetter(0))\n\n# print(\n# f'\\nThe assignments are: {res}\\n')\n# print(f'PAIRS ARE: {getPairsFromNUM(res)}\\n')\n\n# # print(\n# # f'Num of Pair Numbers to Ids Assignments in Solution is: {len(components)}')\n\n# final_matrix = compute_final_meeting_matrix_from_solution(\n# prev_meetings_matrix, components)\n# print(f'\\nORIGINAL MATRIX\\n{prev_meetings_matrix}')\n# print(f'\\n\\nFINAL MATRIX\\n{final_matrix}')\n","sub_path":"aco_all_sections.py","file_name":"aco_all_sections.py","file_ext":"py","file_size_in_byte":12178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"221901233","text":"\n\nfrom xai.brain.wordbase.nouns._velocity import _VELOCITY\n\n#calss header\nclass _VELOCITIES(_VELOCITY, ):\n\tdef __init__(self,): \n\t\t_VELOCITY.__init__(self)\n\t\tself.name = \"VELOCITIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"velocity\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_velocities.py","file_name":"_velocities.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"639047155","text":"#coding=utf-8\n'''\n动态属性与__slots__\n\n如果程序要限制某个类动态添加属性和方法,则可通过__slots__属性来指定。\n\n__slots__属性的值是一个元组,该元组的所有元素列出了该类的实例允许动态添加的所有属性\n名和方法名。(对于python而言,方法相当于属性值为函数的属性)\n'''\n\n\nfrom types import MethodType\n\n\nclass Dog(object):\n\t__slots__ = ('walk','age','name')\n\tdef __init__(self,name):\n\t\tself.name = name\n\tdef test():\n\t\tprint(\"预先定义的test方法\")\n\ndef walk_func(self,name):\n\tself.name = name\n\tprint(\"%s 正在慢慢走\" % self.name)\n\n\n\nd = Dog('Snoopy')\nd1 = Dog('SK')\n\n\n#d.walk = MethodType(lambda self:print('%s 正在慢慢走' % self.name),d)。 #使用lambda创建一个匿名函数\n\nd.walk = MethodType(walk_func,Dog)\nd.age = 5\nd.walk('kk')\n#d.foo() #AttributeError\n\n\n\n'''\n__slots__ = ('walk','age','name') 表示:\n程序只允许为dog实例添加walk、age、name这三个属性或方法。\n\n因此上面程序中:\nd.walk = MethodType(lambda self:print('%s 正在慢慢走' % self.name),d) 表示:\ndog对象动态添加walk()方法\n\nd.age = 5 表示:\n为dog对象动态添加age属性\n\n但是不能动态添加__slots__以外的属性或者方法\n\n'''","sub_path":"python/python_self_study/crazy_python/chapter6_class_object/p14_2.py","file_name":"p14_2.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"137522539","text":"# coding: utf-8\nfrom __future__ import unicode_literals, division, absolute_import, print_function\n\nimport unittest\nimport sys\nimport os\nimport re\n\nfrom oscrypto import tls, errors\nfrom asn1crypto import x509\n\nfrom .unittest_data import data_decorator, data\nfrom ._unittest_compat import patch\n\npatch()\n\nif sys.version_info < (3,):\n str_cls = unicode # noqa\n byte_cls = str\nelse:\n str_cls = str\n byte_cls = bytes\n\n\nxp = sys.platform == 'win32' and sys.getwindowsversion()[0] < 6\n\ntests_root = os.path.dirname(__file__)\nfixtures_dir = os.path.join(tests_root, 'fixtures')\n\ndigicert_ca_path = os.path.join(fixtures_dir, 'digicert_ca.crt')\nbadtls_ca_path = os.path.join(fixtures_dir, 'badtls.io_ca.crt')\n\n\n@data_decorator\nclass TLSTests(unittest.TestCase):\n\n @staticmethod\n def tls_hosts():\n return (\n ('google', 'www.google.com', 443),\n ('package_control', 'packagecontrol.io', 443),\n ('howsmyssl', 'www.howsmyssl.com', 443),\n ('dh1024', 'dh1024.badtls.io', 10005),\n ('revoked', 'revoked.grc.com', 443),\n )\n\n @data('tls_hosts', True)\n def tls_connect(self, hostname, port):\n session = None\n if hostname == 'dh1024.badtls.io':\n session = tls.TLSSession(extra_trust_roots=[badtls_ca_path])\n connection = tls.TLSSocket(hostname, port, session=session)\n self.assertEqual(hostname, connection.hostname)\n self.assertIsInstance(connection.hostname, str_cls)\n self.assertIsInstance(connection.cipher_suite, str_cls)\n self.assertIsInstance(connection.certificate, x509.Certificate)\n self.assertLess(10, len(connection.cipher_suite))\n connection.write(b'GET / HTTP/1.1\\r\\nHost: ' + hostname.encode('utf-8') + b'\\r\\n\\r\\n')\n html = connection.read_until(re.compile(b'', re.I))\n self.assertNotEqual(None, re.search(b'', html, re.I))\n\n def test_tls_error_http(self):\n with self.assertRaisesRegexp(errors.TLSError, 'server responded using HTTP'):\n tls.TLSSocket('www.google.com', 80)\n\n def test_tls_error_ftp(self):\n with self.assertRaisesRegexp(errors.TLSError, 'remote end closed the connection|server responded using FTP'):\n tls.TLSSocket('ftp.debian.org', 21)\n\n def test_tls_error_missing_issuer(self):\n expected = 'certificate issuer not found in trusted root certificate store'\n with self.assertRaisesRegexp(errors.TLSVerificationError, expected):\n tls.TLSSocket('domain-match.badtls.io', 10000)\n\n def test_tls_error_domain_mismatch(self):\n session = tls.TLSSession(extra_trust_roots=[badtls_ca_path])\n with self.assertRaisesRegexp(errors.TLSVerificationError, 'does not match'):\n tls.TLSSocket('domain-mismatch.badtls.io', 11002, session=session)\n\n def test_tls_error_san_mismatch(self):\n session = tls.TLSSession(extra_trust_roots=[badtls_ca_path])\n with self.assertRaisesRegexp(errors.TLSVerificationError, 'does not match'):\n tls.TLSSocket('san-mismatch.badtls.io', 11003, session=session)\n\n def test_tls_wildcard_success(self):\n session = tls.TLSSession(extra_trust_roots=[badtls_ca_path])\n tls.TLSSocket('wildcard-match.badtls.io', 10001, session=session)\n\n def test_tls_error_not_yet_valid(self):\n session = tls.TLSSession(extra_trust_roots=[badtls_ca_path])\n with self.assertRaisesRegexp(errors.TLSVerificationError, 'not valid until'):\n tls.TLSSocket('future.badtls.io', 11001, session=session)\n\n def test_tls_error_expired_2(self):\n session = tls.TLSSession(extra_trust_roots=[badtls_ca_path])\n # This test allows past or future since cert is 1963, which some systems\n # will intepret as 2063\n with self.assertRaisesRegexp(errors.TLSVerificationError, 'certificate expired|not valid until'):\n tls.TLSSocket('expired-1963.badtls.io', 11000, session=session)\n\n def test_tls_error_client_cert_required(self):\n session = tls.TLSSession(extra_trust_roots=[badtls_ca_path])\n with self.assertRaisesRegexp(errors.TLSError, 'client authentication'):\n tls.TLSSocket('required-auth.badtls.io', 10003, session=session)\n\n def test_tls_error_handshake_error_3(self):\n session = tls.TLSSession(extra_trust_roots=[badtls_ca_path])\n with self.assertRaisesRegexp(errors.TLSError, 'weak certificate signature algorithm'):\n tls.TLSSocket('weak-sig.badtls.io', 11004, session=session)\n\n def test_tls_error_non_web(self):\n session = tls.TLSSession(extra_trust_roots=[badtls_ca_path])\n with self.assertRaisesRegexp(errors.TLSVerificationError, 'verification failed'):\n tls.TLSSocket('bad-key-usage.badtls.io', 11005, session=session)\n\n def test_tls_error_wildcard_mismatch(self):\n session = tls.TLSSession(extra_trust_roots=[badtls_ca_path])\n with self.assertRaisesRegexp(errors.TLSVerificationError, 'does not match'):\n tls.TLSSocket('wildcard.mismatch.badtls.io', 11007, session=session)\n\n def test_tls_error_expired(self):\n session = tls.TLSSession(extra_trust_roots=[badtls_ca_path])\n with self.assertRaisesRegexp(errors.TLSVerificationError, 'certificate expired'):\n tls.TLSSocket('expired.badtls.io', 11006, session=session)\n\n def test_tls_error_self_signed(self):\n with self.assertRaisesRegexp(errors.TLSVerificationError, 'self-signed'):\n tls.TLSSocket('self-signed.badssl.com', 443)\n\n def test_tls_error_weak_dh_params(self):\n # badssl.com uses SNI, which Windows XP does not support\n regex = 'weak DH parameters' if not xp else 'self-signed'\n # ideally we would use badtls.io since that does not require SNI, however\n # it is not possible to force a good version of OpenSSL to use such a\n # small value for DH params, and I don't feel like the headache of trying\n # to get an old, staticly-linked socat set up just for this text on XP\n with self.assertRaisesRegexp(errors.TLSError, regex):\n tls.TLSSocket('dh512.badssl.com', 443)\n\n def test_tls_error_handshake_error(self):\n session = tls.TLSSession(extra_trust_roots=[badtls_ca_path])\n with self.assertRaisesRegexp(errors.TLSError, 'TLS handshake failed'):\n tls.TLSSocket('rc4-md5.badtls.io', 11009, session=session)\n\n def test_tls_error_handshake_error_2(self):\n session = tls.TLSSession(extra_trust_roots=[badtls_ca_path])\n with self.assertRaisesRegexp(errors.TLSError, 'TLS handshake failed'):\n tls.TLSSocket('rc4.badtls.io', 11008, session=session)\n\n def test_tls_extra_trust_roots_no_match(self):\n expected = 'certificate issuer not found in trusted root certificate store'\n with self.assertRaisesRegexp(errors.TLSVerificationError, expected):\n session = tls.TLSSession(extra_trust_roots=[digicert_ca_path])\n tls.TLSSocket('domain-match.badtls.io', 10000, session=session)\n\n def test_tls_extra_trust_roots(self):\n session = tls.TLSSession(extra_trust_roots=[badtls_ca_path, digicert_ca_path])\n tls.TLSSocket('domain-match.badtls.io', 10000, session=session)\n","sub_path":"tests/test_tls.py","file_name":"test_tls.py","file_ext":"py","file_size_in_byte":7245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"270723245","text":"import os\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport tqdm\nimport numpy as np\nfrom AFSD.common.anet_dataset import ANET_Dataset, detection_collate\nfrom torch.utils.data import DataLoader\nfrom AFSD.anet.BDNet import BDNet\nfrom AFSD.anet.multisegment_loss import MultiSegmentLoss\nfrom AFSD.common.config import config\n\nbatch_size = config['training']['batch_size']\nlearning_rate = config['training']['learning_rate']\nweight_decay = config['training']['weight_decay']\nmax_epoch = config['training']['max_epoch']\nnum_classes = 2\ncheckpoint_path = config['training']['checkpoint_path']\nfocal_loss = config['training']['focal_loss']\nrandom_seed = config['training']['random_seed']\nngpu = config['ngpu']\n\ntrain_state_path = os.path.join(checkpoint_path, 'training')\nif not os.path.exists(train_state_path):\n os.makedirs(train_state_path)\n\nresume = config['training']['resume']\n\n\ndef print_training_info():\n print('batch size: ', batch_size)\n print('learning rate: ', learning_rate)\n print('weight decay: ', weight_decay)\n print('max epoch: ', max_epoch)\n print('checkpoint path: ', checkpoint_path)\n print('loc weight: ', config['training']['lw'])\n print('cls weight: ', config['training']['cw'])\n print('ssl weight: ', config['training']['ssl'])\n print('piou:', config['training']['piou'])\n print('resume: ', resume)\n print('gpu num: ', ngpu)\n\n\ndef set_seed(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n np.random.seed(seed)\n random.seed(seed)\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n\n\nGLOBAL_SEED = 1\n\n\ndef worker_init_fn(worker_id):\n set_seed(GLOBAL_SEED + worker_id)\n\n\ndef get_rng_states():\n states = []\n states.append(random.getstate())\n states.append(np.random.get_state())\n states.append(torch.get_rng_state())\n if torch.cuda.is_available():\n states.append(torch.cuda.get_rng_state())\n return states\n\n\ndef set_rng_state(states):\n random.setstate(states[0])\n np.random.set_state(states[1])\n torch.set_rng_state(states[2])\n if torch.cuda.is_available():\n torch.cuda.set_rng_state(states[3])\n\n\ndef save_model(epoch, model, optimizer):\n torch.save(model.module.state_dict(),\n os.path.join(checkpoint_path, 'checkpoint-{}.ckpt'.format(epoch)))\n torch.save({'optimizer': optimizer.state_dict(),\n 'state': get_rng_states()},\n os.path.join(train_state_path, 'checkpoint_{}.ckpt'.format(epoch)))\n\n\ndef resume_training(resume, model, optimizer):\n start_epoch = 1\n if resume > 0:\n start_epoch += resume\n model_path = os.path.join(checkpoint_path, 'checkpoint-{}.ckpt'.format(resume))\n model.module.load_state_dict(torch.load(model_path))\n train_path = os.path.join(train_state_path, 'checkpoint_{}.ckpt'.format(resume))\n state_dict = torch.load(train_path)\n optimizer.load_state_dict(state_dict['optimizer'])\n set_rng_state(state_dict['state'])\n return start_epoch\n\n\ndef calc_bce_loss(start, end, scores):\n start = torch.tanh(start).mean(-1)\n end = torch.tanh(end).mean(-1)\n loss_start = F.binary_cross_entropy(start.view(-1),\n scores[:, 1].contiguous().view(-1).cuda(),\n reduction='mean')\n loss_end = F.binary_cross_entropy(end.view(-1),\n scores[:, 2].contiguous().view(-1).cuda(),\n reduction='mean')\n return loss_start, loss_end\n\n\ndef forward_one_epoch(net, clips, targets, scores=None, training=True, ssl=True):\n clips = clips.cuda()\n targets = [t.cuda() for t in targets]\n\n if training:\n if ssl:\n output_dict = net.module(clips, proposals=targets, ssl=ssl)\n else:\n output_dict = net(clips, ssl=False)\n else:\n with torch.no_grad():\n output_dict = net(clips)\n\n if ssl:\n anchor, positive, negative = output_dict\n loss_ = []\n weights = [1, 0.1, 0.1]\n for i in range(3):\n loss_.append(nn.TripletMarginLoss()(anchor[i], positive[i], negative[i]) * weights[i])\n trip_loss = torch.stack(loss_).sum(0)\n return trip_loss\n else:\n loss_l, loss_c, loss_prop_l, loss_prop_c, loss_ct = CPD_Loss(\n [output_dict['loc'], output_dict['conf'],\n output_dict['prop_loc'], output_dict['prop_conf'],\n output_dict['center'], output_dict['priors'][0]],\n targets)\n loss_start, loss_end = calc_bce_loss(output_dict['start'], output_dict['end'], scores)\n scores_ = F.interpolate(scores, scale_factor=1.0 / 8)\n loss_start_loc_prop, loss_end_loc_prop = calc_bce_loss(output_dict['start_loc_prop'],\n output_dict['end_loc_prop'],\n scores_)\n loss_start_conf_prop, loss_end_conf_prop = calc_bce_loss(output_dict['start_conf_prop'],\n output_dict['end_conf_prop'],\n scores_)\n loss_start = loss_start + 0.1 * (loss_start_loc_prop + loss_start_conf_prop)\n loss_end = loss_end + 0.1 * (loss_end_loc_prop + loss_end_conf_prop)\n return loss_l, loss_c, loss_prop_l, loss_prop_c, loss_ct, loss_start, loss_end\n\n\ndef run_one_epoch(epoch, net, optimizer, data_loader, epoch_step_num, training=True):\n if training:\n net.train()\n else:\n net.eval()\n\n loss_loc_val = 0\n loss_conf_val = 0\n loss_prop_l_val = 0\n loss_prop_c_val = 0\n loss_ct_val = 0\n loss_start_val = 0\n loss_end_val = 0\n loss_trip_val = 0\n loss_contras_val = 0\n cost_val = 0\n with tqdm.tqdm(data_loader, total=epoch_step_num, ncols=0) as pbar:\n for n_iter, (clips, targets, scores, ssl_clips, ssl_targets, flags) in enumerate(pbar):\n loss_l, loss_c, loss_prop_l, loss_prop_c, loss_ct, loss_start, loss_end = forward_one_epoch(\n net, clips, targets, scores, training=training, ssl=False)\n\n loss_l = loss_l * config['training']['lw']\n loss_c = loss_c * config['training']['cw']\n loss_prop_l = loss_prop_l * config['training']['lw']\n loss_prop_c = loss_prop_c * config['training']['cw']\n loss_ct = loss_ct * config['training']['cw']\n cost = loss_l + loss_c + loss_prop_l + loss_prop_c + loss_ct + loss_start + loss_end\n\n ssl_count = 0\n loss_trip = 0\n for i in range(len(flags)):\n if flags[i] and config['training']['ssl'] > 0:\n loss_trip += forward_one_epoch(net, ssl_clips[i].unsqueeze(0), [ssl_targets[i]], \n training=training, ssl=True) * config['training']['ssl']\n loss_trip_val += loss_trip.cpu().detach().numpy()\n ssl_count += 1\n if ssl_count:\n loss_trip_val /= ssl_count\n loss_trip /= ssl_count\n cost = cost + loss_trip\n\n if training:\n optimizer.zero_grad()\n cost.backward()\n optimizer.step()\n\n loss_loc_val += loss_l.cpu().detach().numpy()\n loss_conf_val += loss_c.cpu().detach().numpy()\n loss_prop_l_val += loss_prop_l.cpu().detach().numpy()\n loss_prop_c_val += loss_prop_c.cpu().detach().numpy()\n loss_ct_val += loss_ct.cpu().detach().numpy()\n loss_start_val += loss_start.cpu().detach().numpy()\n loss_end_val += loss_end.cpu().detach().numpy()\n cost_val += cost.cpu().detach().numpy()\n pbar.set_postfix(loss='{:.5f}'.format(float(cost.cpu().detach().numpy())))\n\n loss_loc_val /= (n_iter + 1)\n loss_conf_val /= (n_iter + 1)\n loss_prop_l_val /= (n_iter + 1)\n loss_prop_c_val /= (n_iter + 1)\n loss_ct_val /= (n_iter + 1)\n loss_start_val /= (n_iter + 1)\n loss_end_val /= (n_iter + 1)\n loss_trip_val /= (n_iter + 1)\n cost_val /= (n_iter + 1)\n\n if training:\n prefix = 'Train'\n save_model(epoch, net, optimizer)\n else:\n prefix = 'Val'\n\n plog = 'Epoch-{} {} Loss: Total - {:.5f}, loc - {:.5f}, conf - {:.5f}, prop_loc - {:.5f}, ' \\\n 'prop_conf - {:.5f}, IoU - {:.5f}, start - {:.5f}, end - {:.5f}'.format(\n i, prefix, cost_val, loss_loc_val, loss_conf_val, loss_prop_l_val, loss_prop_c_val,\n loss_ct_val, loss_start_val, loss_end_val\n )\n plog = plog + ', Triplet - {:.5f}'.format(loss_trip_val)\n print(plog)\n\n\nif __name__ == '__main__':\n print_training_info()\n set_seed(random_seed)\n \"\"\"\n Setup model\n \"\"\"\n net = BDNet(in_channels=config['model']['in_channels'],\n backbone_model=config['model']['backbone_model'])\n net = nn.DataParallel(net, device_ids=list(range(ngpu))).cuda()\n\n \"\"\"\n Setup optimizer\n \"\"\"\n optimizer = torch.optim.Adam([\n {'params': net.module.backbone.parameters(),\n 'lr': learning_rate * 0.1,\n 'weight_decay': weight_decay},\n {'params': net.module.coarse_pyramid_detection.parameters(),\n 'lr': learning_rate,\n 'weight_decay': weight_decay}\n ])\n\n \"\"\"\n Setup loss\n \"\"\"\n piou = config['training']['piou']\n CPD_Loss = MultiSegmentLoss(num_classes, piou, 1.0, use_focal_loss=focal_loss)\n\n \"\"\"\n Setup dataloader\n \"\"\"\n train_dataset = ANET_Dataset(config['dataset']['training']['video_info_path'],\n config['dataset']['training']['video_mp4_path'],\n config['dataset']['training']['clip_length'],\n config['dataset']['training']['crop_size'],\n config['dataset']['training']['clip_stride'],\n channels=config['model']['in_channels'],\n binary_class=True)\n train_data_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True,\n num_workers=8, worker_init_fn=worker_init_fn,\n collate_fn=detection_collate, pin_memory=True, drop_last=True)\n epoch_step_num = len(train_dataset) // batch_size\n\n \"\"\"\n Start training\n \"\"\"\n start_epoch = resume_training(resume, net, optimizer)\n\n for i in range(start_epoch, max_epoch + 1):\n run_one_epoch(i, net, optimizer, train_data_loader, len(train_dataset) // batch_size)","sub_path":"TAL/aicity/ActionDetection-AFSD-master/ActionDetection-AFSD-master/AFSD/anet/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"376306160","text":"#!/usr/bin/env python\nimport math\nfrom names import array\nletters = ['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\nif __name__ == '__main__':\n iterations = 2000\n list_t = {}\n \n for n in range(1,iterations):\n t = (n * (n+1)) // 2\n list_t[t] = True\n\n counter = 0\n\n for item in array:\n score = 0\n for i in range(0, len(item)):\n score += letters.index(item[i]) + 1\n if score in list_t:\n counter += 1\n print(item, score)\n\n print(counter)\n","sub_path":"python/42/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"331756936","text":"'''\nCreated on Apr 21, 2011\n\n@author: gengarkhan\n'''\n\nclass Process:\n '''\n classdocs\n '''\n\n\n def __init__(self, pid, ppid, s, c, sz, vsz, rsz, etime, cmd):\n '''\n Constructor\n '''\n self.pid=pid\n self.ppid=ppid\n self.s=s\n self.c=c\n self.sz=sz\n self.vsz=vsz\n self.rsz=rsz\n self.etime=etime\n self.cmd=cmd\n ","sub_path":"src/Cat/Process.py","file_name":"Process.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"374686751","text":"## Dependency: system\nimport xml.etree.ElementTree as ET\nimport copy, json, re, os\nfrom itertools import cycle\n\n## Dependency: hslog\nfrom hearthstone.enums import *\n\n## Dependency: local\nfrom constant import *\nfrom xmlpy.card_entity import entity\nfrom lookup.cards import id_lookup, id2class, id2dbfID\nfrom dd_deck import dd_deck\nfrom process.summary import summary\nfrom logpy.parse import state, turn_template_dict\nfrom process.match import matcher\n\n# search functions that are passed into cycle_all:\nimport xmlpy.search as search\n\nclass parser():\n\n def __init__(self, xml_addr):\n self.addr = xml_addr\n self.parsing = False\n packet_tree = open(xml_addr, 'rb').read()\n parser = ET.XML(packet_tree)\n self.game = list(parser)[0]\n self.packets = list(self.game)\n \n from logpy.parse import game_summary_0\n game_summary = copy.deepcopy(game_summary_0)\n game_summary.update({\n 'ranked': True,\n 'format': 'standard',\n })\n self.summary = summary(\n game_summary=game_summary,\n entities={},\n log=[],\n ts_dict={},\n )\n\n # get some hero information\n players = [pkt for pkt in self.packets if pkt.tag == 'Player']\n if len(players) != 2:\n raise ValueError(f'{len(self.players)} players found!')\n self.heroes(players)\n # internal reference:\n self._plyID, self._oppID = self.summary.game_summary['player']['playerID'], self.summary.game_summary['opponent']['playerID']\n self.state = state()\n\n def parse(self):\n # get deck info\n self.summary.game_summary['player']['deck'] = self.deck()\n\n # populate entity dict\n self.summary.game_summary['opponent']['deck']['cards'] = []\n self.cycle_all(self.packets, [search.scrape_entity])\n #self.summary.entities.update()\n\n self.parsing = True\n self.state = state() # wipe turn information\n searches = [\n search.find_plays,\n search.find_choices,\n search.find_drawn,\n search.find_deaths,\n search.find_winstate,\n ]\n self.cycle_all(self.packets, searches)\n\n self.summary.revise()\n from process.card_JSON import card_condenser\n self.summary.game_summary = json.loads(json.dumps(self.summary.game_summary, cls = card_condenser))\n\n def save(self):\n json_name = re.sub(r'\\.xml','.json', os.path.basename(self.addr))\n dst = local_folder / 'summaries' / json_name\n from process.card_JSON import card_encoder\n contents = json.dumps(self.summary, indent=4, cls = card_encoder) # add cls\n open(dst, 'w').write(contents)\n\n def label(self, entityID):\n entity = self.summary.iden(entityID)\n if not entity:\n return f''\n controller = {\n self._plyID:'player',\n self._oppID:'opponent',\n }.get(entity.controller,None)\n if not controller:\n raise ValueError(f'Unknown controller for entity {entityID}')\n return f'{controller}\\'s {entity.name}'\n\n def deck(self) -> str:\n deck = dd_deck()\n\n players = [pkt for pkt in self.packets if pkt.tag == 'Player']\n for player in players:\n try: deck_pkt = [pkt for pkt in list(player) if pkt.tag == 'Deck'][0]\n except IndexError: pass\n if 'deck' not in locals(): raise ValueError('No Deck Found!')\n cardIDs = [packet.attrib['id'] for packet in deck_pkt]\n\n cards = []\n for card in list(set(cardIDs)):\n cards.append([id2dbfID[card], cardIDs.count(card)])\n deck.cards = cards\n deck.format = FormatType.FT_STANDARD\n hero = self.summary.game_summary['player']['class']\n from constant import hero_dict\n deck.heroes = [hero_dict.get(hero)]\n\n dct = {\n 'decklist':deck.readable_decklist,\n 'deckstring':deck.as_deckstring,\n 'match':matcher(deck.cards).match,\n 'cards':[],\n }\n return dct\n\n def heroes(self, players) -> None:\n player = self.summary.game_summary['player']\n opponent = self.summary.game_summary['opponent']\n entity_tag = str(GameTag.ENTITY_ID.numerator)\n for hero in players:\n tags = hero.attrib\n rank = tags.get('rank') if 'rank' in tags else f'Legend {tags.get(\"legendRank\")}' if 'legendRank' in tags else None\n entityID = int([i.attrib['value'] for i in list(hero) if i.tag=='Tag' and i.attrib['tag'] == entity_tag][0])\n dct = {'rank': rank, 'entityID': entityID}\n if [i for i in list(hero) if i.tag == 'Deck']:\n friendly_entityID = int(tags['id'])\n friendly_playerID = int(tags['playerID'])\n player.update(dct)\n else:\n opponent.update(dct)\n\n for pkt in [pkt for pkt in self.packets if pkt.tag == 'FullEntity' and 'cardID' in pkt.attrib]:\n tags = pkt.attrib\n if 'HERO' in tags['cardID']:\n controller = entity(pkt).controller\n _class = id2class[tags['cardID']].title()\n dct = {'playerID': controller, 'class': _class, }\n player.update(dct) if controller == friendly_playerID else opponent.update(dct)\n for blk in [pkt for pkt in self.packets if pkt.tag == 'Block']:\n for sub_pkt in list(blk):\n if sub_pkt.tag == 'TagChange' and sub_pkt.attrib['tag'] == '24':\n first = int(sub_pkt.attrib['entity'])\n player['1st'] = first == friendly_entityID\n opponent['1st'] = first != friendly_entityID\n elif sub_pkt.tag == 'TagChange' and sub_pkt.attrib['tag'] == '20':\n break # exits at the first turn\n\n # iterates over all tags, executing some fn for each\n def cycle_all(self, packets:list, searches:list):\n pkt_cycle = cycle(packets)\n running = True\n next_pkt = next(pkt_cycle)\n while running:\n pkt, next_pkt = next_pkt, next(pkt_cycle)\n self.track(pkt)\n for inject in searches:\n inject(self, pkt, next_pkt)\n self.cycle_all(list(pkt),searches) if list(pkt) else None\n running = False if next_pkt == packets[0] else True\n \n ## Function: updates game state\n def track(self, packet):\n if packet.tag != 'TagChange' or packet.attrib['tag'] != '20': return\n game_turn = int(packet.attrib[\"value\"])\n \n # fake_event fed to _convert_turn\n player, _, turn = self._convert_turn({'turn':game_turn})\n self.summary.game_summary\n self.state.controller = player\n self.state.turn_no = turn\n if turn not in self.summary.game_summary[player]:\n self.summary.game_summary[player][turn] = copy.deepcopy(turn_template_dict)\n if self.parsing:\n self.summary.log.append(f'\\n{player} turn {turn}')\n\n def _convert_turn(self, event:dict) -> (dict, dict, int):\n first_players_turn = True if event['turn'] % 2 else False\n active_player = 'player' if self.summary.game_summary['player']['1st']==first_players_turn else 'opponent'\n _turn = int((event['turn']+1)/2) # divide by 2, rounding up\n event.pop('turn')\n return (active_player, event, _turn)\n\n @property\n def turn_str(self):\n active, turn = self.state.controller, self.state.turn_no\n return f'{active},{turn}'\n\n \nif __name__ == \"__main__\":\n test_doc = local_folder / 'xml' / '8ssdVhmUj8CLtzmvcynJRg.xml'\n xp = xml_parser.from_addr(test_doc)\n print(xp._playerID, xp._oppID)\n print([i.get('cardID',None) for i in xp.opp_cards])","sub_path":"xmlpy/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":7839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"254140198","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nfrom datetime import datetime\nimport os, sys\n\nstrDataTypesBefore = [\"Sales Diagnostic_Detail View_\", \"Forecast and Inventory Planning_\", \"Inventory Health_\"] \nstrDataTypesAfter = [\"-Sales Diagnostic_Detail View-Daily_(sp)_\", \"-Forecast and Inventory Planning-Daily_(sp)_\", \"-Inventory Health-Daily_(sp)_\"]\n\nstrCountriesBefore = [\"US\", \"CA\", \"MX\", \"BR\", \"GB\", \"FR\", \"ES\", \"DE\", \"IT\", \"JP\", \"AU\", \"AE\", \"IN\"]\nstrCountriesAfter = [\"com\", \"ca\", \"com.mx\", \"com.br\", \"co.uk\", \"fr\", \"es\", \"de\", \"it\", \"co.jp\", \"com.au\", \"ae\", \"in\"]\n\n\n\n# List files\nfileList = os.listdir(os.getcwd())\n\n#print ('directory: %s' %fileList)\nsuccessCnt = 0\nfailedCnt = 0\n\nfor fileStr in fileList:\n\ttarCountryIdx = -1\n\ttarDataTypeIdx = -1\n\t\t\n\tif fileStr.find(\".csv\") < 0:\n\t\tcontinue\n\tprint (\"filename : %s\" %fileStr)\n\tstrLen = len(fileStr)\n # Data Type Comparison\n\tfor i in range(len(strDataTypesBefore)):\n\t\t#print(strDataTypesBefore[i])\n\t\t#print(fileStr.find(strDataTypesBefore[i]))\n\t\tif fileStr.find(strDataTypesBefore[i]) >= 0:\n\t\t\ttarDataTypeIdx = i\n\t\t\tbreak\n\t\t\t\n\tfor j in range(len(strCountriesBefore)):\n\t\t#print(strCountriesBefore[j])\n\t\t#print(fileStr[strLen-12: strLen-10])\n\t\tif fileStr.find(strCountriesBefore[j], strLen-12, strLen-10) >= 0:\n\t\t\ttarCountryIdx = j\n\t\t\tbreak\n\tidxStrP = \"DataTypeIdx: {}, CountryIdx: {}\" \t\t\n\t#print (idxStrP.format(tarDataTypeIdx, tarCountryIdx))\n\tif (tarDataTypeIdx >= 0 and tarCountryIdx >=0):\n\t\t#handle date\n\t\tdateStr = fileStr[strLen-9:strLen-4]\n\t\tdateObj = datetime.strptime(\"2020-\"+dateStr, \"%Y-%m-%d\").date()\n\t\tprint(\"==> \"+strCountriesAfter[tarCountryIdx]+strDataTypesAfter[tarDataTypeIdx]+str(dateObj)+\"_to_\"+str(dateObj)+\".csv\")\n\t\tos.rename(fileStr,strCountriesAfter[tarCountryIdx]+strDataTypesAfter[tarDataTypeIdx]+str(dateObj)+\"_to_\"+str(dateObj)+\".csv\")\n\t\tsuccessCnt = successCnt + 1\n\telse:\n\t\tprint(\"==> ERROR! Data Type or Country no matched!!!\")\n\t\tfailedCnt = failedCnt + 1\n\nprint(\"Done.\")\n\nif (successCnt > 0):\n\tprint(\"Success files: \" + str(successCnt))\n\nif (failedCnt > 0):\n\tprint(\"Failed files: \" + str(failedCnt))\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"arapfilerename.py","file_name":"arapfilerename.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"90614730","text":"# Copied from previous adaptations\n\n\nimport torch\nimport higher\nfrom hessian_eigenthings import compute_hessian_eigenthings\nfrom torch.autograd import Variable\n\ndef gradient(_outputs, _inputs, grad_outputs=None, retain_graph=None,\n create_graph=False):\n if torch.is_tensor(_inputs):\n _inputs = [_inputs]\n else:\n _inputs = list(_inputs)\n grads = torch.autograd.grad(_outputs, _inputs, grad_outputs,\n allow_unused=True,\n retain_graph=retain_graph,\n create_graph=create_graph)\n grads = [x if x is not None else torch.zeros_like(y) for x, y in zip(grads,\n _inputs)]\n \n return torch.cat([x.contiguous().view(-1) for x in grads])\n\n\ndef _hessian(outputs, inputs, out=None, allow_unused=False,\n create_graph=False, weight_decay=3e-5):\n #assert outputs.data.ndimension() == 1\n\n if torch.is_tensor(inputs):\n inputs = [inputs]\n else:\n inputs = list(inputs)\n\n n = sum(p.numel() for p in inputs)\n if out is None:\n out = Variable(torch.zeros(n, n)).type_as(outputs)\n\n ai = 0\n for i, inp in enumerate(inputs):\n [grad] = torch.autograd.grad(outputs, inp, create_graph=True,\n allow_unused=allow_unused)\n grad = grad.contiguous().view(-1) + weight_decay*inp.view(-1)\n #grad = outputs[i].contiguous().view(-1)\n\n for j in range(inp.numel()):\n # print('(i, j): ', i, j)\n if grad[j].requires_grad:\n row = gradient(grad[j], inputs[i:], retain_graph=True)[j:]\n else:\n n = sum(x.numel() for x in inputs[i:]) - j\n row = Variable(torch.zeros(n)).type_as(grad[j])\n #row = grad[j].new_zeros(sum(x.numel() for x in inputs[i:]) - j)\n\n out.data[ai, ai:].add_(row.clone().type_as(out).data) # ai's row\n if ai + 1 < n:\n out.data[ai + 1:, ai].add_(row.clone().type_as(out).data[1:]) # ai's column\n del row\n ai += 1\n del grad\n return out\n\ndef exact_hessian(network, val_loader, criterion, xloader, epoch, logger, args):\n labels = []\n for i in range(network._max_nodes):\n for n in network._op_names:\n labels.append(n + \"_\" + str(i))\n\n network.logits_only=True\n val_x, val_y = next(iter(val_loader))\n val_loss = criterion(network(val_x.to('cuda')), val_y.to('cuda'))\n try:\n train_x, train_y, _, _ = next(iter(xloader))\n except:\n train_x, train_y = next(iter(xloader))\n\n train_loss = criterion(network(train_x.to('cuda')), train_y.to('cuda'))\n val_hessian_mat = _hessian(val_loss, network.arch_params())\n if epoch == 0:\n print(f\"Example architecture Hessian: {val_hessian_mat}\")\n val_eigenvals, val_eigenvecs = torch.eig(val_hessian_mat)\n try:\n if not args.merge_train_val_supernet:\n train_hessian_mat = _hessian(train_loss, network.arch_params())\n train_eigenvals, train_eigenvecs = torch.eig(train_hessian_mat)\n else:\n train_eigenvals = val_eigenvals\n except:\n train_eigenvals = val_eigenvals\n val_eigenvals = val_eigenvals[:, 0] # Drop the imaginary components\n if epoch == 0:\n print(f\"Example architecture eigenvals: {val_eigenvals}\")\n train_eigenvals = train_eigenvals[:, 0]\n val_dom_eigenvalue = torch.max(val_eigenvals)\n train_dom_eigenvalue = torch.max(train_eigenvals)\n eigenvalues = {\"max\":{}, \"spectrum\": {}}\n eigenvalues[\"max\"][\"train\"] = train_dom_eigenvalue\n eigenvalues[\"max\"][\"val\"] = val_dom_eigenvalue\n eigenvalues[\"spectrum\"][\"train\"] = {k:v for k,v in zip(labels, train_eigenvals)}\n eigenvalues[\"spectrum\"][\"val\"] = {k:v for k,v in zip(labels, val_eigenvals)}\n network.logits_only=False\n return eigenvalues\n \ndef approx_hessian(network, val_loader, criterion, xloader, args):\n network.logits_only=True\n val_eigenvals, val_eigenvecs = compute_hessian_eigenthings(network, val_loader, criterion, 1, mode=\"power_iter\", \n power_iter_steps=50, arch_only=True, full_dataset=True)\n val_dom_eigenvalue = val_eigenvals[0]\n try:\n if hasattr(args, \"merge_train_val_supernet\") and not args.merge_train_val_supernet:\n train_eigenvals, train_eigenvecs = compute_hessian_eigenthings(network, val_loader, criterion, 1, mode=\"power_iter\", \n power_iter_steps=50, arch_only=True, full_dataset=True)\n train_dom_eigenvalue = train_eigenvals[0]\n else:\n train_eigenvals, train_eigenvecs = None, None\n train_dom_eigenvalue = None\n except:\n train_eigenvals, train_eigenvecs, train_dom_eigenvalue = None, None, None\n eigenvalues = {\"max\":{}, \"spectrum\": {}}\n eigenvalues[\"max\"][\"val\"] = val_dom_eigenvalue\n eigenvalues[\"max\"][\"train\"] = train_dom_eigenvalue\n network.logits_only=False\n network.zero_grad()\n return eigenvalues\n\n\ndef format_input_data(base_inputs, base_targets, arch_inputs, arch_targets, search_loader_iter, inner_steps, args, epoch = 1000, loader_type=\"train-val\"):\n\n base_inputs, base_targets = base_inputs.cuda(non_blocking=True), base_targets.cuda(non_blocking=True)\n arch_inputs, arch_targets = arch_inputs.cuda(non_blocking=True), arch_targets.cuda(non_blocking=True)\n if args.higher_method == \"sotl\":\n arch_inputs, arch_targets = None, None\n all_base_inputs, all_base_targets, all_arch_inputs, all_arch_targets = [base_inputs], [base_targets], [arch_inputs], [arch_targets]\n for extra_step in range(inner_steps-1):\n if args.inner_steps_same_batch and (args.warm_start is None or epoch >= args.warm_start):\n all_base_inputs.append(base_inputs)\n all_base_targets.append(base_targets)\n all_arch_inputs.append(arch_inputs)\n all_arch_targets.append(arch_targets)\n continue # If using the same batch, we should not try to query the search_loader_iter for more samples\n try:\n if loader_type == \"train-val\" or loader_type == \"train-train\":\n (extra_base_inputs, extra_base_targets), (extra_arch_inputs, extra_arch_targets)= next(search_loader_iter)\n else:\n extra_base_inputs, extra_base_targets = next(search_loader_iter)\n extra_arch_inputs, extra_arch_targets = None, None\n except Exception as e:\n continue\n # extra_base_inputs, extra_arch_inputs = extra_base_inputs.cuda(non_blocking=True), extra_arch_inputs.cuda(non_blocking=True)\n # extra_base_targets, extra_arch_targets = extra_base_targets.cuda(non_blocking=True), extra_arch_targets.cuda(non_blocking=True)\n extra_base_inputs, extra_base_targets = extra_base_inputs.cuda(non_blocking=True), extra_base_targets.cuda(non_blocking=True)\n if extra_arch_inputs is not None and extra_arch_targets is not None:\n extra_arch_inputs, extra_arch_targets = extra_arch_inputs.cuda(non_blocking=True), extra_arch_targets.cuda(non_blocking=True)\n \n all_base_inputs.append(extra_base_inputs)\n all_base_targets.append(extra_base_targets)\n all_arch_inputs.append(extra_arch_inputs)\n all_arch_targets.append(extra_arch_targets)\n\n return all_base_inputs, all_base_targets, all_arch_inputs, all_arch_targets\n\n\nimport torch\nimport sys\nimport os\nfrom copy import deepcopy\nfrom typing import *\n\ndef avg_state_dicts(state_dicts: List):\n if len(state_dicts) == 1:\n return state_dicts[0]\n else:\n mean_state_dict = {}\n for k in state_dicts[0].keys():\n mean_state_dict[k] = sum([network[k] for network in state_dicts])/len(state_dicts)\n return mean_state_dict\n\ndef fo_grad_if_possible(args, fnetwork, criterion, all_arch_inputs, all_arch_targets, arch_inputs, arch_targets, cur_grads, inner_step, step, outer_iter, first_order_grad, first_order_grad_for_free_cond, first_order_grad_concurrently_cond, logger=None):\n if first_order_grad_for_free_cond: # If only doing Sum-of-first-order-SOTL gradients in FO-SOTL-DARTS or similar, we can just use these gradients that were already computed here without having to calculate more gradients as in the second-order gradient case\n if inner_step < 3 and step == 0:\n msg = f\"Adding cur_grads to first_order grads at inner_step={inner_step}, step={step}, outer_iter={outer_iter}. First_order_grad is head={str(first_order_grad)[0:100]}, cur_grads is {str(cur_grads)[0:100]}\"\n if logger is not None:\n logger.info(msg)\n else:\n print(msg)\n with torch.no_grad():\n if first_order_grad is None:\n first_order_grad = cur_grads\n else:\n first_order_grad = [g1 + g2 for g1, g2 in zip(first_order_grad, cur_grads)]\n elif first_order_grad_concurrently_cond:\n # NOTE this uses a different arch_sample everytime!\n if args.higher_method == \"val\":\n _, logits = fnetwork(all_arch_inputs[len(all_arch_inputs)-1])\n arch_loss = criterion(logits, all_arch_targets[len(all_arch_targets)-1]) * (1 if args.sandwich is None else 1/args.sandwich)\n elif args.higher_method == \"val_multiple\":\n _, logits = fnetwork(arch_inputs)\n arch_loss = criterion(logits, arch_targets) * (1 if args.sandwich is None else 1/args.sandwich)\n cur_grads = torch.autograd.grad(arch_loss, fnetwork.parameters(), allow_unused=True)\n with torch.no_grad():\n if first_order_grad is None:\n first_order_grad = cur_grads\n else:\n first_order_grad += [g1 + g2 for g1, g2 in zip(first_order_grad, cur_grads)]\n return first_order_grad\n\ndef hyper_meta_step(network, inner_rollouts, meta_grads, args, data_step, logger = None, model_init=None, outer_iters=1, epoch=0):\n\n if args.meta_algo in [\"darts_higher\", \"gdas_higher\", \"setn_higher\"]: assert args.higher_params == \"arch\"\n if args.meta_algo in ['reptile', 'metaprox']:\n avg_inner_rollout = avg_state_dicts(inner_rollouts)\n avg_meta_grad = [(p - p_init) for p, p_init in zip(avg_inner_rollout.values(), model_init.parameters())]\n if data_step == 0:\n for i, rollout in enumerate(inner_rollouts):\n msg = f\"Printing {i}-th rollout's weight sample: {str(list(rollout.values())[1])[0:75]}\"\n if logger is not None:\n logger.info(msg)\n else:\n print(msg)\n msg = f\"Average of all rollouts: {str(list(avg_inner_rollout.values())[1])[0:75]}\"\n if logger is not None:\n logger.info(msg)\n else:\n print(msg)\n network.load_state_dict(\n model_init.state_dict()) # Need to restore to the pre-rollout state before applying meta-update\n else:\n # Sum over outer_iters metagrads - if they were meant to be averaged/summed, it has to be done at the time the grads from inner_iters are put into meta_grads!\n if epoch < 2 and logger is not None:\n msg = f\"Reductioning in the outer loop (len(meta_grads)={len(meta_grads)}, head={str(meta_grads)[0:150]}) with outer reduction={args.higher_reduction_outer}, outer_iters={outer_iters}\"\n if logger is not None:\n logger.info(msg)\n else:\n print(msg)\n with torch.no_grad():\n if args.higher_reduction_outer == \"sum\":\n avg_meta_grad = [sum([g if g is not None else 0 for g in grads]) for grads in zip(*meta_grads)]\n elif args.higher_reduction_outer == \"mean\":\n avg_meta_grad = [sum([g if g is not None else 0 for g in grads]) / outer_iters for grads in\n zip(*meta_grads)]\n\n # The architecture update itself\n with torch.no_grad(): # Update the pre-rollout weights\n for (n, p), g in zip(network.named_parameters(), avg_meta_grad):\n cond = 'arch' not in n if args.higher_params == \"weights\" else 'arch' in n # The meta grads typically contain all gradient params because they arise as a result of torch.autograd.grad(..., model.parameters()) in Higher\n if cond:\n if g is not None and p.requires_grad:\n p.grad = g\n return avg_meta_grad\n\ndef hypergrad_outer(\n args,\n fnetwork,\n criterion,\n arch_targets,\n arch_inputs,\n all_arch_inputs,\n all_arch_targets,\n all_base_inputs,\n all_base_targets,\n sotl,\n inner_step,\n inner_steps,\n inner_rollouts,\n first_order_grad_for_free_cond,\n first_order_grad_concurrently_cond,\n monkeypatch_higher_grads_cond,\n zero_arch_grads_lambda,\n meta_grads,\n step,\n epoch,\n logger=None,\n):\n if args.meta_algo in [\"reptile\", \"metaprox\"]:\n inner_rollouts.append(deepcopy(fnetwork.state_dict()))\n elif args.meta_algo:\n if args.higher_method.startswith(\"val\"):\n if args.higher_order == \"second\":\n _, logits = fnetwork(\n arch_inputs, params=fnetwork.parameters(time=inner_step)\n )\n arch_loss = [criterion(logits, arch_targets)]\n meta_grad = torch.autograd.grad(\n sum(arch_loss), fnetwork.parameters(time=0), allow_unused=True\n )\n meta_grads.append(meta_grad)\n elif args.higher_order == \"first\":\n if not (\n first_order_grad_for_free_cond or first_order_grad_concurrently_cond\n ): # Computing the val grads concurrently allows to avoid gradient tracking in Higher\n if args.higher_method == \"val\":\n all_logits = [\n fnetwork(arch_inputs, params=fnetwork.parameters(time=i))[1]\n for i in range(0, inner_steps)\n ]\n arch_loss = [\n criterion(all_logits[i], arch_targets)\n for i in range(len(all_logits))\n ]\n elif args.higher_method == \"val_multiple\":\n all_logits = [\n fnetwork(\n all_arch_inputs[i], params=fnetwork.parameters(time=i)\n )[1]\n for i in range(0, inner_steps)\n ]\n arch_loss = [\n criterion(all_logits[i], all_arch_targets[i])\n for i in range(len(all_logits))\n ]\n all_grads = [\n torch.autograd.grad(arch_loss[i], fnetwork.parameters(time=i))\n for i in range(0, inner_steps)\n ]\n if step == 0 and epoch < 2:\n msg = f\"Reductioning all_grads (len={len(all_grads)} with reduction={args.higher_reduction}, inner_steps={inner_steps}\"\n if logger is not None:\n logger.info(msg)\n else:\n print()\n if args.higher_reduction == \"sum\":\n\n fo_grad = [sum(grads) for grads in zip(*all_grads)]\n elif args.higher_reduction == \"mean\":\n fo_grad = [\n sum(grads) / inner_steps for grads in zip(*all_grads)\n ]\n meta_grads.append(fo_grad)\n else:\n pass\n\n elif args.higher_method == \"sotl\":\n if args.higher_order == \"second\":\n meta_grad = torch.autograd.grad(\n sum(sotl), fnetwork.parameters(time=0), allow_unused=True\n )\n meta_grads.append(meta_grad)\n\n elif args.higher_order == \"first\":\n if not (\n first_order_grad_for_free_cond or first_order_grad_concurrently_cond\n ): # TODO I think the for_free branch puts each individual FO grad into meta_grads but here we put only average - though shouldnt really make a difference I think since we just sum over them either now or later?\n all_logits = [\n fnetwork(\n all_base_inputs[i], params=fnetwork.parameters(time=i)\n )[1]\n for i in range(0, inner_steps)\n ]\n arch_loss = [\n criterion(all_logits[i], all_base_targets[i])\n for i in range(len(all_logits))\n ]\n all_grads = [\n torch.autograd.grad(arch_loss[i], fnetwork.parameters(time=i))\n for i in range(0, inner_steps)\n ]\n if step == 0 and epoch < 2:\n if logger is not None:\n logger.info(\n f\"Reductioning all_grads (len={len(all_grads)} with reduction={args.higher_reduction}, inner_steps={inner_steps}\"\n )\n logger.info(f\"Grads sample before: {all_grads[0]}\")\n else:\n print(\n f\"Reductioning all_grads (len={len(all_grads)} with reduction={args.higher_reduction}, inner_steps={inner_steps}\"\n )\n print(f\"Grads sample before: {all_grads[0]}\")\n with torch.no_grad():\n if args.higher_reduction == \"sum\":\n fo_grad = [sum(grads) for grads in zip(*all_grads)]\n elif args.higher_reduction == \"mean\":\n fo_grad = [\n sum(grads) / inner_steps for grads in zip(*all_grads)\n ]\n if step == 0:\n print(f\"Grads sample after: {fo_grad[0]}\")\n meta_grads.append(fo_grad)\n elif step == 0 and monkeypatch_higher_grads_cond:\n all_logits = [\n fnetwork(\n all_base_inputs[i], params=fnetwork.parameters(time=i)\n )[1]\n for i in range(0, inner_steps)\n ]\n arch_loss = [\n criterion(all_logits[i], all_base_targets[i])\n for i in range(len(all_logits))\n ]\n all_grads = [\n torch.autograd.grad(arch_loss[i], fnetwork.parameters(time=i))\n for i in range(0, inner_steps)\n ]\n assert torch.all_close(\n zero_arch_grads_lambda(all_grads[0]), meta_grads[0]\n )\n logger.info(\n f\"Correctnes of first-order gradients was checked! Samples:\"\n )\n print(all_grads[0][0])\n print(meta_grads[0][0])\n else:\n pass\n return meta_grads, inner_rollouts\n","sub_path":"NAS-Bench-1Shot1-codes/optimizers/idarts_v2/sotl_utils.py","file_name":"sotl_utils.py","file_ext":"py","file_size_in_byte":19379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"132662986","text":"# coding: utf-8\n# tensorflow 采用符号式编程\n# 先定义各种变量,然后建立一个数据流图,在数据流图中定义各变量的关系。\nimport tensorflow as tf\n\n\n# 每个函数必须空两行\n# 一个简单的程序,定义两个变量的加法运算\ndef simple_example():\n # tensorflow 的运行都要放在图中,而图的运行只发生在会话中\n # 创建图\n a = tf.constant([1.0, 2.0])\n b = tf.constant([3.0, 4.0])\n c = a*b\n # 创建会话\n sess = tf.Session()\n # 计算c\n print(sess.run(c))\n # 关闭会话\n sess.close()\n\n\n# 数据类型\ndef type_example():\n # 创建一个常量运算操作,产生一个1*2的矩阵\n row_matrix = tf.constant([[3.0, 3.0]])\n col_matrix = tf.constant([[2.0], [4.0]])\n # 定义两个矩阵的乘积\n product_matrix = tf.matmul(row_matrix, col_matrix)\n # 创建一个会话\n sess = tf.Session()\n print(sess.run(product_matrix))\n # 关闭会话\n sess.close()\n\n\n\n\n\n# 指定程序运行在哪台设备上\ndef device_example():\n # 指定程序运行到哪台设备上\n with tf.Session() as sess:\n with tf.device(\"/gpu:0\"):\n row_matrix = tf.constant([[3.0, 3.0]])\n col_matrix = tf.constant([[2.0], [4.0]])\n product_matrix = tf.matmul(row_matrix, col_matrix)\n print(sess.run(product_matrix))\n sess.close()\n\n\nif __name__ == '__main__':\n device_example()\n # type_example()\n # simple_example()\n","sub_path":"python_demos/com/机器学习/tensorflowLearning/基础篇.py","file_name":"基础篇.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"623611990","text":"#!/usr/bin/python3\n\nprotein2gene = {}\nwith open(\"./KBExtractor/KB/geneIdToUniprotId.txt\", 'r') as f:\n for line in f:\n items = line.strip().split(\"\\t\")\n protein2gene[items[0]] = items[1]\n\ngenetripleStream = open(\"./KBExtractor/KB/geneTriple.txt\", 'w')\nwith open(\"./KBExtractor/KB/triple.txt\", 'r') as f:\n for line in f:\n items = line.strip().split(\"\\t\")\n if items[0] in protein2gene:\n gene1 = protein2gene[items[0]]\n else:\n continue\n if items[1] in protein2gene:\n gene2 = protein2gene[items[1]]\n else:\n continue\n genetripleStream.write(\"{}\\t{}\\t{}\\n\".format(gene1, gene2, items[2]))\ngenetripleStream.close()","sub_path":"KBExtractor/geneTriple.py","file_name":"geneTriple.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"526524256","text":"class Solution:\n\tdef permuteUnique(self, nums):\n\t\tres = []\n\t\tnums.sort()\n\t\tself.dfs(nums, 0, len(nums), [False]*len(nums), [], res)\n\t\treturn res\n\n\tdef dfs(self, nums, depth, n, used, path, res):\n\t\tif depth == n:\n\t\t\t# print(path)\n\t\t\tres.append(path[:])\n\t\t\treturn\n\n\t\t# for i in range(len(nums)):\n\t\t# \tif used[i]: continue\t# 仍是面向全部元素访问, 此处不是break, 也不用start索引\n\t\t# \tif i > 0 and used[i-1] and nums[i] == nums[i-1]:\t# i>0 使得第一个元素过关,避免py中nums[-1]干扰\n\t\t# \t\tcontinue\n\t\t# \tused[i] = True\n\t\t# \tpath.append(nums[i])\n\t\t# \tprint(\"run path is => \", path, \"\\t\", depth, \"\\t\", used, \"\\t\", i, used[i-1])\n\t\t# \tself.dfs(nums, depth+1, n, used, path, res)\n\t\t# \tpath.pop()\n\t\t# \tused[i] = False\n\n\t\tfor i in range(len(nums)):\n\t\t\tif not used[i]: \t# 这样判断快一点\n\t\t\t\tif i > 0 and not used[i-1] and nums[i] == nums[i-1]:\n\t\t\t\t\tcontinue\n\t\t\tused[i] = True\n\t\t\tpath.append(nums[i])\n\t\t\t# print(\"run path is => \", path, \"\\t\", depth, \"\\t\", used, \"\\t\", i, used[i-1])\n\t\t\tself.dfs(nums, depth+1, n, used, path, res)\n\t\t\tpath.pop()\n\t\t\tused[i] = False\n\n\nif __name__ == '__main__':\n\tprint(Solution().permuteUnique([1, 1, 2]))\n\tprint(Solution().permuteUnique([1, 1]))\n","sub_path":"bygroup/search/permutation/LC47.py","file_name":"LC47.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"381942735","text":"from django import forms\nfrom django.forms import ModelForm, Textarea\nfrom .models import Blog, Category, Comment\n\n\nclass BlogForm(ModelForm):\n def __init__(self, *args, **kwargs):\n super(BlogForm, self).__init__(*args, **kwargs)\n self.fields['title'].widget.attrs.update({'placeholder': 'Title'})\n self.fields['title'].widget.attrs.update({'id': 'post_edit_title'})\n self.fields['category'].empty_label = None\n self.fields['category'].widget.choices = self.fields['category'].choices\n self.fields['edit_date'].widget.attrs['readonly'] = True\n self.fields['edit_date'].widget.attrs.update({'id': 'formfieldastext'})\n\n class Meta:\n model = Blog\n fields = ('title', 'body', 'category', 'pinned', 'edit_date', )\n labels = {\n 'title': '',\n 'body': '',\n 'category': 'Category',\n }\n widgets = {\n 'body': Textarea(attrs={'cols': 200, 'rows': 20}),\n }\n\n\nclass CategoryForm(ModelForm):\n def __init__(self, *args, **kwargs):\n super(CategoryForm, self).__init__(*args, **kwargs)\n self.fields['title'].widget.attrs.update({'placeholder': 'Title'})\n\n class Meta:\n model = Category\n fields = ('title', )\n labels = {\n 'title': 'title',\n }\n\n\nclass CommentForm(ModelForm):\n def __init__(self, *args, **kwargs):\n super(CommentForm, self).__init__(*args, **kwargs)\n self.fields['comment'].widget.attrs.update({'placeholder': 'Comment'})\n\n class Meta:\n model = Comment\n fields = ('comment',)\n labels = {\n 'comment': '',\n }\n widgets = {\n 'comment': Textarea(attrs={'cols': 80, 'rows': 6}),\n }\n\n\nclass SearchForm(forms.Form):\n search_term = forms.CharField(label='Search', max_length=100)\n","sub_path":"blog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"411499297","text":"import cv2\nimport keras\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\nfrom keras.layers import Input, Dense, Lambda\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras import objectives\nfrom keras.datasets import mnist\nfrom keras.layers.core import Reshape\nfrom __future__ import print_function\nimport numpy as np\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten, Merge\nfrom keras.layers import Convolution2D, MaxPooling2D\nfrom keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D, UpSampling2D\nfrom keras.utils import np_utils\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.callbacks import ModelCheckpoint,LearningRateScheduler\nimport os\nfrom keras.optimizers import SGD\n\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\nprint(face_cascade)\nimg = cv2.imread('JenniferGroup.jpg')\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nfaces = face_cascade.detectMultiScale(gray, 1.3, 5)\n\nfor (x,y,w,h) in faces:\n cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)\n roi_gray = gray[y:y+h, x:x+w]\n roi_color = img[y:y+h, x:x+w]\n\na=[]\nfor i in range(0,faces.shape[0]):\n a.append(gray[faces[i][1]:faces[i][1]+faces[i][3],faces[i][0]:faces[i][0]+faces[i][2]])\n \nimport matplotlib.pyplot as plt\nplt.imshow(a[1],cmap=plt.get_cmap('gray'))\n\nfor k in range(0,faces.shape[0]): \n print(a[k].shape)\n\nimport scipy.misc\nshape=28\n\nimg1=[]\nimg2=[]\nfor i in range(0,faces.shape[0]): \n scipy.misc.imsave('face{}.jpg'.format(i), a[i])\n img1.append(cv2.cvtColor(cv2.imread('face{}.jpg'.format(i)), cv2.COLOR_BGR2GRAY))\n img2.append(cv2.resize(img1[i], (shape, shape)))\n\nimg2=np.array(img2)\n\nfor k in range(0,faces.shape[0]): \n print(img2[k].shape)\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\nx_train = x_train.astype('float32') / 255.\nx_test = x_test.astype('float32') / 255.\n\nzero=np.where(y_train==0)\n\nx_train=x_train[zero][0:20]\n\n\nbatch_size = 30\nnb_classes = 10\nimg_rows, img_cols = shape, shape\nnb_filters = 32\npool_size = (2, 2)\nkernel_size = (3, 3)\ninput_shape=(shape,shape,1)\noriginal_dim = 784\nlatent_dim = 2\nintermediate_dim = 256\nepsilon_std = 1.0\n\nlearning_rate = 0.028\ndecay_rate = 5e-5\nmomentum = 0.9\nsgd = SGD(lr=learning_rate,momentum=momentum, decay=decay_rate, nesterov=False)\n\ndef norm(x):\n return (x-np.min(x))/(np.max(x)-np.min(x))\n\npart=8\nthre=1\n\n### START GENERATOR\nrecog=Sequential()\nrecog.add(Dense(64,activation='relu',input_shape=(784,),init='glorot_uniform'))\nget_0_layer_output=K.function([recog.layers[0].input, \n K.learning_phase()],[recog.layers[0].output])\nc=get_0_layer_output([x_train[0].reshape((1,784)), 0])[0][0]\n\nrecog_left=recog\nrecog_right.add(Lambda(lambda x: x + np.mean(c), output_shape=(64,)))\n\nrecog_right=recog\nrecog_right.add(Lambda(lambda x: x + K.exp(x / 2) * K.random_normal(shape=(1, 64), mean=0.,\n std=epsilon_std), output_shape=(64,)))\n\nrecog1=Sequential()\nrecog1.add(Merge([recog_left,recog_right],mode = 'ave'))\nrecog1.add(Dense(64, activation='relu',init='glorot_uniform'))\nrecog1.add(Dense(784, activation='relu',init='glorot_uniform'))\nrecog1.compile(loss='mean_squared_error', optimizer=sgd,metrics = ['mae'])\n### END FIRST MODEL\n\n### START DISCRIMINATOR\nrecog12=Sequential()\nrecog12.add(Reshape((28,28,1),input_shape=(784,)))\nrecog12.add(Convolution2D(20, 3,3,\n border_mode='valid',\n input_shape=input_shape))\nrecog12.add(BatchNormalization(mode=2))\nrecog12.add(Activation('relu'))\nrecog12.add(UpSampling2D(size=(2, 2)))\nrecog12.add(Convolution2D(20, 3, 3,\n init='glorot_uniform'))\nrecog12.add(BatchNormalization(mode=2))\nrecog12.add(Activation('relu'))\nrecog12.add(Convolution2D(20, 3, 3,init='glorot_uniform'))\nrecog12.add(BatchNormalization(mode=2))\nrecog12.add(Activation('relu'))\nrecog12.add(MaxPooling2D(pool_size=(3,3)))\nrecog12.add(Convolution2D(4, 3, 3,init='glorot_uniform'))\nrecog12.add(BatchNormalization(mode=2))\nrecog12.add(Activation('relu'))\nrecog12.add(Reshape((28,28,1)))\nrecog12.add(Reshape((784,)))\nrecog12.add(Dense(784, activation='sigmoid',init='glorot_uniform'))\n\nrecog12.compile(loss='mean_squared_error', optimizer=sgd,metrics = ['mae'])\n\nrecog12.fit(x_train[0].reshape((1,784)), x_train[0].reshape((1,784)),\n nb_epoch=1,\n batch_size=30,verbose=1)\n\n################## GAN\n\ndef not_train(net, val):\n net.trainable = val\n for k in net.layers:\n k.trainable = val\nnot_train(recog1, False)\n\ngan_input = Input(batch_shape=(1,784))\n\ngan_level2 = recog12(recog1(gan_input))\n\nGAN = Model(gan_input, gan_level2)\nGAN.compile(loss='mean_squared_error', optimizer='adam',metrics = ['mae'])\n\nGAN.fit(x_train[0].reshape(1,784), x_train[0].reshape((1,784)), \n batch_size=30, nb_epoch=1,verbose=1)\n\nx_train_GAN=x_train[0].reshape(1,784)\n\na=GAN.predict(x_train[0].reshape(1,784),verbose=1)\n\nplt.figure(figsize=(10, 10))\nax = plt.subplot(1, 2, 1)\nplt.imshow(x_train_GAN.reshape(28, 28))\nplt.gray()\nax.get_xaxis().set_visible(False)\nax.get_yaxis().set_visible(False)\nax = plt.subplot(1, 2, 2)\nplt.imshow(a.reshape(28, 28))\nplt.gray()\nax.get_xaxis().set_visible(False)\nax.get_yaxis().set_visible(False)\nplt.show()\n\n\nimport pydot\nimport graphviz\nimport pydot_ng as pydot\n\nfrom IPython.display import SVG\nfrom keras.utils.visualize_util import model_to_dot\nSVG(model_to_dot(recog_right).create(prog='dot', format='svg'))\n","sub_path":"examples/rubens/gan_generative_adversarial_0.py","file_name":"gan_generative_adversarial_0.py","file_ext":"py","file_size_in_byte":5601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"19105280","text":"from django.db import models\n\nclass Despesa(models.Model):\n TIPO_DESPESA_CHOICES = (\n ('Remédio', 'Remédio'),\n ('Roupas', 'Roupas'),\n ('Alimentação', 'Alimentação'),\n ('Educação', 'Educação'),\n ('Transporte', 'Transporte'),\n ('Outros', 'Outros'),\n )\n FORMA_PAGAMENTO_CHOICES = (\n ('Dinheiro', 'Dinheiro'),\n ('Cartão de Crédito', 'Cartão de Crédito'),\n ('Cartão de Débito', 'Cartão de Débito'),\n ('Cartão Crediário', 'Cartão Crediário'),\n ('Cheque', 'Cheque'),\n )\n\n data_criacao = models.CharField('data de criacao',max_length=20)\n tipo_despesa = models.CharField('tipo de despesa',max_length=30, choices=TIPO_DESPESA_CHOICES)\n descricao = models.TextField('descricao', max_length=100)\n forma_pagamento = models.CharField('forma de pagamento',max_length=50, choices=FORMA_PAGAMENTO_CHOICES)\n vencimento = models.DateField()\n quitado = models.BooleanField()\n\n\n class Meta:\n verbose_name_plural = 'Despesas'\n verbose_name = 'Despesa'\n ordering = ('-vencimento', 'forma_pagamento',)\n\n def __str__(self):\n return '{} - {} - {}'.format(\n self.data_criacao,\n self.tipo_despesa, )\n self.descricao,\n\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"551853337","text":"###############################################################################\n#\n# Tests for XlsxWriter.\n#\n# SPDX-License-Identifier: BSD-2-Clause\n# Copyright (c), 2013-2023, John McNamara, jmcnamara@cpan.org\n#\n\nfrom ..excel_comparison_test import ExcelComparisonTest\nfrom ...workbook import Workbook\n\n\nclass TestCompareXLSXFiles(ExcelComparisonTest):\n \"\"\"\n Test file created by XlsxWriter against a file created by Excel.\n\n \"\"\"\n\n def setUp(self):\n self.set_filename(\"chart_column13.xlsx\")\n\n def test_create_file(self):\n \"\"\"Test the creation of a simple XlsxWriter file.\"\"\"\n\n workbook = Workbook(self.got_filename)\n\n worksheet = workbook.add_worksheet()\n chart = workbook.add_chart({\"type\": \"column\"})\n\n chart.axis_ids = [60474496, 78612736]\n\n worksheet.write(\"A1\", \"1.1_1\")\n worksheet.write(\"B1\", \"2.2_2\")\n worksheet.write(\"A2\", 1)\n worksheet.write(\"B2\", 2)\n\n chart.add_series(\n {\"categories\": \"=Sheet1!$A$1:$B$1\", \"values\": \"=Sheet1!$A$2:$B$2\"}\n )\n\n worksheet.insert_chart(\"E9\", chart)\n\n workbook.close()\n\n self.assertExcelEqual()\n","sub_path":"xlsxwriter/test/comparison/test_chart_column13.py","file_name":"test_chart_column13.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"293920313","text":"import tensorflow as tf\nfrom collections import defaultdict\nimport abc\n\nfrom functools import partial\nfrom yolo.ops import (loss_utils, box_ops, math_ops)\n\n\nclass YoloLossBase(object, metaclass=abc.ABCMeta):\n \"\"\"Parameters for the YOLO loss functions used at each detection \n generator. This base class implements the base functionality required to \n implement a Yolo Loss function\"\"\"\n\n def __init__(self,\n classes,\n mask,\n anchors,\n path_stride=1,\n ignore_thresh=0.7,\n truth_thresh=1.0,\n loss_type=\"ciou\",\n iou_normalizer=1.0,\n cls_normalizer=1.0,\n obj_normalizer=1.0,\n label_smoothing=0.0,\n objectness_smooth=True,\n update_on_repeat=False,\n box_type=\"original\",\n scale_x_y=1.0,\n max_delta=10):\n \"\"\"Loss Function Initialization. \n\n Args:\n classes: `int` for the number of classes \n mask: `List[int]` for the output level that this specific model output \n level\n anchors: `List[List[int]]` for the anchor boxes that are used in the model \n at all levels. For anchor free prediction set the anchor list to be the \n same as the image resolution. \n path_stride: `int` for how much to scale this level to get the orginal \n input shape.\n ignore_thresh: `float` for the IOU value over which the loss is not \n propagated, and a detection is assumed to have been made.\n truth_thresh: `float` for the IOU value over which the loss is propagated \n despite a detection being made.\n loss_type: `str` for the typeof iou loss to use with in {ciou, diou, \n giou, iou}.\n iou_normalizer: `float` for how much to scale the loss on the IOU or the \n boxes.\n cls_normalizer: `float` for how much to scale the loss on the classes.\n obj_normalizer: `float` for how much to scale loss on the detection map.\n objectness_smooth: `float` for how much to smooth the loss on the \n detection map.\n use_reduction_sum: `bool` for whether to use the scaled loss \n or the traditional loss.\n update_on_repeat: `bool` for whether to replace with the newest or the\n best value when an index is consumed by multiple objects. \n label_smoothing: `float` for how much to smooth the loss on the classes\n box_type: `bool` for which scaling type to use. \n scale_x_y: dictionary `float` values inidcating how far each pixel can see \n outside of its containment of 1.0. a value of 1.2 indicates there is a \n 20% extended radius around each pixel that this specific pixel can \n predict values for a center at. the center can range from 0 - value/2 \n to 1 + value/2, this value is set in the yolo filter, and resused here. \n there should be one value for scale_xy for each level from min_level to \n max_level.\n max_delta: gradient clipping to apply to the box loss. \n \"\"\"\n self._loss_type = loss_type\n self._classes = tf.constant(tf.cast(classes, dtype=tf.int32))\n self._num = tf.cast(len(mask), dtype=tf.int32)\n self._truth_thresh = truth_thresh\n self._ignore_thresh = ignore_thresh\n self._masks = mask\n self._anchors = anchors\n\n self._iou_normalizer = iou_normalizer\n self._cls_normalizer = cls_normalizer\n self._obj_normalizer = obj_normalizer\n self._scale_x_y = scale_x_y\n self._max_delta = max_delta\n\n self._label_smoothing = tf.cast(label_smoothing, tf.float32)\n self._objectness_smooth = float(objectness_smooth)\n self._update_on_repeat = update_on_repeat\n self._box_type = box_type\n self._path_stride = path_stride\n\n box_kwargs = dict(\n stride=self._path_stride,\n scale_xy=self._scale_x_y,\n box_type=self._box_type,\n max_delta=self._max_delta)\n self._decode_boxes = partial(loss_utils.get_predicted_box, **box_kwargs)\n\n self._search_pairs = None\n self._build_per_path_attributes()\n\n def box_loss(self, true_box, pred_box, darknet=False):\n \"\"\"Calls the iou functions and uses it to compute the loss this op is \n the same regardless of Yolo Loss version\"\"\"\n if self._loss_type == \"giou\":\n iou, liou = box_ops.compute_giou(true_box, pred_box)\n elif self._loss_type == \"ciou\":\n iou, liou = box_ops.compute_ciou(true_box, pred_box, darknet=darknet)\n else:\n liou = iou = box_ops.compute_iou(true_box, pred_box)\n loss_box = 1 - liou\n return iou, liou, loss_box\n\n def _tiled_global_box_search(self,\n pred_boxes,\n pred_classes,\n boxes,\n classes,\n true_conf,\n smoothed,\n scale=None):\n \"\"\"Completes a search of all predictions against all the ground truths to \n dynamically associate ground truths with predictions.\"\"\"\n\n if self._search_pairs is None:\n return true_conf, tf.ones_like(true_conf)\n\n # Search all predictions against ground truths to find mathcing boxes for\n # each pixel.\n _, _, iou_max, _ = self._search_pairs(\n pred_boxes, pred_classes, boxes, classes, scale=scale, yxyx=True)\n\n # Find the exact indexes to ignore and keep.\n ignore_mask = tf.cast(iou_max < self._ignore_thresh, pred_boxes.dtype)\n iou_mask = iou_max > self._ignore_thresh\n\n if not smoothed:\n # Ignore all pixels where a box was not supposed to be predicted but a\n # high confidence box was predicted.\n obj_mask = true_conf + (1 - true_conf) * ignore_mask\n else:\n # Replace pixels in the tre confidence map with the max iou predicted\n # with in that cell.\n obj_mask = tf.ones_like(true_conf)\n iou_ = (1 - self._objectness_smooth) + self._objectness_smooth * iou_max\n iou_ = tf.where(iou_max > 0, iou_, tf.zeros_like(iou_))\n true_conf = tf.where(iou_mask, iou_, true_conf)\n\n # Stop gradient so while loop is not tracked.\n obj_mask = tf.stop_gradient(obj_mask)\n true_conf = tf.stop_gradient(true_conf)\n return true_conf, obj_mask\n\n def __call__(self, true_counts, inds, y_true, boxes, classes, y_pred):\n \"\"\"Call function to compute the loss and return the total loss as \n well as the loss for each detection mask on a given FPN level. \n \n Args: \n true_counts: `Tensor` of shape [batchsize, height, width, num_anchors] \n represeneting how many boxes are in a given pixel [j, i] in the \n output map.\n inds: `Tensor` of shape [batchsize, None, 3] indicating the location \n [j, i] that a given box is associatied with in the FPN prediction \n map. \n y_true: `Tensor` of shape [batchsize, None, 8] indicating the actual box \n associated with each index in the inds tensor list.\n boxes: `Tensor` of shape [batchsize, None, 4] indicating the original \n ground truth boxes for each image as they came from the decoder used\n for bounding box search. \n classes: `Tensor` of shape [batchsize, None, 1] indicating the original \n ground truth classes for each image as they came from the decoder used\n for bounding box search.\n y_pred: `Tensor` of shape [batchsize, height, width, output_depth] \n holding the models output at a specific FPN level.\n\n Return:\n loss: `float` for the actual loss.\n box_loss: `float` loss on the boxes used for metrics.\n conf_loss: `float` loss on the confidence used for metrics.\n class_loss: `float` loss on the classes used for metrics.\n avg_iou: `float` metric for the average iou between predictions \n and ground truth.\n avg_obj: `float` metric for the average confidence of the model \n for predictions.\n \"\"\"\n (loss, box_loss, conf_loss, class_loss, mean_loss, iou, pred_conf, ind_mask,\n grid_mask) = self.call(true_counts, inds, y_true, boxes, classes, y_pred)\n\n # Metric compute using done here to save time and resources.\n sigmoid_conf = tf.stop_gradient(tf.sigmoid(pred_conf))\n iou = tf.stop_gradient(iou)\n avg_iou = loss_utils.avgiou(\n loss_utils.apply_mask(tf.squeeze(ind_mask, axis=-1), iou))\n avg_obj = loss_utils.avgiou(tf.squeeze(sigmoid_conf, axis=-1) * grid_mask)\n return (loss, box_loss, conf_loss, class_loss, mean_loss,\n tf.stop_gradient(avg_iou), tf.stop_gradient(avg_obj))\n\n @abc.abstractmethod\n def _build_per_path_attributes(self):\n \"\"\"Additional initialization required specifically for each unique YOLO \n loss version\"\"\"\n ...\n\n @abc.abstractmethod\n def call():\n \"\"\"The actual logic to apply to the raw model for optimization.\"\"\"\n ...\n\n def post_path_aggregation(self, \n loss, box_loss, conf_loss, class_loss, ground_truths, predictions):\n \"\"\"This method allows for post processing of a loss value after the loss\n has been aggregateda across all the FPN levels.\"\"\"\n return loss\n\n @abc.abstractmethod\n def cross_replica_aggregation(self, loss, num_replicas_in_sync):\n \"\"\"This controls how the loss should be aggregated across replicas.\"\"\"\n ...\n\n\n@tf.custom_gradient\ndef grad_sigmoid(values):\n # This is an identity operation that will\n # allow us to add some steps to the back propagation.\n def delta(dy):\n # Darknet only propagtes sigmoids for the boxes\n # under some conditions, so we need this to selectively\n # add the sigmoid to the chain rule\n t = tf.math.sigmoid(values)\n return dy * t * (1 - t)\n\n return values, delta\n\n\nclass DarknetLoss(YoloLossBase):\n \"\"\"This class implements the full logic for the standard Yolo models \n encompassing Yolov3, Yolov4, and Yolo-Tiny.\"\"\"\n\n def _build_per_path_attributes(self):\n \"\"\"Paramterization of pair wise search and grid generators for box \n decoding and dynamic ground truth association.\"\"\"\n self._anchor_generator = loss_utils.GridGenerator(\n masks=self._masks,\n anchors=self._anchors,\n scale_anchors=self._path_stride)\n\n if self._ignore_thresh > 0.0:\n self._search_pairs = loss_utils.PairWiseSearch(\n iou_type=\"iou\", any=True, min_conf=0.25)\n return\n\n def call(self, true_counts, inds, y_true, boxes, classes, y_pred):\n \"\"\"Per FPN path loss computation logic.\"\"\"\n if self._box_type == \"scaled\":\n # Darknet Model Propagates a sigmoid once in back prop so we replicate\n # that behaviour\n y_pred = grad_sigmoid(y_pred)\n\n # Generate and store constants and format output.\n shape = tf.shape(true_counts)\n batch_size, width, height, num = shape[0], shape[1], shape[2], shape[3]\n fwidth = tf.cast(width, tf.float32)\n fheight = tf.cast(height, tf.float32)\n grid_points, anchor_grid = self._anchor_generator(\n width, height, batch_size, dtype=tf.float32)\n\n # Cast all input compontnts to float32 and stop gradient to save memory.\n boxes = tf.stop_gradient(tf.cast(boxes, tf.float32))\n classes = tf.stop_gradient(tf.cast(classes, tf.float32))\n y_true = tf.stop_gradient(tf.cast(y_true, tf.float32))\n true_counts = tf.stop_gradient(tf.cast(true_counts, tf.float32))\n true_conf = tf.stop_gradient(tf.clip_by_value(true_counts, 0.0, 1.0))\n grid_points = tf.stop_gradient(grid_points)\n anchor_grid = tf.stop_gradient(anchor_grid)\n\n # Split all the ground truths to use as seperate items in loss computation.\n (true_box, ind_mask, true_class, _, _) = tf.split(\n y_true, [4, 1, 1, 1, 1], axis=-1)\n true_conf = tf.squeeze(true_conf, axis=-1)\n true_class = tf.squeeze(true_class, axis=-1)\n grid_mask = true_conf\n\n # Splits all predictions.\n y_pred = tf.cast(\n tf.reshape(y_pred, [batch_size, width, height, num, -1]), tf.float32)\n pred_box, pred_conf, pred_class = tf.split(y_pred, [4, 1, -1], axis=-1)\n\n # Decode the boxes to be used for loss compute.\n _, _, pred_box = self._decode_boxes(\n fwidth, fheight, pred_box, anchor_grid, grid_points, darknet=True)\n\n # If the ignore threshold is enabled, search all boxes ignore all\n # IOU valeus larger than the ignore threshold that are not in the\n # noted ground truth list.\n if self._ignore_thresh != 0.0:\n (true_conf, obj_mask) = self._tiled_global_box_search(\n pred_box,\n tf.stop_gradient(tf.sigmoid(pred_class)),\n boxes,\n classes,\n true_conf,\n smoothed=self._objectness_smooth > 0)\n\n # Build the one hot class list that are used for class loss.\n true_class = tf.one_hot(\n tf.cast(true_class, tf.int32),\n depth=tf.shape(pred_class)[-1],\n dtype=pred_class.dtype)\n true_classes = tf.stop_gradient(loss_utils.apply_mask(ind_mask, true_class))\n\n # Reorganize the one hot class list as a grid.\n true_class = loss_utils.build_grid(\n inds, true_classes, pred_class, ind_mask, update=False)\n true_class = tf.stop_gradient(true_class)\n\n # Use the class mask to find the number of objects located in\n # each predicted grid cell/pixel.\n counts = true_class\n counts = tf.reduce_sum(counts, axis=-1, keepdims=True)\n reps = tf.gather_nd(counts, inds, batch_dims=1)\n reps = tf.squeeze(reps, axis=-1)\n reps = tf.stop_gradient(tf.where(reps == 0.0, tf.ones_like(reps), reps))\n\n # Compute the loss for only the cells in which the boxes are located.\n pred_box = loss_utils.apply_mask(ind_mask,\n tf.gather_nd(pred_box, inds, batch_dims=1))\n iou, _, box_loss = self.box_loss(true_box, pred_box, darknet=True)\n box_loss = loss_utils.apply_mask(tf.squeeze(ind_mask, axis=-1), box_loss)\n box_loss = math_ops.divide_no_nan(box_loss, reps)\n box_loss = tf.cast(tf.reduce_sum(box_loss, axis=1), dtype=y_pred.dtype)\n\n # Compute the sigmoid binary cross entropy for the class maps.\n class_loss = tf.reduce_mean(\n loss_utils.sigmoid_BCE(\n tf.expand_dims(true_class, axis=-1),\n tf.expand_dims(pred_class, axis=-1), self._label_smoothing),\n axis=-1)\n\n # Apply normalization to the class losses.\n if self._cls_normalizer < 1.0:\n # Build a mask based on the true class locations.\n cls_norm_mask = true_class\n # Apply the classes weight to class indexes were one_hot is one.\n class_loss *= ((1 - cls_norm_mask) + cls_norm_mask * self._cls_normalizer)\n\n # Mask to the class loss and compute the sum over all the objects.\n class_loss = tf.reduce_sum(class_loss, axis=-1)\n class_loss = loss_utils.apply_mask(grid_mask, class_loss)\n class_loss = math_ops.rm_nan_inf(class_loss, val=0.0)\n class_loss = tf.cast(\n tf.reduce_sum(class_loss, axis=(1, 2, 3)), dtype=y_pred.dtype)\n\n # Compute the sigmoid binary cross entropy for the confidence maps.\n bce = tf.reduce_mean(\n loss_utils.sigmoid_BCE(\n tf.expand_dims(true_conf, axis=-1), pred_conf, 0.0),\n axis=-1)\n\n # Mask the confidence loss and take the sum across all the grid cells.\n if self._ignore_thresh != 0.0:\n bce = loss_utils.apply_mask(obj_mask, bce)\n conf_loss = tf.cast(tf.reduce_sum(bce, axis=(1, 2, 3)), dtype=y_pred.dtype)\n\n # Apply the weights to each loss.\n box_loss *= self._iou_normalizer\n conf_loss *= self._obj_normalizer\n\n # Add all the losses together then take the mean over the batches.\n loss = box_loss + class_loss + conf_loss\n loss = tf.reduce_mean(loss)\n\n # Reduce the mean of the losses to use as a metric.\n box_loss = tf.reduce_mean(box_loss)\n conf_loss = tf.reduce_mean(conf_loss)\n class_loss = tf.reduce_mean(class_loss)\n\n return (loss, box_loss, conf_loss, class_loss, loss, iou, pred_conf,\n ind_mask, grid_mask)\n\n def cross_replica_aggregation(self, loss, num_replicas_in_sync):\n \"\"\"this method is not specific to each loss path, but each loss type\"\"\"\n return loss / num_replicas_in_sync\n\n\nclass ScaledLoss(YoloLossBase):\n \"\"\"This class implements the full logic for the scaled Yolo models \n encompassing Yolov4-csp, Yolov4-Large, and Yolov5.\"\"\"\n\n def _build_per_path_attributes(self):\n \"\"\"Paramterization of pair wise search and grid generators for box \n decoding and dynamic ground truth association.\"\"\"\n self._anchor_generator = loss_utils.GridGenerator(\n masks=self._masks,\n anchors=self._anchors,\n scale_anchors=self._path_stride)\n\n if self._ignore_thresh > 0.0:\n self._search_pairs = loss_utils.PairWiseSearch(\n iou_type=self._loss_type, any=False, min_conf=0.25)\n return\n\n def call(self, true_counts, inds, y_true, boxes, classes, y_pred):\n \"\"\"Per FPN path loss computation logic.\"\"\"\n # Generate shape constants.\n shape = tf.shape(true_counts)\n batch_size, width, height, num = shape[0], shape[1], shape[2], shape[3]\n fwidth = tf.cast(width, tf.float32)\n fheight = tf.cast(height, tf.float32)\n\n # Cast all input compontnts to float32 and stop gradient to save memory.\n y_true = tf.cast(y_true, tf.float32)\n true_counts = tf.cast(true_counts, tf.float32)\n true_conf = tf.clip_by_value(true_counts, 0.0, 1.0)\n grid_points, anchor_grid = self._anchor_generator(\n width, height, batch_size, dtype=tf.float32)\n\n # Split the y_true list.\n (true_box, ind_mask, true_class, _, _) = tf.split(\n y_true, [4, 1, 1, 1, 1], axis=-1)\n grid_mask = true_conf = tf.squeeze(true_conf, axis=-1)\n true_class = tf.squeeze(true_class, axis=-1)\n num_objs = tf.cast(tf.reduce_sum(ind_mask), dtype=y_pred.dtype)\n\n # Split up the predicitons.\n y_pred = tf.cast(\n tf.reshape(y_pred, [batch_size, width, height, num, -1]), tf.float32)\n pred_box, pred_conf, pred_class = tf.split(y_pred, [4, 1, -1], axis=-1)\n\n # Decode the boxes for loss compute.\n scale, pred_box, pbg = self._decode_boxes(\n fwidth, fheight, pred_box, anchor_grid, grid_points, darknet=False)\n\n # If the ignore threshold is enabled, search all boxes ignore all\n # IOU valeus larger than the ignore threshold that are not in the\n # noted ground truth list.\n if self._ignore_thresh != 0.0:\n (_, obj_mask) = self._tiled_global_box_search(\n pbg,\n tf.stop_gradient(tf.sigmoid(pred_class)),\n boxes,\n classes,\n true_conf,\n smoothed=False,\n scale=None)\n\n # Scale and shift and select the ground truth boxes\n # and predictions to the prediciton domain.\n if self._box_type == \"anchor_free\":\n true_box = loss_utils.apply_mask(\n ind_mask, (scale * self._path_stride * true_box))\n else:\n offset = tf.cast(\n tf.gather_nd(grid_points, inds, batch_dims=1), true_box.dtype)\n offset = tf.concat([offset, tf.zeros_like(offset)], axis=-1)\n true_box = loss_utils.apply_mask(ind_mask, (scale * true_box) - offset)\n pred_box = loss_utils.apply_mask(ind_mask,\n tf.gather_nd(pred_box, inds, batch_dims=1))\n\n # Select the correct/used prediction classes.\n true_class = tf.one_hot(\n tf.cast(true_class, tf.int32),\n depth=tf.shape(pred_class)[-1],\n dtype=pred_class.dtype)\n true_class = loss_utils.apply_mask(ind_mask, true_class)\n pred_class = loss_utils.apply_mask(\n ind_mask, tf.gather_nd(pred_class, inds, batch_dims=1))\n\n # Compute the box loss.\n _, iou, box_loss = self.box_loss(true_box, pred_box, darknet=False)\n box_loss = loss_utils.apply_mask(tf.squeeze(ind_mask, axis=-1), box_loss)\n box_loss = math_ops.divide_no_nan(tf.reduce_sum(box_loss), num_objs)\n\n # Use the box IOU to build the map for confidence loss computation.\n iou = tf.maximum(tf.stop_gradient(iou), 0.0)\n smoothed_iou = ((\n (1 - self._objectness_smooth) * tf.cast(ind_mask, iou.dtype)) +\n self._objectness_smooth * tf.expand_dims(iou, axis=-1))\n smoothed_iou = loss_utils.apply_mask(ind_mask, smoothed_iou)\n true_conf = loss_utils.build_grid(\n inds, smoothed_iou, pred_conf, ind_mask, update=self._update_on_repeat)\n true_conf = tf.squeeze(true_conf, axis=-1)\n\n # Compute the cross entropy loss for the confidence map.\n bce = tf.keras.losses.binary_crossentropy(\n tf.expand_dims(true_conf, axis=-1), pred_conf, from_logits=True)\n if self._ignore_thresh != 0.0:\n bce = loss_utils.apply_mask(obj_mask, bce)\n conf_loss = tf.reduce_sum(bce) / tf.reduce_sum(obj_mask)\n else:\n conf_loss = tf.reduce_mean(bce)\n\n # Compute the cross entropy loss for the class maps.\n class_loss = tf.keras.losses.binary_crossentropy(\n true_class,\n pred_class,\n label_smoothing=self._label_smoothing,\n from_logits=True)\n class_loss = loss_utils.apply_mask(\n tf.squeeze(ind_mask, axis=-1), class_loss)\n class_loss = math_ops.divide_no_nan(tf.reduce_sum(class_loss), num_objs)\n\n # Apply the weights to each loss.\n box_loss *= self._iou_normalizer\n class_loss *= self._cls_normalizer\n conf_loss *= self._obj_normalizer\n\n # Add all the losses together then take the sum over the batches.\n mean_loss = box_loss + class_loss + conf_loss\n loss = mean_loss * tf.cast(batch_size, mean_loss.dtype)\n\n return (loss, box_loss, conf_loss, class_loss, mean_loss, iou, pred_conf,\n ind_mask, grid_mask)\n\n def post_path_aggregation(self, \n loss, box_loss, conf_loss, class_loss, ground_truths, predictions):\n scale = tf.stop_gradient(3 / len(list(predictions.keys())))\n return loss * scale\n\n def cross_replica_aggregation(self, loss, num_replicas_in_sync):\n \"\"\"this method is not specific to each loss path, but each loss type\"\"\"\n return loss\n\n\nclass YoloLoss(object):\n \"\"\"This class implements the aggregated loss across paths for the YOLO \n model. The class implements the YOLO loss as a factory in order to allow \n selection and implementation of new versions of the YOLO loss as the model \n is updated in the future. \n \"\"\"\n\n def __init__(self,\n keys,\n classes,\n anchors,\n masks=None,\n path_strides=None,\n truth_thresholds=None,\n ignore_thresholds=None,\n loss_types=None,\n iou_normalizers=None,\n cls_normalizers=None,\n obj_normalizers=None,\n objectness_smooths=None,\n box_types=None,\n scale_xys=None,\n max_deltas=None,\n label_smoothing=0.0,\n use_scaled_loss=False,\n update_on_repeat=False):\n \"\"\"Loss Function Initialization. \n\n Args:\n keys: `List[str]` indicating the name of the FPN paths that need to be\n optimized.\n classes: `int` for the number of classes \n anchors: `List[List[int]]` for the anchor boxes that are used in the model \n at all levels. For anchor free prediction set the anchor list to be the \n same as the image resolution.\n masks: `List[int]` for the output level that this specific model output \n level\n path_strides: `Dict[int]` for how much to scale this level to get the \n orginal input shape for each FPN path.\n truth_thresholds: `Dict[float]` for the IOU value over which the loss is \n propagated despite a detection being made for each FPN path.\n ignore_thresholds: `Dict[float]` for the IOU value over which the loss is \n not propagated, and a detection is assumed to have been made for each \n FPN path.\n loss_types: `Dict[str]` for the typeof iou loss to use with in {ciou, \n diou, giou, iou} for each FPN path.\n iou_normalizers: `Dict[float]` for how much to scale the loss on the IOU \n or the boxes for each FPN path.\n cls_normalizers: `Dict[float]` for how much to scale the loss on the \n classes for each FPN path.\n obj_normalizers: `Dict[float]` for how much to scale loss on the detection \n map for each FPN path.\n objectness_smooths: `Dict[float]` for how much to smooth the loss on the \n detection map for each FPN path.\n box_type: `Dict[bool]` for which scaling type to use for each FPN path. \n scale_xys: `Dict[float]` values inidcating how far each pixel can see \n outside of its containment of 1.0. a value of 1.2 indicates there is a \n 20% extended radius around each pixel that this specific pixel can \n predict values for a center at. the center can range from 0 - value/2 \n to 1 + value/2, this value is set in the yolo filter, and resused here. \n there should be one value for scale_xy for each level from min_level to \n max_level. One for each FPN path.\n max_deltas: `Dict[float]` for gradient clipping to apply to the box loss \n for each FPN path.\n label_smoothing: `Dict[float]` for how much to smooth the loss on the \n classes for each FPN path.\n use_scaled_loss: `bool` for whether to use the scaled loss \n or the traditional loss.\n update_on_repeat: `bool` for whether to replace with the newest or \n the best value when an index is consumed by multiple objects. \n \"\"\"\n if use_scaled_loss:\n loss_type = \"scaled\"\n else:\n loss_type = \"darknet\"\n\n LOSSES = {\"darknet\": DarknetLoss, \"scaled\": ScaledLoss}\n self._loss_dict = {}\n for key in keys:\n self._loss_dict[key] = LOSSES[loss_type](\n classes=classes,\n anchors=anchors,\n mask=masks[key],\n truth_thresh=truth_thresholds[key],\n ignore_thresh=ignore_thresholds[key],\n loss_type=loss_types[key],\n iou_normalizer=iou_normalizers[key],\n cls_normalizer=cls_normalizers[key],\n obj_normalizer=obj_normalizers[key],\n box_type=box_types[key],\n objectness_smooth=objectness_smooths[key],\n max_delta=max_deltas[key],\n path_stride=path_strides[key],\n scale_x_y=scale_xys[key],\n update_on_repeat=update_on_repeat,\n label_smoothing=label_smoothing)\n\n def __call__(self, ground_truth, predictions):\n metric_dict = defaultdict(dict)\n metric_dict['net']['box'] = 0\n metric_dict['net']['class'] = 0\n metric_dict['net']['conf'] = 0\n\n loss_val, metric_loss = 0, 0\n num_replicas_in_sync = tf.distribute.get_strategy().num_replicas_in_sync\n\n for key in predictions.keys():\n (_loss, _loss_box, _loss_conf, _loss_class, _mean_loss, _avg_iou,\n _avg_obj) = self._loss_dict[key](ground_truth['true_conf'][key],\n ground_truth['inds'][key],\n ground_truth['upds'][key],\n ground_truth['bbox'],\n ground_truth['classes'],\n predictions[key])\n\n # after computing the loss, scale loss as needed for aggregation\n # across FPN levels\n _loss = self._loss_dict[key].post_path_aggregation(\n _loss, _loss_box, _loss_conf, _loss_class, ground_truth, predictions)\n\n # after completing the scaling of the loss on each replica, handle\n # scaling the loss for mergeing the loss across replicas\n _loss = self._loss_dict[key].cross_replica_aggregation(\n _loss, num_replicas_in_sync)\n loss_val += _loss\n\n # detach all the below gradients: none of them should make a\n # contribution to the gradient form this point forwards\n metric_loss += tf.stop_gradient(_mean_loss)\n metric_dict[key]['loss'] = tf.stop_gradient(_mean_loss)\n metric_dict[key]['avg_iou'] = tf.stop_gradient(_avg_iou)\n metric_dict[key][\"avg_obj\"] = tf.stop_gradient(_avg_obj)\n\n metric_dict['net']['box'] += tf.stop_gradient(_loss_box)\n metric_dict['net']['class'] += tf.stop_gradient(_loss_class)\n metric_dict['net']['conf'] += tf.stop_gradient(_loss_conf)\n return loss_val, metric_loss, metric_dict\n","sub_path":"yolo/losses/yolo_loss.py","file_name":"yolo_loss.py","file_ext":"py","file_size_in_byte":28031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"379947432","text":"#!/usr/bin/env python3\n\n# Copyright (c) 2013, Ruslan Baratov\n# All rights reserved.\n\nimport argparse\nimport glob\nimport os\nimport subprocess\nimport sys\n\nparser = argparse.ArgumentParser(\n description='Workaround for not working ios install command'\n)\n\nparser.add_argument(\n '--target',\n type=str,\n required=True,\n help='install target'\n)\n\nparser.add_argument(\n '--destination',\n type=str,\n required=True,\n help='destination directory'\n)\n\nparser.add_argument(\n '--verbose',\n action='store_true',\n help='print a lot info'\n)\n\nclass Log:\n def __init__(self, verbose):\n self.verbose = verbose\n def p(self, message):\n if self.verbose:\n print(message)\n\ndebug_prefix = 'd'\n\nargs = parser.parse_args()\ntarget = args.target\ndst = args.destination\n\nlog = Log(args.verbose)\n\nlog.p('target: {}'.format(target))\nlog.p('destination: {}'.format(dst))\n\nos.makedirs(dst, exist_ok=True)\n\ndef run_xcode(configuration, sdk):\n if sdk == 'iphonesimulator':\n arch = '-arch i386'\n else:\n arch = ''\n subprocess.check_call(\n 'xcodebuild -target {} -configuration {} -sdk {} {}'.format(\n target, configuration, sdk, arch\n ),\n shell=True\n )\n\nrun_xcode('Debug', 'iphoneos')\nrun_xcode('Release', 'iphoneos')\nrun_xcode('Debug', 'iphonesimulator')\nrun_xcode('Release', 'iphonesimulator')\n\ndef detect_file(dir):\n cwd = os.getcwd()\n target_file = 'lib{}.a'.format(target)\n target_file_postfix = 'lib{}d.a'.format(target)\n for root, dirs, files in os.walk(cwd):\n if not dir in dirs:\n continue\n for target_root, x, target_files in os.walk(os.path.join(root, dir)):\n if target_file in target_files:\n return os.path.join(target_root, target_file)\n if target_file_postfix in target_files:\n return os.path.join(target_root, target_file_postfix)\n print('working directory: {}'.format(cwd))\n sys.exit(\n 'file \"{}\" not found in directory \"{}\"'.format(target_file, dir)\n )\n\ndebug_arm = detect_file('Debug-iphoneos')\ndebug_x86 = detect_file('Debug-iphonesimulator')\n\nlog.p('detected debug files:\\n {}\\n {}'.format(debug_arm, debug_x86))\n\ndebug_result = '{}/lib{}{}.a'.format(dst, target, debug_prefix)\nsubprocess.check_call(\n 'lipo -output {} -create {} {}'.format(\n debug_result, debug_arm, debug_x86\n ),\n shell=True\n)\n\nrelease_arm = detect_file('Release-iphoneos')\nrelease_x86 = detect_file('Release-iphonesimulator')\n\nlog.p('detected release files:\\n {}\\n {}'.format(release_arm, release_x86))\n\nrelease_result = '{}/lib{}.a'.format(dst, target)\nsubprocess.check_call(\n 'lipo -output {} -create {} {}'.format(\n release_result, release_arm, release_x86\n ),\n shell=True\n)\n\nprint(\n 'Install universal library done:\\n {}\\n {}'.format(\n debug_result, release_result\n )\n)\n","sub_path":"python/sugar_install_ios_library.py","file_name":"sugar_install_ios_library.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"226779029","text":"import numpy as np\nfrom itertools import permutations \n\n\nclass HilbertExplorer:\n \n '''\n p = 1 # order of Hilbert Curve\n t = 0.5 # current position on the curve\n l = [] # side length of space\n v = 1 # initial velocity\n dist = '1'\n '''\n\n def __init__(self, n, p=1, l=None, rho=1, latent=None):\n '''Intialize Hiblert tExplorer with:\n Args:\n n: Dimension of explored spapce\n l: side length of space \n Size of Explored Space: [-l, l]^ N\n rho: number of points return between on a segment\n '''\n\n if n <= 0:\n raise ValueError('N must be > 0')\n\n self.n = n\n self.p = p\n self.t = 0.5\n self.rho = rho\n self.v = 1\n self.dist = '1'\n\n if latent is not None:\n self.t = self.getT_from_coord(latent, self.p)\n print(\"T:\", self.t)\n \n if l is None: \n l = [[-1,1]]*n\n else:\n if (checkL(l, n)):\n self.l = l\n else:\n print('l is not initialized')\n self.l = [[-1,1]]*n\n \n self.l = l\n \n #default permutation is original coordinate\n self.Perm = list(range(self.n)) \n \n # maximum distance along curve\n #self.max_h = 2**(self.p * self.n) - 1\n self.max_h = (self.p*self.n) * '1'\n \n # maximum coordinate value in any dimension\n #self.max_x = 2**self.p - 1\n self.max_x = '1'*(self.p)\n \n \n ''' \n def printPerm(self):\n permList = list(permutations(range(self.n)))\n print(permList)\n '''\n \n def setL(self, l):\n # input a length of length l \n if (checkL(l, self.n)):\n self.l = l\n else:\n print('l is not initialized')\n \n #input an index to get order of permutation\n def setPermIndex(self, index):\n permList = list(permutations(range(self.n)))\n self.Perm = np.array(permList[index])\n \n #input the Permutation List\n def setPermIndex2(self, permIndexList):\n self.Perm = np.array(permIndexList)\n \n def setT(self, t):\n self.t = t\n self.dist = self._calDistFromT(self.t)\n \n # Step will modify current t\n def step(self):\n self.t += self.stepsize\n return self.t\n\n def update_stepsize(self):\n self.stepsize = (1/2**(self.p+5))\n\n \n def _calDistFromT(self, t):\n dist = (int(t * pow(10,10)) * (2 ** (self.n * self.p) - 1)) // pow(10,10)\n dist = format(dist, 'b')\n return dist\n \n def getCoord(self):\n self.dist = self._calDistFromT(self.t)\n \n # update max value\n self.max_h = '1' * (self.p*self.n)\n #self.max_h = 2**(self.p * self.n) - 1\n #self.max_x = 2**self.p - 1\n self.max_x = '1' * self.p\n \n cur_dist = self._calDistFromT(self.t) #t is in scale [0,1], dist is in scale[0, 2^(Np)-1]\n coord = self._coordinates_from_distance(cur_dist)\n perm_coord = self._getPermCoord(list(coord))\n norm_coord = self._coord_normalization(perm_coord)\n return (norm_coord)\n \n def setP(self, p):\n \n if p >= self.p:\n self.dist = self.dist + '0' * ((p-self.p)*self.n)\n else:\n self.dist = self.dist[:((p-self.p)*self.n)]\n #self.dist = int(self.dist * (2 ** (self.n * p) -1) // ((2 ** (self.n * self.p) -1))) \n #self.t = (self.dist * pow(10,10) // (2 ** (self.n * p) -1)) / pow(10,10)\n \n self.p = p\n #maximum distance along curve\n #self.max_h = 2**(self.p * self.n) - 1\n self.max_h = '1' * (self.p*self.n)\n # maximum coordinate value in any dimension\n #self.max_x = 2**self.p - 1\n self.max_x = '1' * (self.p)\n self.update_stepsize()\n\n\n def getNextCoord(self, v, t):\n dist = self._calDistFromT(t)\n v1 = format(v,'b')\n next_dist = _add_binary_nums(dist,v1)\n #next_dist = int(dist + v)\n return (self._coord_normalization(self._getPermCoord(self._coordinates_from_distance(next_dist))))\n\n def getNextCoordFromDist(self, v, dist):\n v1 = format(v,'b')\n next_dist = _add_binary_nums(dist,v1)\n return (self._coord_normalization(self._getPermCoord(self._coordinates_from_distance(next_dist))))\n\n def getCoordFromDist(self, dist):\n #return (self._getPermCoord(self._coord_normalization(self._coordinates_from_distance(dist))))\n return (self._coord_normalization(self._getPermCoord(self._coordinates_from_distance(dist))))\n\n def updateDist(self, v):\n v1 = format(v,'b')\n self.dist = _add_binary_nums(self.dist,v1)\n \n '''\n def getRandomCoord(self, t, p = None):\n if p is None:\n pass\n else:\n self.p = p\n \n self.t = t\n self.dist = t * (2 ** (self.n * self.p) - 1)\n \n # update max value\n self.max_h = 2**(self.p * self.n) - 1\n self.max_x = 2**self.p - 1\n \n dist = self.t * (2**(self.n*self.p)-1)\n dist1 = int(dist)\n dist2 = int(dist) + 1\n \n k = dist1 - dist\n coord = k * np.asarray(self._coordinates_from_distance(dist1)) + (1-k) * np.asarray(self._coordinates_from_distance(dist2)) + np.random.normal(size = self.n)\n return (self._getPermCoord(self._coord_normalization(coord)))\n '''\n \n def getNextT(self, v = None, p = None, t = None):\n #input v, get next T\n \n if v is None:\n pass\n else:\n self.v = v\n \n if p is None:\n pass\n else:\n self.p = p\n \n \n if t is None:\n pass\n else:\n self.t = t\n self.dist = self._calDistFromT(t)\n \n self.v = v\n \n #next_t = (self.t * (2**(self.n*self.p)-1) + self.v) / (2**(self.n*self.p)-1)\n next_t = self.t + self.v / (2**(self.n*self.p)-1)\n return next_t\n \n def _getPermCoord(self, coord):\n new_coord = [coord[i] for i in self.Perm]\n return np.array(new_coord)\n\n\n def _hilbert_integer_to_transpose(self, h):\n \"\"\"Store a hilbert integer (`h`) as its transpose (`x`).\n Args:\n h (int): integer distance along hilbert curve\n Returns:\n x (list): transpose of h\n (n components with values between 0 and 2**p-1)\n \"\"\"\n h_bit_str = h.zfill(self.p*self.n)\n #h_bit_str = _binary_repr(h, self.p*self.n)\n x = [int(h_bit_str[i::self.n], 2) for i in range(self.n)]\n return x\n\n def _transpose_to_hilbert_integer(self, x):\n \"\"\"Restore a hilbert integer (`h`) from its transpose (`x`).\n Args:\n x (list): transpose of h\n (n components with values between 0 and 2**p-1)\n Returns:\n h (int): integer distance along hilbert curve\n \"\"\"\n x_bit_str = [_binary_repr(x[i], self.p) for i in range(self.n)]\n h = int(''.join([y[i] for i in range(self.p) for y in x_bit_str]), 2)\n return h\n \n def _coord_normalization(self, coord):\n #norm_coord = np.array([((coord_x / (2**(self.p) -1 ))-0.5)*2*self.l for coord_x in coord])\n norm_coord = np.array([((coord[j]/(2**(self.p)-1)-0.5)*(self.l[j][1]-self.l[j][0])+(self.l[j][1]+self.l[j][0])/2) for j in range(self.n)])\n return norm_coord\n \n\n def _coordinates_from_distance(self, h):\n \"\"\"Return the coordinates for a given hilbert distance.\n Args:\n h (int): integer distance along hilbert curve\n Returns:\n x (list): transpose of h\n (n components with values between 0 and 2**p-1)\n \"\"\"\n ###---MAX-NEED-UPDATE---###\n if len(h) > len(self.max_h):\n raise ValueError('h={} is greater than 2**(p*N)-1={}'.format(h, self.max_h))\n #if h < 0:\n # raise ValueError('h={} but must be > 0'.format(h))\n\n x = self._hilbert_integer_to_transpose(h)\n Z = 2 << (self.p-1)\n\n # Gray decode by H ^ (H/2)\n t = x[self.n-1] >> 1\n for i in range(self.n-1, 0, -1):\n x[i] ^= x[i-1]\n x[0] ^= t\n\n # Undo excess work\n Q = 2\n while Q != Z:\n P = Q - 1\n for i in range(self.n-1, -1, -1):\n if x[i] & Q:\n # invert\n x[0] ^= P\n else:\n # exchange\n t = (x[0] ^ x[i]) & P\n x[0] ^= t\n x[i] ^= t\n Q <<= 1\n\n # done\n return x\n\n def getCoordList(self, t, p = None, rho = None):\n if rho is None:\n pass\n else:\n self.rho = rho\n \n if p is None:\n pass\n else:\n self.p = p\n \n self.t = t\n self.dist = t * (2 ** (self.n * self.p) - 1)\n \n # update max value\n self.max_h = 2**(self.p * self.n) - 1\n self.max_x = 2**self.p - 1\n \n dist = self.t * (2**(self.n*self.p)-1)\n #dist1 = int(dist)\n #dist2 = int(dist) + 2\n \n temp = self.rho - 1\n k_list = np.arange(0, 1+1/temp, 1/temp)\n \n #coord1 = np.asarray(self.coord_normalization(self.coordinates_from_distance(dist1)))\n #coord2 = np.asarray(self.coord_normalization(self.coordinates_from_distance(dist2)))\n coord1 = self.getCoord()\n \n #next_t = (t * (2**(self.n*self.p)-1) + 2) / (2**(self.n*self.p)-1)\n #print(t)\n #print(float(next_t))\n coord2 = self.getNextCoord(1, t)\n \n coord_list = [[ k * coord1[i] + (1-k) * coord2[i] for i in range(self.n)] for k in k_list] \n \n perm_list = [self._getPermCoord(coord) for coord in coord_list]\n\n return(coord_list)\n \n def getT_from_coord(self, coord, cur_p):\n test_coord = [co for co in coord]\n new_coord = [int((coord_x + 1) * ((2**cur_p)-1)/2) for coord_x in coord]\n cur_dist = self._distance_from_coordinates(new_coord, cur_p)\n new_t = cur_dist / (2 ** (self.n*cur_p) - 1)\n return(new_t)\n \n \n def _distance_from_coordinates(self, x_in, temp_p):\n \"\"\"Return the hilbert distance for a given set of coordinates.\n Args:\n x_in (list): transpose of h\n (n components with values between 0 and 2**p-1)\n Returns:\n h (int): integer distance along hilbert curve\n \"\"\"\n x = list(x_in)\n '''\n if len(x) != self.n:\n raise ValueError('x={} must have N={} dimensions'.format(x, self.n))\n if any(elx > self.max_x for elx in x):\n raise ValueError(\n 'invalid coordinate input x={}. one or more dimensions have a '\n 'value greater than 2**p-1={}'.format(x, self.max_x))\n if any(elx < 0 for elx in x):\n raise ValueError(\n 'invalid coordinate input x={}. one or more dimensions have a '\n 'value less than 0'.format(x))\n \n '''\n M = 1 << (temp_p - 1)\n # Inverse undo excess work\n Q = M\n while Q > 1:\n P = Q - 1\n for i in range(self.n):\n if x[i] & Q:\n x[0] ^= P\n else:\n t = (x[0] ^ x[i]) & P\n x[0] ^= t\n x[i] ^= t\n Q >>= 1\n # Gray encode\n for i in range(1, self.n):\n x[i] ^= x[i-1]\n t = 0\n Q = M\n while Q > 1:\n if x[self.n-1] & Q:\n t ^= Q - 1\n Q >>= 1\n for i in range(self.n):\n x[i] ^= t\n h = self._transpose_to_hilbert_integer(x)\n return h \n \ndef _binary_repr(num, width):\n \"\"\"Return a binary string representation of `num` zero padded to `width`\n bits.\"\"\"\n return format(num, 'b').zfill(width)\n\n\ndef _add_binary_nums(x,y):\n max_len = max(len(x), len(y))\n\n x = x.zfill(max_len)\n y = y.zfill(max_len)\n\n result = ''\n carry = 0\n\n for i in range(max_len-1, -1, -1):\n r = carry\n r += 1 if x[i] == '1' else 0\n r += 1 if y[i] == '1' else 0\n result = ('1' if r % 2 == 1 else '0') + result\n carry = 0 if r < 2 else 1 \n\n if carry !=0 : result = '1' + result\n\n return result.zfill(max_len)\n\ndef checkL(l,n):\n if (len(l) != n):\n return False\n \n for i in l:\n if (len(i) != 2):\n return False\n elif (i[0] >= i[1]):\n return False\n \n return True\n","sub_path":"flask-back/hilbert/HilbertExplorer.py","file_name":"HilbertExplorer.py","file_ext":"py","file_size_in_byte":12780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"486741098","text":"# https://leetcode-cn.com/problems/binary-tree-level-order-traversal/submissions/\n\n# 思路 仍然是二叉树的中序遍历,只需 1)借助队列 2)将每个节点与其层级数(作为元组)关联起来\n\n# 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\nfrom queue import Queue\nfrom typing import List\n\n\nclass Solution:\n def levelOrder(self, root: TreeNode) -> List[List[int]]:\n if not root:\n return []\n ans = []\n q = Queue()\n q.put((root, 1))\n while not q.empty():\n node, lev = q.get()\n if lev > len(ans):\n ans.append([])\n ans[lev - 1].append(node.val)\n if node.left:\n q.put((node.left, lev + 1))\n if node.right:\n q.put((node.right, lev + 1))\n return ans\n\n\n# 思路 2: 递归形式的层序遍历?\n# 官方给出的递归形式的遍历,其实并非真正的层序遍历,而是 DFS 加上层级信息而已\n\n\nclass Solution2:\n def levelOrder(self, root):\n levels = []\n\n if not root:\n return levels\n\n def helper(node, level):\n if len(levels) == level:\n levels.append([])\n\n levels[level].append([node.val])\n\n if node.left:\n helper(node.left, level + 1)\n if node.right:\n helper(node.right, level + 1)\n\n helper(root, 0)\n return levels","sub_path":"Week_02/id_40/leetcode_102_40.py","file_name":"leetcode_102_40.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"78031376","text":"\n\nfrom xai.brain.wordbase.nouns._oratory import _ORATORY\n\n#calss header\nclass _ORATORIES(_ORATORY, ):\n\tdef __init__(self,): \n\t\t_ORATORY.__init__(self)\n\t\tself.name = \"ORATORIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"oratory\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_oratories.py","file_name":"_oratories.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"262081827","text":"#!/usr/bin/python\nimport socket\nimport signal\nimport errno\n# from time import sleep\n\n\ndef HttpResponse(header, whtml):\n f = open(whtml)\n contxtlist = f.readlines()\n context = ''.join(contxtlist)\n response = \"%s %d\\n\\n%s\\n\\n\" % (header, len(context), context)\n f.close()\n return response\n\n\ndef sigIntHander(signo, frame):\n print('get signo# ', signo)\n global runflag\n runflag = False\n global lisfd\n lisfd.shutdown(socket.SHUT_RD)\n\n\nhostname = socket.gethostname()\nip = socket.gethostbyname(hostname)\nstrHost = ip\nHOST = strHost # socket.inet_pton(socket.AF_INET,strHost)\nPORT = 2333\nprint('[hostName]', hostname)\nprint('[hostIPAddress]', ip)\nprint('[port]', PORT)\n\nhttpheader = '''\\\nHTTP/1.1 200 OK\nContext-Type: text/html\nServer: Hanyuu Furude Http Server.\nContext-Length: '''\n\nlisfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nlisfd.bind((HOST, PORT))\nlisfd.listen(2)\n\nsignal.signal(signal.SIGINT, sigIntHander)\n\nrunflag = True\nwhile runflag:\n try:\n confd, addr = lisfd.accept()\n except socket.error as e:\n if e.errno == errno.EINTR:\n print('get a except EINTR')\n else:\n raise\n continue\n\n if runflag is False:\n break\n\n print(\"connect by \", addr)\n data = confd.recv(1024)\n if not data:\n break\n print(data)\n # confd.send(HttpResponse(httpheader, './index.html'))\n confd.send(bytes(HttpResponse(httpheader, './index.html'), 'utf-8'))\n confd.close()\nelse:\n print('runflag#', runflag)\n\nprint('Done')\n","sub_path":"studyNotes/python/HttpServer/httpServer.py","file_name":"httpServer.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"130490319","text":"import requests\nfrom bs4 import BeautifulSoup\n\nurl_end = ''\nprint('Write your request:')\nurl_end = input()\n\ndef make_url(url_end):\n\n url_base = 'https://ru.wikipedia.org/wiki/'\n\n url = url_base + url_end\n\n return url\n\n\ndef get_request(url_end):\n\n request = requests.get(make_url(url_end))\n\n with open('request.txt', 'w', encoding='utf8') as file:\n file.write(request.text)\n\n return request.text\n\n\ndef cleaning(url_end):\n\n soup = BeautifulSoup((get_request(url_end)), \"lxml\")\n\n main_information = soup.find('div', {'id' : 'bodyContent'})\n\n with open('request_clean.txt', 'w', encoding='utf8') as file:\n file.write(main_information.text)\n\n return main_information.text\n\nprint('\\nSuccess!\\nYou can open file request_clean.txt')\nprint('\\nYou can also print information on console\\nWrite yes or no:')\n\nchoice = input()\nif choice == 'yes':\n print(cleaning(url_end))\n print('\\nSee you later!')\nelse:\n cleaning(url_end)\n print('\\nOk, see you later!')\n","sub_path":"Other/Lab21_1.py","file_name":"Lab21_1.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"270878173","text":"\"\"\"\nUtilities for downloading and unpacking the CIFAR-10 dataset, originally published\nby Krizhevsky et al. and hosted here: https://www.cs.toronto.edu/~kriz/cifar.html\n\"\"\"\n\nimport os\nimport sys\nimport tarfile\nfrom six.moves import urllib\nimport numpy as np\n\ndef maybe_download_and_extract(data_dir, url='http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'):\n if not os.path.exists(os.path.join(data_dir, 'cifar-10-batches-py')):\n if not os.path.exists(data_dir):\n os.makedirs(data_dir)\n filename = url.split('/')[-1]\n filepath = os.path.join(data_dir, filename)\n if not os.path.exists(filepath):\n def _progress(count, block_size, total_size):\n sys.stdout.write('\\r>> Downloading %s %.1f%%' % (filename,\n float(count * block_size) / float(total_size) * 100.0))\n sys.stdout.flush()\n filepath, _ = urllib.request.urlretrieve(url, filepath, _progress)\n print()\n statinfo = os.stat(filepath)\n print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')\n tarfile.open(filepath, 'r:gz').extractall(data_dir)\n\ndef unpickle(file):\n fo = open(file, 'rb')\n if (sys.version_info >= (3, 0)):\n import pickle\n d = pickle.load(fo, encoding='latin1')\n else:\n import cPickle\n d = cPickle.load(fo)\n fo.close()\n return {'x': d['data'].reshape((10000,3,32,32)), 'y': np.array(d['labels']).astype(np.uint8)}\n\ndef load(filename, to_load):\n data = [np.loadtxt(filename + \"\" + str(x) + \".data\", delimiter=\",\", dtype=np.float32) for x in to_load]\n data = np.concatenate(data)\n data = np.reshape(data, (data.shape[0], 1, 1, data.shape[1]))\n mm = np.loadtxt(filename + \"m.data\", delimiter=\", \", dtype=np.float32)\n minz = mm[1] - 1\n maxz = mm[0]\n maxz -= minz\n data -= minz\n data /= maxz\n data *= 255\n return data\n \n\n\nclass DataLoader(object):\n \"\"\" an object that generates batches of CIFAR-10 data for training \"\"\"\n\n def __init__(self, data_dir, subset, batch_size, rng=None, shuffle=False, num=1):\n \"\"\" \n - data_dir is location where to store files\n - subset is train|test \n - batch_size is int, of #examples to load at once\n - rng is np.random.RandomState object for reproducibility\n \"\"\"\n\n self.data_dir = data_dir\n self.batch_size = batch_size\n self.shuffle = shuffle\n\n # create temporary storage for the data, if not yet created\n if not os.path.exists(data_dir):\n print('creating folder', data_dir)\n os.makedirs(data_dir)\n\n # load CIFAR-10 training data to RAM\n to_load = list(range(1, num)) + list(range(num+1, 11)) if subset == 'train' else [num]\n self.data = load(data_dir, to_load)\n print (np.max(self.data))\n print (np.min(self.data))\n self.p = 0 # pointer to where we are in iteration\n self.rng = np.random.RandomState(1) if rng is None else rng\n\n def get_observation_size(self):\n return self.data.shape[1:]\n\n def reset(self):\n self.p = 0\n\n def __iter__(self):\n return self\n\n def __next__(self, n=None):\n \"\"\" n is the number of examples to fetch \"\"\"\n if n is None: n = self.batch_size\n\n # on first iteration lazily permute all data\n if self.p == 0 and self.shuffle:\n inds = self.rng.permutation(self.data.shape[0])\n self.data = self.data[inds]\n\n # on last iteration reset the counter and raise StopIteration\n if self.p + n > self.data.shape[0]:\n self.reset() # reset for next time we get called\n raise StopIteration\n\n # on intermediate iterations fetch the next batch\n x = self.data[self.p : self.p + n]\n self.p += self.batch_size\n\n return x\n\n next = __next__ # Python 2 compatibility (https://stackoverflow.com/questions/29578469/how-to-make-an-object-both-a-python2-and-python3-iterator)\n\n\n","sub_path":"data/cifar10_data.py","file_name":"cifar10_data.py","file_ext":"py","file_size_in_byte":4031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"321427009","text":"from .storageManager.jsonMode import showDatabases\nfrom console import print_success, print_table \nfrom prettytable import PrettyTable\ndef executeShowDatabases(self):\n #self.intermediate.memory.append(self)\n x = PrettyTable()\n dbs = showDatabases()\n #self.messages.append(\"Databases:\")\n x.field_names = [\"Databases\"]\n for db in dbs:\n x.add_row([db])\n #self.messages.append(\"\\t\"+db)\n x.align = \"r\"\n x.border = True\n x.padding_width = 7\n print_success(\"QUERY\",\"Query carried out successfully\",2)\n print_table(\"QUERY TABLE\",x.get_string(),2)\n print(x) #show databases;","sub_path":"parser/fase2/team20/execution/executeShow.py","file_name":"executeShow.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"25"} +{"seq_id":"240619235","text":"#!/usr/bin/env python\n\nimport rospy\nfrom humanoid_league_msgs.msg import GameState\n\nclass GameStateChanger:\n def __init__(self):\n self.gamestate_pub = rospy.Publisher(\"gamestate\", GameState, queue_size = 2)\n self.gs_index = 0\n self.keep_playing = rospy.get_param('/changer/keep_playing')\n def perform(self):\n new_gs = GameState()\n if self.keep_playing:\n new_gs.gameState = 3\n else:\n new_gs.gameState = self.gs_index\n new_gs.allowedToMove = True\n rospy.loginfo('CURRENT GAMESTATE is {}'.format(self.gs_index))\n self.gamestate_pub.publish(new_gs)\n self.gs_index = (self.gs_index + 1) % 5\n\ndef main():\n rospy.init_node(\"GameStateChanger\")\n gs_changer = GameStateChanger()\n rate = rospy.Rate(0.5)\n while not rospy.is_shutdown():\n gs_changer.perform()\n rate.sleep()\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"src/simulator/game_state_changer.py","file_name":"game_state_changer.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"275096600","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\nimport logging\n\n\nimport logging\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n# create a file handler\nhandler = logging.FileHandler('log.txt')\nhandler.setLevel(logging.INFO)\n\n# create a logging format\nformatter = logging.Formatter('%(asctime)s %(levelname)s: %(funcName)s in %(filename)s wrote: %(message)s')\nhandler.setFormatter(formatter)\n\n# add the handlers to the logger\nlogger.addHandler(handler)\n\n\n\n\n\n\n# import threading\n# from _datetime import datetime\n# from collections import Iterable\n#\n#\n# def write_log(res):\n# now = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n# lock = threading.Lock()\n# with lock:\n# f = open('log.txt', 'a+', encoding='utf-8')\n#\n# if len(res) == 2:\n# f.write(now + ' Краулер выполнил запрос к базе:\\n')\n# f.write(res[1] + '\\n')\n# f.write('База вернула результат:\\n')\n# if isinstance(res[0], Iterable):\n# for t in res[0]:\n# f.write(str(t) + '\\n')\n# else:\n# f.write(res[0])\n# f.write('\\n')\n# elif len(res) == 3:\n# f.write(now + ' Краулер выполнил запрос к базе:\\n')\n# argums = ' '.join(map(lambda x: str(x), res[2]))\n# f.write(res[1] + ' аргументы: ' + argums + '\\n')\n# f.write('База вернула результат: ' +\n# str(res[0]) + '\\n')\n# f.write('\\n')\n","sub_path":"nerine_server/krauler/Logger.py","file_name":"Logger.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"56845932","text":"# -*- coding: utf-8 -*-\r\n'''\r\nHandles the config-file of the application.\r\n\r\n@author: Moritz Kurt Heilemann\r\n'''\r\nfrom os import path as ospath\r\nfrom configparser import SafeConfigParser\r\n#from module.datasource.sql_stmt_info import SQLStmtInfo\r\n#from module.datasource.sql_builder import Statement\r\n\r\n\r\n\r\n# define a private module variable\r\n__config_parser = None\r\n__local_db = None\r\n__config_file = \"config.cfg\"\r\n\r\ndef init(path):\r\n # load config data\r\n global __config_parser\r\n global __config_file\r\n # create config parser object to access and save program data\r\n __config_parser = SafeConfigParser()\r\n __config_file = ospath.join(path, __config_file)\r\n \r\n print('Verwendete Konfigurationsdatei: ' + str(__config_file)) \r\n \r\n # try to find the config file\r\n if __config_file not in __config_parser.read(__config_file):\r\n path = r'W:\\Org_AEPB1D\\AEPB1D_Mitarbeiter\\Mitarbeiter\\Kamfor\\WinPython-64bit-3.4.4.2\\projects\\ZRechner'\r\n __config_parser.read(ospath.join(path, __config_file))\r\n print('Config-Manager erfolgreich initialisiert!')\r\n \r\n \r\n # check if config file valid\r\n if not key_exists('DATA', 'path'):\r\n # if the file is not valid create a new one\r\n __config_parser.add_section('DATA')\r\n __config_parser.set('DATA', 'path', r'data\\zinsdaten.db')\r\n __config_parser.set('DATA', 'report_path', r'data\\report')\r\n __config_parser.add_section('LOG')\r\n __config_parser.set('LOG', 'file', r'log\\zrechner.log')\r\n __config_parser.add_section('APP')\r\n __config_parser.set('APP', 'path', path)\r\n \r\n # save the config file, overwrite\r\n with open(__config_file, 'w') as config_file:\r\n __config_parser.write(config_file)\r\n \r\n \r\ndef get(section, key):\r\n return __config_parser.get(section, key)\r\n \r\ndef set(section, key, value):\r\n global __config_parser\r\n __config_parser.set(section, key, value)\r\n # save changes\r\n with open(__config_file, 'w+', encoding='utf8') as configfile:\r\n __config_parser.write(configfile)\r\n \r\n# help function for easier use of this module\r\ndef get_path(key):\r\n return __config_parser.get('PATH', key)\r\n\r\n# returns True if the section, key exists\r\ndef key_exists(section, key):\r\n if __config_parser:\r\n return __config_parser.has_section(section) and __config_parser.has_option(section, key)\r\n else:\r\n return False\r\n \r\ndef set_database(db):\r\n global __local_db\r\n __local_db = db\r\n\r\ndef is_database_ready():\r\n global __local_db\r\n return __local_db\r\n \r\ndef __get_option_string(obj):\r\n if hasattr(obj, 'value'): \r\n return obj.value\r\n else:\r\n return obj\r\n","sub_path":"zinsrechner/model/config_manager.py","file_name":"config_manager.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"115691351","text":"from flask import Flask,request,render_template\n# from utils import upload_to_aws,bucket_name\nfrom healthcheck import HealthCheck\nimport os\n\n\napplication = app = Flask(__name__,template_folder='templates')\n\nApp_path = os.path.dirname(os.path.abspath(__file__))\n@app.route('/home')\ndef home():\n return render_template('index.html')\n\ndef app_status():\n \"\"\"\n added health check\n \"\"\"\n return True,\"App is up and running\"\n \nhealth = HealthCheck(app,\"/healthcheck\")\nhealth.add_check(app_status)\n\n\n\nif __name__ == '__main__':\n app.run(debug = True, host='0.0.0.0', port= 5000 )","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"214302293","text":"\nfrom Factory import Factory\nfrom inspect import isfunction\nfrom FDNode import *\n\nclass FDNodeFunc(FDNode):\n\n\tdef __init__(self, dic):\n\t\tsuper(FDNodeFunc, self).__init__(dic)\n\n\t\tfunc = dic['func']\n\t\tif isinstance(func, str):\n\t\t\tself.__func = Factory.reflectFunc(func)\n\t\telif isfunction(func):\n\t\t\tself.__func = func\n\t\telse:\n\t\t\tself.__func = None\n\n\t@property\n\tdef dic(self):\n\t\tsuperDic = super(FDNodeFunc, self).dic\n\t\tdic = {'func': self.func}\n\t\treturn {**superDic, **dic}\n\n\t@property\n\tdef func(self):\n\t\treturn self.__func\n\n\t@property\n\tdef funcKeys(self):\n\t\treturn self.func.__code__.co_varnames[:self.func.__code__.co_argcount]\n\n\t@property\n\tdef funcDefaults(self):\n\t\treturn self.func.__defaults__\n\n\tdef activite(self):\n\t\t# check if ready\n\t\tif self.status != 'ready':\n\t\t\treturn\n\t\t# get argsDict\n\t\targsDict = {k: e.data for e, k in self.parents}\n\t\t# invoke func\n\t\tretVal = self.func(**argsDict)\n\t\t# set retVal\n\t\tfor e, i in self.children:\n\t\t\te.data = retVal[i] if isinstance(retVal, tuple) else retVal\n\t\t\te.upToDate = True\n","sub_path":"Flow/src/FDNodeFunc.py","file_name":"FDNodeFunc.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"609434889","text":"# Copyright 2015 Intel Corporation\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport subprocess\n\nfrom tempest import clients\nfrom tempest.common import credentials_factory as common_creds\nfrom tempest.common import waiters\nfrom tempest.lib.common.utils import data_utils\nfrom tempest.scenario import manager\n\n\n# Using 2M hugepages\nHUGEPAGE_SIZE = 2048\n\n\ndef command(args, args2=None):\n '''\n Command: returns the output of the given command(s)\n Input: up to 2 commands\n Output: String representing the output of these commands\n\n Note: Using shell=False means that the following are unsupported:\n - Using pipes: Separate your commands\n i.e. \"cat /dev/null | grep anything\" ->\n [\"cat\", \"/dev/null\"], [\"grep\", \"anything\"]\n - Using wildcards: use glob to expand wildcards in dir listings\n i.e. [\"cat\", \"/proc/*info\"] ->\n [\"cat\"]+glob.glob(\"/proc/*info\")\n - String in commands: split manually\n e.g. awk {'print $2'} -> str.split()[1]\n '''\n if args2:\n process1 = subprocess.Popen(args, stdout=subprocess.PIPE,\n shell=False)\n\n process2 = subprocess.Popen(args2, stdin=process1.stdout,\n stdout=subprocess.PIPE, shell=False)\n # Allow process_curl to receive a SIGPIPE if process_wc exits.\n process1.stdout.close()\n return process2.communicate()[0]\n\n else:\n return subprocess.Popen(args,\n stdout=subprocess.PIPE,\n shell=False).communicate()[0]\n\n\ndef _get_number_free_hugepages(pagesize=HUGEPAGE_SIZE):\n # original command:\n # \"cat /sys/kernel/mm/hugepages/hugepages-${size}kB/\"\n return command([\"cat\",\n \"/sys/kernel/mm/hugepages/hugepages-{}kB/free_hugepages\"\n .format(pagesize)])\n\n\nclass TestHugepages(manager.ScenarioTest):\n run_ssh = True\n disk_config = 'AUTO'\n\n @classmethod\n def setup_credentials(cls):\n super(TestHugepages, cls).setup_credentials()\n cls.manager = clients.Manager(\n credentials=common_creds.get_configured_admin_credentials(\n fill_in=False))\n\n def setUp(self):\n super(TestHugepages, self).setUp()\n self.meta = {'hello': 'world'}\n self.accessIPv4 = '1.1.1.1'\n self.name = data_utils.rand_name('server')\n self.client = self.servers_client\n cli_resp = self.create_server(\n name=self.name,\n flavor=self.create_flavor_with_extra_specs(),\n )\n self.server_initial = cli_resp\n waiters.wait_for_server_status(self.client, self.server_initial['id'],\n 'ACTIVE')\n self.server = self.client.show_server(self.server_initial['id'])\n\n def create_flavor_with_extra_specs(self, name='hugepages_flavor', count=1):\n flavor_with_hugepages_name = data_utils.rand_name(name)\n flavor_with_hugepages_id = data_utils.rand_int_id(start=1000)\n ram = 64\n vcpus = 1\n disk = 0\n\n # set numa pagesize\n extra_specs = {\"hw:mem_page_size\": str(HUGEPAGE_SIZE)}\n # Create a flavor with extra specs\n resp = (self.flavors_client.\n create_flavor(name=flavor_with_hugepages_name,\n ram=ram, vcpus=vcpus, disk=disk,\n id=flavor_with_hugepages_id))\n self.flavors_client.set_flavor_extra_spec(flavor_with_hugepages_id,\n **extra_specs)\n self.addCleanup(self.flavor_clean_up, flavor_with_hugepages_id)\n self.assertEqual(200, resp.response.status)\n\n return flavor_with_hugepages_id\n\n def flavor_clean_up(self, flavor_id):\n resp = self.flavors_client.delete_flavor(flavor_id)\n self.assertEqual(resp.response.status, 202)\n self.flavors_client.wait_for_resource_deletion(flavor_id)\n\n def test_hugepage_backed_instance(self):\n # Check system hugepages\n hugepages_init = int(_get_number_free_hugepages())\n # Calc expected hugepages\n # flavor memory/hugepage_size, rounded up\n # create instance with hugepages flavor\n\n flavor_id = self.create_flavor_with_extra_specs(\"hugepages_flavor\")\n\n self.create_server(flavor=flavor_id, wait_until='ACTIVE')\n\n required_hugepages = 64 / (HUGEPAGE_SIZE / 1024.) # ram/hugepages_size\n expected_hugepages = int(hugepages_init - required_hugepages)\n actual_hugepages = int(_get_number_free_hugepages(HUGEPAGE_SIZE))\n\n self.assertEqual(required_hugepages, 32)\n self.assertEqual(expected_hugepages, actual_hugepages)\n","sub_path":"intel_nfv_ci_tests/tests/scenario/test_hugepages.py","file_name":"test_hugepages.py","file_ext":"py","file_size_in_byte":5324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"263735297","text":"print(\"웹 크롤링을 시작합니다.\")\nimport urllib.request\nfrom bs4 import BeautifulSoup\nfrom pandas import DataFrame\n\nmax_page=5\nlist_length=6\nTab='\\t'\nTab_l=9\nTab_m=5\nTab_s=3\n\nSeoul=0\nGyeonggi=0\nIncheon=0\nGangwon=0\nChungbuk=0\nChungnam=0\nDaejeon=0\nSejong=0\nJeonbuk=0\nJeonnam=0\nGwangju=0\nGyungbuk=0\nDaegu=0\nUlsan=0\nGyunnam=0\nBusan=0\nJeju=0\n\nstore_local=[]\nstore_addr=[]\nstore_name=[]\nstore_num=[]\n\npercent=[]\nfor page_idx in range(1,max_page+1):\n #페이지에 파라미터가 들어간다. get 방식 post방식 파라미터 물고 들어가는게 get 방식. 코드 안에 숨겨진 걸 찾는게 post방식\n URL='http://www.tonyburger.co.kr/shop_contents/myboard_list.htm?page=%s&myboard_code=sub3_1'%str(page_idx)\n print(\"Destination : %s\"%URL)\n\n response = urllib.request.urlopen(URL)\n soup = BeautifulSoup(response, 'html.parser')\n\n store_all = soup.find_all('td')#처가집은 a가 소문자. 나머지는 대문자 A. 왜인지는 모름\n data_len=len(store_all)\n\n for i in range(0, data_len, list_length): # data_len은 한 페이지를 읽어올 때마다 변하므로 페이지 안의 데이터가 적으면 그만큼 줄어든 길이가 들어옴\n store_local.append(store_all[i].text)# 지역구\n store_name.append(store_all[i+1].text)# 매장명\n store_addr.append(store_all[i+2].text)# 주소\n store_num.append(store_all[i+4].text)# 전화번호\n\nresult=[]\n\nprint(\"지역구\"+Tab*Tab_m+\"|\"+Tab*Tab_l+\"주소\"+Tab*Tab_l+\"|\"+Tab*Tab_s+\"매장명\"+Tab*Tab_s+\"|\"+Tab*Tab_s+\"전화번호\"+Tab*Tab_s)\nprint(\"-\"*149)\nfor i in range(len(store_addr)):\n result.append([store_local[i]]+[store_addr[i]]+[store_name[i]]+[store_num[i]])\n print(\"%s\\t|\\t\\t%50s\\t\\t|\\t\\t%12s\\t\\t|\\t\\t%s\" %(store_local[i].ljust(20,' '),store_addr[i].ljust(45,' '),store_name[i].ljust(12),store_num[i]))\n # print('{message:{fill}{align}{width}}'.format(message=store_num[i], fill=' ', align='<', width=12)) #미ㅏㄴ얾니ㅑㅇ러\ntony_table = DataFrame(result, columns=('지역구','주소','매장명','전화번호'))\ntony_table.to_csv(\"tony_list.csv\",encoding=\"cp949\",mode='w',index=False)\n\nSi_list=[\"서울특별시\",\"경기도\",\"인천광역시\",\"강원도\",\"충청북도\",\"충청남도\",\"대전광역시\",\"세종특별자치시시\",\"전라북도\",\"전라남도\",\"광주광역시\",\"경상북도\",\"대구광역시\",\"울산광역시\",\"경상남도\",\"부산광역시\",\"제주도특별자치도시\"]\n\nfor i in range(len(store_local)):\n Seoul += store_local[i].count(Si_list[0])\n Gyeonggi += store_local[i].count(Si_list[1])\n Incheon += store_local[i].count(Si_list[2])\n Gangwon += store_local[i].count(Si_list[3])\n Chungbuk += store_local[i].count(Si_list[4])\n Chungnam += store_local[i].count(Si_list[5])\n Daejeon += store_local[i].count(Si_list[6])\n Sejong += store_local[i].count(Si_list[7])\n Jeonbuk += store_local[i].count(Si_list[8])\n Jeonnam += store_local[i].count(Si_list[9])\n Gwangju += store_local[i].count(Si_list[10])\n Gyungbuk += store_local[i].count(Si_list[11])\n Daegu += store_local[i].count(Si_list[12])\n Ulsan += store_local[i].count(Si_list[13])\n Gyunnam +=store_local[i].count(Si_list[14])\n Busan += store_local[i].count(Si_list[15])\n Jeju += store_local[i].count(Si_list[16])\n\nJijeom_cnt_list=[Seoul,Gyeonggi,Incheon,Gangwon,Chungbuk,Chungnam,Daejeon,Sejong,Jeonbuk,Jeonnam,Gwangju,Gyungbuk,Daegu,Ulsan,Gyunnam,Busan,Jeju]\n\nresult2=[]\n\nfor i in range(len(Jijeom_cnt_list)):\n percent.append((Jijeom_cnt_list[i]/len(result))*100)\n percent[i] = \"%.2f %%\" % percent[i]\n result2.append([Si_list[i]] + [Jijeom_cnt_list[i]] + [percent[i]])\n##############################################################################\nresult2=sorted(result2, key=lambda r_list:r_list[1], reverse = True)\n#sorted를 이용하여 이중리스트에서 원하는 부분만을 가지고 정렬\n##############################################################################\n\nprint(\"\\n\\n검색된 레코드 수: %d\"%len(result))\nprint(\"지역별 현황\\n\\n\")\nprint(Tab*2+\"지역구\"+Tab*2+\"|\"+Tab+\"지점수\"+Tab+\"|\"+Tab+\"비율\"+Tab*2)\nprint(\"-\"*43)\n\nfor i in range(len(result2)):\n print(\"{0:<12}\".format(result2[i][0])+(Tab*2),end=\"\")\n print(\"|\\t%2s\\t\\t|\" % result2[i][1], end=\"\")\n print(\"\\t%7s\" % result2[i][2])\n\ntony_table = DataFrame(result2, columns=('지역구','지점수','비율'))\ntony_table.to_csv(\"tony_list2.csv\",encoding=\"cp949\",mode='w',index=False)\n#내림차순 정렬한 것을 csv로 다른 이름으로 저장하기\n\nprint(\"end\")","sub_path":"03_Data_Science/1.Collection/JSON/01_15/tonyburger2.py","file_name":"tonyburger2.py","file_ext":"py","file_size_in_byte":4562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"520419792","text":"def hasSingleCycle(array):\n # Write your code here.\n counter = 0\n currentIdx = 0\n while counter < len(array):\n if counter > 0 and currentIdx == 0:\n return False\n counter += 1\n currentIdx = getNextIdx(currentIdx, array)\n return currentIdx == 0\n\n\ndef getNextIdx(currentIdx, array):\n jump = array[currentIdx]\n nextIdx = (currentIdx + jump) % len(array)\n return nextIdx if nextIdx >= 0 else nextIdx + len(array)\n","sub_path":"AlgoExpert/hasSingleCycle.py","file_name":"hasSingleCycle.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"79641701","text":"# Author: Acer Zhang\n# Datetime:2019/8/25\n# Copyright belongs to the author.\n# Please indicate the source for reprinting.\n\nimport matplotlib.pyplot as plt\nfrom pylab import mpl\n\nmpl.rcParams['font.sans-serif'] = ['SimHei'] # 用来显示中文\n\n\ndef make_classify_info(file_path, limit=None):\n \"\"\"\n :param limit: Max x\n :param file_path:log file path\n\n Data Example:\n\n 2019-08-31-21-01\n 0.13099-0.54513-2.31339_0.16342-0.58067-2.27263_2.5705785751342773\n 0.17225-0.60655-2.25609_0.18672-0.62579-2.24045_2.529569625854492\n\n First line:Date\n Other :Data\n\n data Type: train_acc1 - train_acc5 - train_loss _ test_acc1 - test_acc5 - test_loss _ cost_time\n\n \"\"\"\n train_acc1 = []\n train_acc5 = []\n train_loss = []\n test_acc1 = []\n test_acc5 = []\n time_list = []\n with open(file_path, \"r\") as f:\n data = f.readlines()\n for line_id, info in enumerate(data):\n if line_id == 0:\n continue\n if line_id == limit:\n break\n info = info.split(\"_\")\n train_acc1.append([float(info[0].split(\"-\")[0])])\n train_acc5.append([float(info[0].split(\"-\")[1])])\n try:\n train_loss.append([float(info[0].split(\"-\")[2])])\n except ValueError:\n train_loss.append([0])\n test_acc1.append([float(info[1].split(\"-\")[0])])\n test_acc5.append([float(info[1].split(\"-\")[1])])\n time_list.append(float(info[2].split(\"-\")[0].replace(\"\\n\", \"\")))\n\n print(\"The time cost on this train is : \" + str(round(sum(time_list), 3)))\n epoch_list = [i + 1 for i in range(len(time_list))]\n return epoch_list, train_acc1, train_acc5, train_loss, test_acc1, test_acc5, time_list\n\n\ndef make_2label(epoch_list, a_list, b_list, title, y_label='accuracy rate', a_label='train', b_label='validation'):\n \"\"\"\n 制作出图\n :param epoch_list: X轴数据\n :param a_list: 数据A\n :param b_list: 数据B\n :param title: 标题\n :param y_label: Y轴标签\n :param a_label: 图例A\n :param b_label: 图例B\n :return: epoch_list, train_acc1, train_acc5, train_loss, test_acc1, test_acc5, time_list\n \"\"\"\n plt.title(title)\n plt.xlabel('Epoch')\n plt.ylabel(y_label)\n if y_label == 'accuracy rate':\n plt.ylim(0, 1)\n plt.plot(epoch_list, a_list, 'r', label=a_label)\n plt.plot(epoch_list, b_list, 'b', label=b_label)\n plt.legend(bbox_to_anchor=[1, 1])\n plt.grid()\n\n\ndataC1 = make_classify_info(\n r'F:\\Python3Notes\\Class_PaddlePaddle\\test06_Parameter_Adjustment\\test01_Optimizer\\2019-08-31-22-23C1.log',\n limit=30)\ndataC2 = make_classify_info(\n r'F:\\Python3Notes\\Class_PaddlePaddle\\test06_Parameter_Adjustment\\test01_Optimizer\\2019-08-31-22-22C2.log',\n limit=30)\n\n# epoch_list, train_acc1, train_acc5, train_loss, test_acc1, test_acc5, time_list\n# Top1\nmake_2label(epoch_list=dataC1[0], a_list=dataC1[1], b_list=dataC2[1], title=\"Cifar-10 Top1 Train 准确率\", a_label=\"SGD\",\n b_label=\"Adam\")\nplt.show()\n\nmake_2label(epoch_list=dataC1[0], a_list=dataC1[4], b_list=dataC2[4], title=\"Cifar-10 Top1 Validation 准确率\",\n a_label=\"SGD\",\n b_label=\"Adam\")\nplt.show()\n# Top5\nmake_2label(epoch_list=dataC1[0], a_list=dataC1[5], b_list=dataC2[5], title=\"Cifar-10 Top5 Validation 准确率\",\n a_label=\"SGD\",\n b_label=\"Adam\")\nplt.show()\n# Loss\nmake_2label(epoch_list=dataC1[0], a_list=dataC1[3], b_list=dataC2[3], title=\"Cifar-10 loss\", a_label=\"SGD\",\n b_label=\"Adam\", y_label=\"loss\")\nplt.show()\n","sub_path":"Class_PaddlePaddle/test06_Parameter_Adjustment/script/result_plt.py","file_name":"result_plt.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"498496254","text":"from setuptools import setup, find_packages\nimport os\n\nversion = '1.0'\n\nsetup(name='plone.app.event',\n version=version,\n description=\"Event content type for plone\",\n long_description=open(\"README.txt\").read() + \"\\n\" +\n open(os.path.join(\"docs\", \"HISTORY.txt\")).read(),\n # Get more strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Framework :: Plone\",\n \"Programming Language :: Python\",\n ],\n keywords='plone event',\n author='Plone Foundation',\n author_email='plone-developers@lists.sourceforge.net',\n url='/svn/plone/plone.app.event/',\n license='GPL',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['plone','plone.app'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n 'collective.calendarwidget',\n 'Plone',\n 'Products.DateRecurringIndex',\n ],\n extras_require={'test': ['interlude',]},\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"341913739","text":"from __future__ import absolute_import\nfrom google.appengine.ext import ndb\nfrom ferris.core.handler import Handler, route, route_with\nfrom oauth2client.client import OAuth2WebServerFlow\nfrom ferris.core.oauth2.user_credentials import UserCredentials as OAuth2UserCredentials\nfrom settings import app_config\n\n\nclass Oauth(Handler):\n\n @route\n def start(self, session):\n if not app_config['oauth2']['client_id'] or not app_config['oauth2']['client_secret']:\n self.response.write(\"OAuth2 has not been configured in settings.py\")\n return 500\n\n session = ndb.Key(urlsafe=session).get()\n callback_uri = self.uri(action='callback', _full=True)\n\n flow = OAuth2WebServerFlow(\n client_id=app_config['oauth2']['client_id'],\n client_secret=app_config['oauth2']['client_secret'],\n scope=session.scopes,\n redirect_uri=callback_uri)\n\n flow.params['state'] = session.key.urlsafe()\n\n if session.admin or session.force_prompt:\n flow.params['approval_prompt'] = 'force'\n\n uri = flow.step1_get_authorize_url()\n\n session.flow = flow\n session.put()\n\n return self.redirect(uri)\n\n @route_with(template='/oauth2callback')\n def callback(self):\n session = ndb.Key(urlsafe=self.request.params['state']).get()\n\n credentials = session.flow.step2_exchange(self.request.params['code'])\n\n # Delete any old credentials\n old_credentials = OAuth2UserCredentials.find_all(user=self.user, scopes=session.scopes, admin=session.admin)\n for x in old_credentials:\n x.key.delete()\n\n # Save the new ones\n user_credentials = OAuth2UserCredentials(\n user=self.user,\n scopes=session.scopes,\n credentials=credentials,\n admin=session.admin\n )\n\n user_credentials.put()\n session.key.delete() # No need for the session any longer\n\n return self.redirect(str(session.redirect))\n","sub_path":"ferris/handlers/oauth.py","file_name":"oauth.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"302639617","text":"import cv2\n\nimage = cv2.imread('H:/DownloadsFirefox/test.jpg')\nhsvImage = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\ncv2.imshow('original image', image)\ncv2.imshow('hsv Image', hsvImage)\ncv2.imwrite('H:/Code/Python/ImageManipulation/test1.jpg', hsvImage)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"Python/Functions/ImageManipulation/convertimagetohsv.py","file_name":"convertimagetohsv.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"394702512","text":"from bitmovin_api_sdk.models import CloudRegion\n\n\nclass EncodingListQueryParams(object):\n def __init__(self, offset=None, limit=None, sort=None, type_=None, status=None, cloud_region=None, encoder_version=None, name=None, search=None):\n # type: (int, int, string_types, string_types, string_types, CloudRegion, string_types, string_types, string_types) -> None\n super(EncodingListQueryParams, self).__init__()\n\n self.offset = offset\n self.limit = limit\n self.sort = sort\n self.type = type_\n self.status = status\n self.cloud_region = cloud_region\n self.encoder_version = encoder_version\n self.name = name\n self.search = search\n\n @property\n def openapi_types(self):\n types = {\n 'offset': 'int',\n 'limit': 'int',\n 'sort': 'string_types',\n 'type': 'string_types',\n 'status': 'string_types',\n 'cloud_region': 'CloudRegion',\n 'encoder_version': 'string_types',\n 'name': 'string_types',\n 'search': 'string_types'\n }\n\n return types\n\n @property\n def attribute_map(self):\n attributes = {\n 'offset': 'offset',\n 'limit': 'limit',\n 'sort': 'sort',\n 'type': 'type',\n 'status': 'status',\n 'cloud_region': 'cloudRegion',\n 'encoder_version': 'encoderVersion',\n 'name': 'name',\n 'search': 'search'\n }\n\n return attributes\n","sub_path":"bitmovin_api_sdk/encoding/encodings/encoding_list_query_params.py","file_name":"encoding_list_query_params.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"101787837","text":"import socket\nfrom sys import getsizeof\n\nQUIT = 'quit'.encode('utf-8')\n\ndef getHost():\n host = input(\"Enter the IP address of the server: \")\n port = input(\"Enter the port to connect to the server on: \")\n return (host, int(port))\n\ndef Main():\n message = ''\n server = getHost()\n\n sock = socket.socket()\n\n sock.connect(server)\n sock.setblocking(0)\n\n while message != QUIT:\n message = input(\"You: \").encode('utf-8')\n\n if getsizeof(message) <= 2048:\n sock.sendall(message)\n else:\n print(\"Message exceeds maximum length.\")\n \n try:\n message = sock.recv(2048)\n print(\"Them: \" + message.decode('utf-8'))\n except:\n pass\n\n sock.close()\n\nMain()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"478181113","text":"import numpy as np\r\nimport scipy.io\r\n\r\ndef loss(Y, U, V, l):\r\n \"\"\" Squared-loss function.\r\n\r\n Evaluate the loss for training samples in Y, using U and V. The loss consists of a regularization portion\r\n (left_L) and a squared-loss term (right_L).\r\n \r\n Args:\r\n Y: (array). An array with dimensions m by n, non-zero values at Y[m,n] represent training samples.\r\n U: (array). An array with dimensions k by m, where k is the number of latent factors.\r\n V: (array). An array with dimensions k by n, where k is the number of latent factors.\r\n l: (scalar). Regularization strength.\r\n\r\n Returns:\r\n L: (scalar). Squared loss with regularization.\r\n \r\n Raises:\r\n None\r\n \"\"\"\r\n \r\n m = Y.shape[0]\r\n n = Y.shape[1]\r\n \r\n # squared loss\r\n index = (Y != 0)\r\n Y_hat= np.dot(np.transpose(U), V)\r\n L = 0.5 * np.sum(np.square(Y[index] - Y_hat[index]))\r\n\r\n return L\r\n\r\n\r\n\"\"\" main \"\"\"\r\nk = 20 # number of latent factors\r\nl = 0 # regularization lambda\r\n\r\n\r\ndata = np.load('models/model_' + str(k) + '_' + str(l) + '.npz')\r\nepoch = data['epoch']\r\nY = data['Y']\r\nU = data['U']\r\nV = data['V']\r\ntrain = data['train']\r\nl = data['l']\r\n\r\nm = Y.shape[0]\r\nn = Y.shape[1]\r\n \r\nY_hat = np.dot(np.transpose(U), V)\r\n\r\nE_in = loss(Y, U, V, l)\r\n# E_out = loss(Y_test, U, V, l)\r\n\r\nprint('k = ' + str(k))\r\nprint('l = ' + str(l))\r\nprint('E_in = ' + str(E_in))\r\n# print('E_out = ' + str(E_out))\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"src/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"320404762","text":"from cv2 import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimg=cv2.imread('img/bird.jpg')\nrows,cols,ch=img.shape\npts1=np.float32([[50,50],[200,50],[50,200]])\npts2=np.float32([[10,100],[200,50],[100,250]])\nM=cv2.getAffineTransform(pts1,pts2)\ndst=cv2.warpAffine(img,M,(cols,rows))\n\ncv2.imshow('img',dst)\ncv2.waitKey(0)\ncv2.destroyAllWindow()","sub_path":"14 几何变换/14-4.py","file_name":"14-4.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"564370671","text":"# -*- encoding:utf-8 -*-\n\"\"\"\nViews and functions for serving static files. These are only to be used\nduring development, and SHOULD NOT be used in a production setting.\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport mimetypes\nimport os\nimport posixpath\nimport re\nimport stat\nimport StringIO\nfrom django.conf import settings\nfrom django.http import (\n FileResponse, Http404, HttpResponse, HttpResponseNotModified,\n HttpResponseRedirect,\n)\nfrom django.template import Context, Engine, TemplateDoesNotExist, loader\nfrom django.utils.http import http_date, parse_http_date\nfrom django.utils.six.moves.urllib.parse import unquote\nfrom django.utils.translation import ugettext as _, ugettext_lazy\nfrom PIL import Image, ImageDraw, ImageFont, ImageEnhance\n\n\ndef serve(request, path, document_root=None, show_indexes=False):\n \"\"\"\n Serve static files below a given point in the directory structure.\n\n To use, put a URL pattern such as::\n\n from django.views.static import serve\n\n url(r'^(?P.*)$', serve, {'document_root': '/path/to/my/files/'})\n\n in your URLconf. You must provide the ``document_root`` param. You may\n also set ``show_indexes`` to ``True`` if you'd like to serve a basic index\n of the directory. This index view will use the template hardcoded below,\n but if you'd like to override it, you can create a template called\n ``static/directory_index.html``.\n \"\"\"\n path = posixpath.normpath(unquote(path))\n path = path.lstrip('/')\n newpath = ''\n for part in path.split('/'):\n if not part:\n # Strip empty path components.\n continue\n drive, part = os.path.splitdrive(part)\n head, part = os.path.split(part)\n if part in (os.curdir, os.pardir):\n # Strip '.' and '..' in path.\n continue\n newpath = os.path.join(newpath, part).replace('\\\\', '/')\n if newpath and path != newpath:\n return HttpResponseRedirect(newpath)\n true_path = newpath\n size_mode = (0, 0)\n rotate_mode = 0\n width_mode = 0\n height_mode = 0\n long_mode = 0\n short_mode = 0\n max_mode = 0\n cut_mode = (0, 0)\n cut_px_mode = (0, 0)\n cut_py_mode = (0, 0)\n u_mode = (0, 0)\n size_regex = re.compile(r'(.*/?.+\\..+)_(\\d+)X(\\d+)')\n rotate_regex = re.compile(r'(.*/?.+\\..+)_A(\\d+)')\n width_regex = re.compile(r'(.*/?.+\\..+)_W(\\d+)')\n height_regex = re.compile(r'(.*/?.+\\..+)_H(\\d+)')\n thumb_regex = re.compile(r'(.*/?.+\\..+)_THUMB')\n long_regex = re.compile(r'(.*/?.+\\..+)_L(\\d+)')\n short_regex = re.compile(r'(.*/?.+\\..+)_S(\\d+)')\n max_regex = re.compile(r'(.*/?.+\\..+)_MAX(\\d+)')\n cut_regex = re.compile(r'(.*/?.+\\..+)_C(\\d+)-(\\d+)')\n cut_px_regex = re.compile(r'(.*/?.+\\..+)_PX(\\d+)-(\\d+)')\n cut_py_regex = re.compile(r'(.*/?.+\\..+)_PY(\\d+)-(\\d+)')\n u_regex = re.compile(r'(.*/?.+\\..+)_U(\\d+)-(\\d+)')\n if size_regex.findall(newpath):\n true_path = size_regex.findall(newpath)[0][0]\n size_mode = (int(size_regex.findall(newpath)[0][1]),\n int(size_regex.findall(newpath)[0][2]))\n if rotate_regex.findall(newpath):\n true_path = rotate_regex.findall(newpath)[0][0]\n rotate_mode = int(rotate_regex.findall(newpath)[0][1])\n if width_regex.findall(newpath):\n true_path = width_regex.findall(newpath)[0][0]\n width_mode = int(width_regex.findall(newpath)[0][1])\n if height_regex.findall(newpath):\n true_path = height_regex.findall(newpath)[0][0]\n height_mode = int(height_regex.findall(newpath)[0][1])\n if thumb_regex.findall(newpath):\n true_path = thumb_regex.findall(newpath)[0]\n width_mode = 1000\n if long_regex.findall(newpath):\n true_path = long_regex.findall(newpath)[0][0]\n long_mode = int(long_regex.findall(newpath)[0][1])\n if short_regex.findall(newpath):\n true_path = short_regex.findall(newpath)[0][0]\n short_mode = int(short_regex.findall(newpath)[0][1])\n if max_regex.findall(newpath):\n true_path = max_regex.findall(newpath)[0][0]\n max_mode = int(max_regex.findall(newpath)[0][1])\n if cut_regex.findall(newpath):\n true_path = cut_regex.findall(newpath)[0][0]\n cut_mode = (int(cut_regex.findall(newpath)[0][1]),\n int(cut_regex.findall(newpath)[0][2]))\n if cut_px_regex.findall(newpath):\n true_path = cut_px_regex.findall(newpath)[0][0]\n cut_px_mode = (int(cut_px_regex.findall(newpath)[0][1]),\n int(cut_px_regex.findall(newpath)[0][2]))\n if cut_py_regex.findall(newpath):\n true_path = cut_py_regex.findall(newpath)[0][0]\n cut_py_mode = (int(cut_py_regex.findall(newpath)[0][1]),\n int(cut_py_regex.findall(newpath)[0][2]))\n if u_regex.findall(newpath):\n true_path = u_regex.findall(newpath)[0][0]\n u_mode = (int(u_regex.findall(newpath)[0][1]),\n int(u_regex.findall(newpath)[0][2]))\n fullpath = os.path.join(document_root, true_path)\n if os.path.isdir(fullpath):\n if show_indexes:\n return directory_index(newpath, fullpath)\n raise Http404(_(\"Directory indexes are not allowed here.\"))\n if not os.path.exists(fullpath):\n raise Http404(_('\"%(path)s\" does not exist') % {'path': fullpath})\n # Respect the If-Modified-Since header.\n statobj = os.stat(fullpath)\n content_type, encoding = mimetypes.guess_type(fullpath)\n content_type = content_type or 'application/octet-stream'\n try:\n image_file = Image.open(fullpath)\n out_image = image_file\n if size_mode != (0, 0):\n resize_rate = min(image_file.width * 1.0 / size_mode[0],\n image_file.height * 1.0 / size_mode[1])\n target_size = (int(image_file.width / resize_rate + 0.5),\n int(image_file.height / resize_rate + 0.5))\n out_image = image_file.resize(target_size, resample=Image.LANCZOS)\n out_image = out_image.crop((int(\n 0.5 * (target_size[0] - size_mode[0])), int(\n 0.5 * (target_size[1] - size_mode[1])),\n int(0.5 * (\n target_size[0] + size_mode[0])),\n int(0.5 * (\n target_size[1] + size_mode[1]))))\n if rotate_mode != 0:\n out_image = image_file.rotate(rotate_mode, expand=True)\n if width_mode != 0:\n width = width_mode\n height = int(image_file.height * width * 1.0 / image_file.width)\n out_image = image_file.resize((width, height))\n if height_mode != 0:\n height = height_mode\n width = int(image_file.width * height * 1.0 / image_file.height)\n out_image = image_file.resize((width, height))\n if long_mode != 0:\n if image_file.width >= image_file.height:\n width = long_mode\n height = int(image_file.height * width * 1.0 / image_file.width)\n out_image = image_file.resize((width, height))\n else:\n height = long_mode\n width = int(image_file.width * height * 1.0 / image_file.height)\n out_image = image_file.resize((width, height))\n if short_mode != 0:\n if image_file.width <= image_file.height:\n width = short_mode\n height = int(image_file.height * width * 1.0 / image_file.width)\n out_image = image_file.resize((width, height))\n else:\n height = short_mode\n width = int(image_file.width * height * 1.0 / image_file.height)\n out_image = image_file.resize((width, height))\n if max_mode != 0:\n if image_file.width >= image_file.height:\n if image_file.width > max_mode:\n width = max_mode\n height = int(\n image_file.height * width * 1.0 / image_file.width)\n out_image = image_file.resize((width, height))\n else:\n if image_file.height > max_mode:\n height = max_mode\n width = int(\n image_file.width * height * 1.0 / image_file.height)\n out_image = image_file.resize((width, height))\n if cut_mode != (0, 0):\n width = int(image_file.width * 1.0 / (cut_mode[1] + 1))\n height = int(image_file.height * 1.0 / (cut_mode[0] + 1))\n out_image = image_file.crop((0, 0, width, height))\n if cut_px_mode != (0, 0):\n height = int(image_file.height * 1.0 / (cut_px_mode[0] + 1))\n out_image = image_file.crop((0, (cut_px_mode[1] - 1) * height,\n image_file.width,\n cut_px_mode[1] * height))\n if cut_py_mode != (0, 0):\n width = int(image_file.width * 1.0 / (cut_py_mode[0] + 1))\n out_image = image_file.crop(((cut_py_mode[1] - 1) * width, 0,\n cut_py_mode[1] * width,\n image_file.height))\n if u_mode != (0, 0):\n if image_file.width >= image_file.height:\n if u_mode[0] < image_file.width < u_mode[1]:\n width = u_mode[0]\n height = int(\n image_file.height * width * 1.0 / image_file.width)\n out_image = image_file.resize((width, height))\n elif image_file >= u_mode[1]:\n width = image_file.width / 2\n height = image_file.height / 2\n out_image = image_file.resize((width, height))\n else:\n if u_mode[0] < image_file.height < u_mode[1]:\n height = u_mode[0]\n width = int(\n image_file.width * height * 1.0 / image_file.height)\n out_image = image_file.resize((width, height))\n elif image_file >= u_mode[1]:\n height = image_file.height / 2\n width = image_file.width / 2\n out_image = image_file.resize((width, height))\n out = StringIO.StringIO()\n out_image.save(out, image_file.format)\n s = out.getvalue()\n out.close()\n response = FileResponse(s, content_type=content_type)\n response[\"Last-Modified\"] = http_date(statobj.st_mtime)\n response[\"Content-Length\"] = len(s)\n if encoding:\n response[\"Content-Encoding\"] = encoding\n return response\n except Exception:\n response = FileResponse(open(fullpath, 'rb'), content_type=content_type)\n response[\"Last-Modified\"] = http_date(statobj.st_mtime)\n if stat.S_ISREG(statobj.st_mode):\n response[\"Content-Length\"] = statobj.st_size\n if encoding:\n response[\"Content-Encoding\"] = encoding\n return response\n\n\nDEFAULT_DIRECTORY_INDEX_TEMPLATE = \"\"\"\n{% load i18n %}\n\n\n \n \n \n \n {% blocktrans %}Index of {{ directory }}{% endblocktrans %}\n \n \n

      {% blocktrans %}Index of {{ directory }}{% endblocktrans %}

      \n
        \n {% if directory != \"/\" %}\n
      • ../
      • \n {% endif %}\n {% for f in file_list %}\n
      • {{ f }}
      • \n {% endfor %}\n
      \n \n\n\"\"\"\ntemplate_translatable = ugettext_lazy(\"Index of %(directory)s\")\n\n\ndef directory_index(path, fullpath):\n try:\n t = loader.select_template([\n 'static/directory_index.html',\n 'static/directory_index',\n ])\n except TemplateDoesNotExist:\n t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)\n files = []\n for f in os.listdir(fullpath):\n if not f.startswith('.'):\n if os.path.isdir(os.path.join(fullpath, f)):\n f += '/'\n files.append(f)\n c = Context({\n 'directory': path + '/',\n 'file_list': files,\n })\n return HttpResponse(t.render(c))\n\n\ndef was_modified_since(header=None, mtime=0, size=0):\n \"\"\"\n Was something modified since the user last downloaded it?\n\n header\n This is the value of the If-Modified-Since header. If this is None,\n I'll just return True.\n\n mtime\n This is the modification time of the item we're talking about.\n\n size\n This is the size of the item we're talking about.\n \"\"\"\n try:\n if header is None:\n raise ValueError\n matches = re.match(r\"^([^;]+)(; length=([0-9]+))?$\", header,\n re.IGNORECASE)\n header_mtime = parse_http_date(matches.group(1))\n header_len = matches.group(3)\n if header_len and int(header_len) != size:\n raise ValueError\n if int(mtime) > header_mtime:\n raise ValueError\n except (AttributeError, ValueError, OverflowError):\n return True\n return False\n","sub_path":"demo/serve.py","file_name":"serve.py","file_ext":"py","file_size_in_byte":13378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"26"} +{"seq_id":"21051375","text":"#\r\n# @lc app=leetcode id=1008 lang=python3\r\n#\r\n# [1008] Construct Binary Search Tree from Preorder Traversal\r\n#\r\n# https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/description/\r\n#\r\n# algorithms\r\n# Medium (72.70%)\r\n# Likes: 217\r\n# Dislikes: 10\r\n# Total Accepted: 14.2K\r\n# Total Submissions: 19.4K\r\n# Testcase Example: '[8,5,1,7,10,12]'\r\n#\r\n# Return the root node of a binary search tree that matches the given preorder\r\n# traversal.\r\n# \r\n# (Recall that a binary search tree is a binary tree where for every node, any\r\n# descendant of node.left has a value < node.val, and any descendant of\r\n# node.right has a value > node.val.  Also recall that a preorder traversal\r\n# displays the value of the node first, then traverses node.left, then\r\n# traverses node.right.)\r\n# \r\n# \r\n# \r\n# Example 1:\r\n# \r\n# \r\n# Input: [8,5,1,7,10,12]\r\n# Output: [8,5,10,1,7,null,12]\r\n# \r\n# \r\n# \r\n# \r\n# \r\n# Note: \r\n# \r\n# \r\n# 1 <= preorder.length <= 100\r\n# The values of preorder are distinct.\r\n# \r\n# \r\n#\r\n# Definition for a binary tree node.\r\n# class TreeNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n\r\nclass Solution:\r\n def bstFromPreorder(self, preorder: List[int]) -> TreeNode:\r\n n=len(preorder)\r\n if n==0:\r\n return None\r\n return self.helper(preorder, 0, n)\r\n\r\n def helper(self, preorder:List[int], st:int, end:int)->TreeNode:\r\n if st