diff --git "a/6338.jsonl" "b/6338.jsonl" new file mode 100644--- /dev/null +++ "b/6338.jsonl" @@ -0,0 +1,602 @@ +{"seq_id":"580145016","text":"import RPi.GPIO as GPIO\n\nimport os\n\nfrom globaldefs import *\nfrom platformdefs import *\n\nfrom ledscanner import *\nfrom ledcontroller import *\nfrom buttonmonitor import *\n\nimport time\nimport subprocess\nfrom threading import Thread\n\nclass CommandSwitch(object):\n\n terminate = False\n\n def __init__(self, prompts_dir, termination_event, sound_player, led_scanner):\n self.__command_underway = False\n self.__prompts_dir = prompts_dir\n self.__termination_event = termination_event\n self.__sound_player = sound_player\n self.__led_scanner = led_scanner\n\n\n def process_switch_events(self):\n try:\n while not CommandSwitch.terminate:\n GPIO.wait_for_edge(ROTARY_SWITCH_PIN, GPIO.FALLING)\n print('control button pressed')\n\n if self.__sound_player.is_active():\n # sound player is active, meaning a sound is playing\n\n if self.__sound_player.is_paused():\n # if paused and the button remains pressed...\n time.sleep(1.0)\n if GPIO.input(ROTARY_SWITCH_PIN) == GPIO.LOW:\n # button was held down while playing/paused,\n # stop this sound file and resume scanning\n # awaiting a new sound choice\n # sound player is paused, quit playing\n self.__sound_player.quit_playing()\n else:\n p = self.__sound_player.toggle_playback()\n else:\n # sound playing, not paused\n p = self.__sound_player.toggle_playback()\n else:\n # Player is not active (leds are scanning)...\n # Wait 2 seconds to see if command button remains pressed\n time.sleep(2.0)\n if GPIO.input(ROTARY_SWITCH_PIN) == GPIO.LOW:\n # we are ending one way or another.\n # prevent the main thread from starting a sound\n self.__termination_event.clear()\n\n # command button held down for 2 sec\n # see if we shut down or go to configuration restart\n turnoff_all_leds()\n self.__led_scanner.stop_scanning()\n turnoff_all_leds()\n\n # shutdown-admin-resume.wav\n #\n # Soundbox is shutting down.\n # Choose one of the three following options\n # Press the red button to power down.\n # or\n # Press the green button to configure Soundbox and\n # restart it\n # or\n # Press any other button to restart Soundbox\n subprocess.Popen(['omxplayer',\n '-o','alsa:'+ALSA_DEVICE_NAME,\n self.__prompts_dir+'shutdown-admin-resume.wav'],\n stdin=subprocess.PIPE,\n stdout=None,stderr=None)\n\n led_controller = LEDController(1000, (LED_GREEN, LED_RED))\n led_thread = Thread(target=led_controller.run)\n led_thread.start()\n\n\n button_monitor = ButtonMonitor(1)\n button_pattern = button_monitor.get_button_presses()\n\n led_controller.go_dark()\n\n if button_pattern[0] == BUTTON_GREEN:\n\n led_controller.light_up(BUTTON_GREEN)\n time.sleep(1.0)\n print('restarting in config mode')\n self.__sound_player.close()\n os.system('sudo /etc/init.d/soundbox restart')\n\n else:\n if button_pattern[0] == BUTTON_RED:\n\n print('shutting down now')\n led_controller.light_up(BUTTON_RED)\n time.sleep(1.0)\n os.system('sudo shutdown now')\n\n else:\n os.system('sudo /etc/init.d/soundbox restart2')\n\n\n\n#\n\n # sleep just a bit in case of switch bounce. this is because\n # we are using edge detection here, and if the switch bounces,\n # one press could cause two or more detectable edges.\n time.sleep(0.2)\n except Exception as ex:\n print('CommandSwitch: exception: ', ex)\n","sub_path":"commandswitch.py","file_name":"commandswitch.py","file_ext":"py","file_size_in_byte":4874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"333815184","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Feb 28 19:46:22 2021\r\n\r\n@author: maeng\r\n\"\"\"\r\nimport os\r\nimport numpy as np\r\nimport datetime\r\nimport pickle\r\nimport gc\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom PIL import Image\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torchvision\r\nimport torchvision.transforms as T\r\n\r\nos.chdir(\"D:/masked-CNN\")\r\nfrom cam import scorecam_vggnet_batch\r\nfrom cam import scorecam_resnet_batch\r\nfrom cam import scorecam_vggnet_original\r\n\r\ndef load_image(image_path): \r\n return Image.open(image_path).convert('RGB')\r\n\r\ndef softmax(x):\r\n return F.softmax(torch.tensor(x), dim = 0).numpy()\r\n\r\n##################################################################################################################\r\n# #\r\n# Parameter #\r\n# #\r\n################################################################################################################## \r\n\r\ntransform_test = T.Compose([\r\n T.Resize(256),\r\n T.CenterCrop(224),\r\n T.ToTensor(),\r\n T.Normalize([0.4831, 0.4918, 0.4248], [0.1839, 0.1833, 0.1943]),\r\n])\r\n\r\nUSE_CUDA = torch.cuda.is_available()\r\nDEVICE = torch.device(\"cuda\" if USE_CUDA else \"cpu\")\r\n\r\nalias = \"VGG16\"\r\n\r\nDATA_PATH = \"D:/data/CUB_200_2011\"\r\nLOAD_PATH = \"D:/masked-CNN/CUB_prop/\"\r\nSAVE_PATH = os.path.join(\"D:/masked-CNN/CUB_mask\", alias)\r\nMODEL_PATH = os.path.join(DATA_PATH, \"record\", alias)\r\n\r\nTARGET_LAYER = 42\r\nNUM_CLASS = 200\r\nBATCH_SIZE = 50\r\n\r\n##################################################################################################################\r\n# #\r\n# Data Load #\r\n# #\r\n################################################################################################################## \r\n\r\n#Prop Data\r\ndata = pd.read_csv(os.path.join(LOAD_PATH, \"CUB_img_\" + alias + \"_prop.csv\"), encoding = \"UTF-8-sig\")\r\n\r\ndata[\"top1_correct\"] = data.top1_pred == data.target\r\ndata[\"top5_correct\"] = data.apply(lambda x : x.target in eval(x.top5_pred), axis = 1)\r\n\r\nsum(data.top1_correct) / len(data)\r\nsum(data.top5_correct) / len(data)\r\n\r\nidx = [str(i) for i in range(0, NUM_CLASS)]\r\n\r\n#Best epoch\r\nlast = str(max(set([int(i.split(\".\")[0].split(\"_\")[1]) for i in os.listdir(os.path.join(MODEL_PATH))])))\r\ntest_acc = eval(open(os.path.join(MODEL_PATH, alias + \"_\" + last + \"_test_acc.txt\"), 'r').read())\r\nepoch = max(test_acc.items(), key = lambda x : x[1])[0]\r\nprint(\"Best All Epoch : \" + str(epoch) + \" Acc : \" + str(test_acc[epoch]))\r\n\r\nepoch = max([i for i in test_acc.items() if i[0] % 5 == 0], key = lambda x : x[1])[0]\r\nprint(\"Best Save Epoch : \" + str(epoch) + \" Acc : \" + str(test_acc[epoch]))\r\n\r\n#VGG\r\nmodel = torchvision.models.vgg16_bn(pretrained = False)\r\nmodel.classifier[-1] = nn.Linear(in_features = model.classifier[-1].in_features, out_features = 200, bias = True)\r\nmodel.load_state_dict(torch.load(os.path.join(MODEL_PATH, alias + \"_\" + str(epoch) + \".pth\")))\r\nmodel = model.to(DEVICE)\r\n\r\n#RESNET\r\n# model = torchvision.models.resnet50(pretrained = False)\r\n# model.fc = nn.Linear(in_features = model.fc.in_features, out_features = NUM_CLASS, bias = True)\r\n# model.load_state_dict(torch.load(os.path.join(MODEL_PATH, alias + \"_\" + str(epoch) + \".pth\")))\r\n# model = model.to(DEVICE)\r\n\r\nmodel.eval()\r\n##################################################################################################################\r\n# #\r\n# Mask image #\r\n# #\r\n################################################################################################################## \r\nif not os.path.exists(SAVE_PATH):\r\n os.makedirs(SAVE_PATH)\r\n\r\ni = 0\r\nfor i in range(0, len(data)):\r\n\r\n start = datetime.datetime.now()\r\n\r\n picture = load_image(data.path[i])\r\n img = transform_test(picture).unsqueeze(0).to(DEVICE)\r\n label = torch.tensor(eval(data.topk_pred[i]))\r\n \r\n #score_cam1 = scorecam_vggnet_original.ScoreCam(model, TARGET_LAYER)\r\n #saliency_map1 = score_cam1.generate_cam(img, label[0])\r\n\r\n score_cam = scorecam_vggnet_batch.ScoreCam(model, TARGET_LAYER)\r\n saliency_map = score_cam.generate_cam(img, label, BATCH_SIZE)\r\n \r\n meta = dict()\r\n meta[\"img\"] = data.img[i]\r\n meta[\"path\"] = data.path[i]\r\n meta[\"target\"] = data.target[i]\r\n meta[\"origin_pred\"] = data.top1_pred[i]\r\n meta[\"mask_label\"] = label.cpu().numpy()\r\n meta[\"saliency_map\"] = saliency_map\r\n \r\n with open(os.path.join(SAVE_PATH, \"CUB_\" + alias + \"_img_\" + str(i) + \".pickle\"), 'wb') as file:\r\n pickle.dump(meta, file)\r\n file.close()\r\n \r\n del meta, file\r\n gc.collect()\r\n \r\n end = datetime.datetime.now()\r\n \r\n print(i, (end - start).total_seconds())\r\n\r\n\r\n","sub_path":"CUB_saliency_map.py","file_name":"CUB_saliency_map.py","file_ext":"py","file_size_in_byte":5639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"64235011","text":"__author__ = 'jingxuan'\n\nimport unittest\nfrom genomeapi.api import ODThroughLink\nimport json\n\nclass TestODThroughLink(unittest.TestCase):\n def test_od_through_link(self):\n od_thr_link = ODThroughLink(\"URL\",\"token\")\n od_thr_link.dates(begin_date=\"2018-07-11\")\n od_thr_link.time_series_reference(\"arrival\")\n od_thr_link.link(\"NSW513133313\")\n od_thr_link.dimension_facets(\"mode\")\n od_thr_link.granularity(period=\"PT6H\")\n od_thr_link.aggregate(metric=\"unique_agents\", described_as=\"unique_agents\")\n od_thr_link.aggregate(metric=\"total_records\", described_as=\"total_records\")\n od_thr_link.dumps()\n res = od_thr_link.json\n expected ={\n \"dates\": {\n \"type\": \"single\",\n \"value\": \"2018-07-11\"\n },\n \"timeSeriesReference\": \"arrival\",\n \"links\": [\n \"NSW513133313\"\n ],\n \"dimensionFacets\": [\n \"mode\"\n ],\n \"queryGranularity\": {\n \"type\": \"period\",\n \"period\": \"PT6H\",\n \"timeZone\": \"Australia/Sydney\"\n },\n \"aggregations\": [\n {\n \"metric\": \"unique_agents\",\n \"type\": \"hyperUnique\",\n \"describedAs\": \"unique_agents\"\n },\n {\n \"metric\": \"total_records\",\n \"type\": \"longSum\",\n \"describedAs\": \"total_records\"\n }]\n }\n\n self.assertEqual(json.loads(res), expected)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"testing/api/test_od_through_link.py","file_name":"test_od_through_link.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"560348475","text":"# view created 11:33 19.07.2018\n\nimport pandas as pd\nfrom providers import getProvider\n\nprovider = getProvider(\n name = 'daily-minimum-temperatures'\n)\n\nview = pd.DataFrame(provider.getData());\nview.set_index('date');\n","sub_path":"app/electron/git/flaff/example-temperature-analysis.view/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"483014755","text":"from datetime import timedelta\nfrom requests.auth import HTTPBasicAuth\nfrom django.core.exceptions import ValidationError\nfrom django.utils import timezone\nfrom django.core.cache import cache\nfrom ..settings import (\n WFRS_GATEWAY_COMPANY_ID,\n WFRS_GATEWAY_ENTITY_ID,\n WFRS_GATEWAY_API_HOST,\n WFRS_GATEWAY_CONSUMER_KEY,\n WFRS_GATEWAY_CONSUMER_SECRET,\n WFRS_GATEWAY_CLIENT_CERT_PATH,\n WFRS_GATEWAY_PRIV_KEY_PATH,\n)\nfrom ..security import encrypt_pickle, decrypt_pickle\nimport requests\nimport logging\nimport uuid\n\nlogger = logging.getLogger(__name__)\n\n\nclass BearerTokenAuth(requests.auth.AuthBase):\n def __init__(self, api_key):\n self.api_key = api_key\n\n def __call__(self, request):\n request.headers[\"Authorization\"] = \"Bearer %s\" % self.api_key\n return request\n\n\nclass WFRSAPIKey:\n def __init__(self, api_key, expires_on):\n self.api_key = api_key\n self.expires_on = expires_on\n\n @property\n def is_expired(self):\n # Force key rotation 10 minutes before it actually expires\n expires_on = self.expires_on - timedelta(minutes=10)\n now = timezone.now()\n return now >= expires_on\n\n @property\n def ttl(self):\n return int((self.expires_on - timezone.now()).total_seconds())\n\n def __str__(self):\n return \"\" % self.expires_on\n\n\nclass WFRSGatewayAPIClient:\n company_id = WFRS_GATEWAY_COMPANY_ID\n entity_id = WFRS_GATEWAY_ENTITY_ID\n api_host = WFRS_GATEWAY_API_HOST\n consumer_key = WFRS_GATEWAY_CONSUMER_KEY\n consumer_secret = WFRS_GATEWAY_CONSUMER_SECRET\n client_cert_path = WFRS_GATEWAY_CLIENT_CERT_PATH\n priv_key_path = WFRS_GATEWAY_PRIV_KEY_PATH\n scopes = [\n \"PLCCA-Prequalifications\",\n \"PLCCA-Applications\",\n \"PLCCA-Payment-Calculations\",\n \"PLCCA-Transactions-Authorization\",\n \"PLCCA-Transactions-Charge\",\n \"PLCCA-Transactions-Authorization-Charge\",\n \"PLCCA-Transactions-Return\",\n \"PLCCA-Transactions-Cancel-Authorization\",\n \"PLCCA-Transactions-Void-Return\",\n \"PLCCA-Transactions-Void-Sale\",\n \"PLCCA-Transactions-Timeout-Authorization-Charge\",\n \"PLCCA-Transactions-Timeout-Return\",\n \"PLCCA-Account-Details\",\n ]\n\n cache_version = 1\n\n @property\n def cache_key(self):\n return \"wfrs-gateway-api-key-{api_host}-{consumer_key}\".format(\n api_host=self.api_host, consumer_key=self.consumer_key\n )\n\n def api_get(self, path, **kwargs):\n return self.make_api_request(\"get\", path, **kwargs)\n\n def api_post(self, path, **kwargs):\n return self.make_api_request(\"post\", path, **kwargs)\n\n def make_api_request(self, method, path, client_request_id=None, **kwargs):\n url = \"https://{host}{path}\".format(host=self.api_host, path=path)\n # Setup authentication\n auth = BearerTokenAuth(self.get_api_key().api_key)\n cert = None\n if self.client_cert_path and self.priv_key_path:\n cert = (self.client_cert_path, self.priv_key_path)\n # Build headers\n request_id = (\n str(uuid.uuid4()) if client_request_id is None else str(client_request_id)\n )\n headers = {\n \"request-id\": request_id,\n \"gateway-company-id\": self.company_id,\n \"gateway-entity-id\": self.entity_id,\n }\n if client_request_id is not None:\n headers[\"client-request-id\"] = str(client_request_id)\n # Send request\n logger.info(\n \"Sending WFRS Gateway API request. URL=[%s], RequestID=[%s]\",\n url,\n request_id,\n )\n request_fn = getattr(requests, method)\n resp = request_fn(url, auth=auth, cert=cert, headers=headers, **kwargs)\n logger.info(\n \"WFRS Gateway API request returned. URL=[%s], RequestID=[%s], Status=[%s]\",\n url,\n request_id,\n resp.status_code,\n )\n # Check response for errors\n if resp.status_code == 400:\n resp_data = resp.json()\n errors = []\n for err in resp_data.get(\"errors\", []):\n exc = ValidationError(err[\"description\"], code=err[\"error_code\"])\n errors.append(exc)\n raise ValidationError(errors)\n # Return response\n return resp\n\n def get_api_key(self):\n # Check for a cached key\n key_obj = self.get_cached_api_key()\n if key_obj is None:\n key_obj = self.generate_api_key()\n self.store_cached_api_key(key_obj)\n return key_obj\n\n def get_cached_api_key(self):\n # Try to get an API key from cache\n encrypted_obj = cache.get(self.cache_key, version=self.cache_version)\n if encrypted_obj is None:\n return None\n # Try to decrypt the object we got from cache\n try:\n key_obj = decrypt_pickle(encrypted_obj)\n except Exception as e:\n logger.exception(e)\n return None\n # Check if the key is expired\n if key_obj.is_expired:\n return None\n # Return the key\n return key_obj\n\n def store_cached_api_key(self, key_obj):\n # Pickle and encrypt the key object\n encrypted_obj = encrypt_pickle(key_obj)\n # Store it in Django's cache for later\n cache.set(\n self.cache_key, encrypted_obj, key_obj.ttl, version=self.cache_version\n )\n\n def generate_api_key(self):\n url = \"https://{host}/oauth2/v1/token\".format(host=self.api_host)\n auth = HTTPBasicAuth(self.consumer_key, self.consumer_secret)\n cert = (self.client_cert_path, self.priv_key_path)\n req_data = {\n \"grant_type\": \"client_credentials\",\n \"scope\": \" \".join(self.scopes),\n }\n resp = requests.post(url, auth=auth, cert=cert, data=req_data)\n resp.raise_for_status()\n resp_data = resp.json()\n expires_on = timezone.now() + timedelta(seconds=resp_data[\"expires_in\"])\n logger.info(\"Generated new WFRS API Key. ExpiresIn=[%s]\", expires_on)\n key_obj = WFRSAPIKey(api_key=resp_data[\"access_token\"], expires_on=expires_on)\n return key_obj\n","sub_path":"src/wellsfargo/connector/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":6238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"383065308","text":"\"\"\"empty message\n\nRevision ID: d03ba82d2923\nRevises: 48ac60350ca4\nCreate Date: 2020-04-10 04:59:10.477213\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'd03ba82d2923'\ndown_revision = '48ac60350ca4'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('user', schema=None) as batch_op:\n batch_op.add_column(sa.Column('email', sa.String(length=80), nullable=True))\n batch_op.create_unique_constraint(None, ['email'])\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('user', schema=None) as batch_op:\n batch_op.drop_constraint(None, type_='unique')\n batch_op.drop_column('email')\n\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/d03ba82d2923_.py","file_name":"d03ba82d2923_.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"489007770","text":"import codecs\nimport re\n\nf = codecs.open(\"python_text.rtf\", 'r')\nfile1 = f.read()\n\npythoninputbychunksbylinesbykeywords = []\n\npythoninputbychunksbylinesbykeywords = [x.split('\\n') for x in file1.split('\\n\\n\\n')] # this is still just lines\n\n#print(pythoninputbychunksbylinesbykeywords)\n\npythoninputbychunksbylinesbykeywords = [[x for x in y if x != \"\"] for y in pythoninputbychunksbylinesbykeywords] # no need for \"\\n\" just \"\" (see visualizer)\n\n#print(pythoninputbychunksbylinesbykeywords)\n\npythonbinarybychunksbylinesbykeywords = [[0 for x in y] for y in pythoninputbychunksbylinesbykeywords]\n\n#print(pythonbinarybychunksbylinesbykeywords)\n\n# Python keywords\n# Removed:\n# 'elif ' because of \"if\"\n# 'for ' because of \"or\"\n# 'not ' because always compounded with another\n# Changes:\n# ' ' added to end of all but \"print\", \"yield\", \"None\", \"True\", and \"False\"\n# 'else:' used instead of 'else '\nkeywords = [\n 'and ', 'assert ', 'break ', 'class ', 'continue ', 'def ',\n 'del ', 'else:', 'except ', 'exec ', 'finally ',\n 'from ', 'global ', 'if ', 'import ', 'in ',\n 'is ', 'lambda ', 'or ', 'pass ', 'print',\n 'raise ', 'return ', 'try ', 'while ' , 'yield',\n 'None', 'True', 'False',\n ]\n\nfor chunk in pythoninputbychunksbylinesbykeywords:\n chunkindex = pythoninputbychunksbylinesbykeywords.index(chunk)\n for line in chunk:\n lineindex = pythoninputbychunksbylinesbykeywords[chunkindex].index(line)\n q = []\n for x in keywords:\n if re.findall(x, line) != []:\n q.append(x)\n print(q)\n if (len(q)) == 1:\n pythonbinarybychunksbylinesbykeywords[chunkindex][lineindex] = [0, 1]\n elif (len(q)) == 2:\n pythonbinarybychunksbylinesbykeywords[chunkindex][lineindex] = [0, 1, 0, 1] # line was previously: 0; now it is: [0, 1, 0, 1]\n elif \"=\" in line:\n pythonbinarybychunksbylinesbykeywords[chunkindex][lineindex] = 1\n\nprint(pythoninputbychunksbylinesbykeywords)\nprint(pythonbinarybychunksbylinesbykeywords)","sub_path":"python_keywords.py","file_name":"python_keywords.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"535910333","text":"# ./crackme.hooked XXXXXXXXXXXXXXXXXXXXX\n# Hook add\n# Damn_YoU_Got_The_Flag\n# XXXXXXXXXXXXXXXXXXXXX\n# You got it !!\nimport lief\n\ncrackme = lief.parse(\"crackme.bin\")\nhook = lief.parse(\"hook\")\n\nsegment_added = crackme.add(hook.segments[0])\n\nmy_memcmp = hook.get_symbol(\"my_memcmp\")\nmy_memcmp_addr = segment_added.virtual_address + my_memcmp.value\n\ncrackme.patch_pltgot('memcmp', my_memcmp_addr)\ncrackme.write(\"crackme.hooked\")\n","sub_path":"05_ELF_infect_plt-got/hook_pltgot.py","file_name":"hook_pltgot.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"57786523","text":"# Copyright (C) 2012 Robert Lanfear and Brett Calcott\n#\n# This program is free software: you can redistribute it and/or modify it under\n# the terms of the GNU General Public License as published by the Free Software\n# Foundation, either version 3 of the License, or (at your option) any later\n# version.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n# details. You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n# PartitionFinder also includes the PhyML program, the RAxML program, and the\n# PyParsing library, all of which are protected by their own licenses and\n# conditions, using PartitionFinder implies that you agree with those licences\n# and conditions as well.\n\nimport hashlib\nimport cPickle as pickle\nimport subset\n\nimport logging\nlog = logging.getLogger(\"subset_ops\")\n\n\ndef subset_unique_name(subset):\n \"\"\"Return a unique string based on the subsets columns (which are unique)\"\"\"\n\n # Use pickle to give us a string from the object\n pickled_columns = pickle.dumps(subset.column_set, -1)\n\n # Now get an md5 hash from this. There is some vanishingly small chance that\n # we'll get the same thing. Google \"MD5 Hash Collision\"\n return hashlib.md5(pickled_columns).hexdigest()\n\n\ndef merge_subsets(subset_list):\n \"\"\"Take a set of subsets and merge them together\"\"\"\n columns = set()\n\n # We just need the columns\n for sub in subset_list:\n columns |= sub.column_set\n\n return subset.Subset(sub.cfg, columns)\n\n\ndef subsets_overlap(subset_list):\n columns = set()\n\n for sub in subset_list:\n # If the intersection is non-empty...\n if sub.column_set & columns:\n return True\n columns |= sub.column_set\n\n return False\n\n\ndef has_missing(subset_list):\n return False\n\n\ndef split_subset(a_subset, cluster_list):\n \"\"\"Takes a subset and splits it according to a cluster list,\n then returns the subsets resulting from the split\"\"\"\n # Take each site from the first list and add it to a new\n \n subset_list = a_subset.columns\n likelihood_list = a_subset.site_lnls_GTRG\n subset_columns = []\n site_likelihoods = []\n list_of_subsets = []\n for cluster in cluster_list:\n list_of_sites = []\n likelihood_for_site = []\n for site in cluster:\n list_of_sites.append(subset_list[site - 1])\n likelihood_for_site += (likelihood_list[site - 1])\n subset_columns.append(set(list_of_sites))\n site_likelihoods.append(likelihood_for_site)\n # print subset_columns\n tracker = 0\n for column_set in subset_columns:\n new_subset = subset.Subset(a_subset.cfg, column_set)\n if new_subset.best_lnl > 0:\n new_subset.fabricated = True\n list_of_subsets.append(new_subset)\n new_subset.site_lnls_GTRG = site_likelihoods[tracker]\n tracker += 1\n\n return list_of_subsets\n\ndef merge_fabricated_subsets(subset_list):\n '''Allows the merging of fabricated subsets and the preservation of their\n centroids and lnls'''\n columns = set()\n lnl = 0\n centroid = []\n\n # Figure out how many dimensions the centroid is\n centroid_dim = len(subset_list[0].centroid)\n for i in range(centroid_dim):\n centroid.append(0)\n\n for sub in subset_list:\n columns |= sub.column_set\n lnl += sub.best_lnl\n number = 0\n for observation in centroid:\n observation += sub.centroid[number]\n number += 1\n\n # Now just take the average of each centroid to be the centroid of the new\n # subset\n centroid = [x/len(subset_list) for x in centroid]\n\n new_sub = subset.Subset(sub.cfg, columns)\n\n # Add the centroid and sum of the lnls to the subset. TODO: create\n # functions to update these variables in the subset rather than messing\n # with them directly\n new_sub.centroid = centroid\n new_sub.lnl = lnl\n return new_sub\n","sub_path":"partfinder/subset_ops.py","file_name":"subset_ops.py","file_ext":"py","file_size_in_byte":4144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"13100540","text":"from collections import Counter\nfrom heapq import heappush, heappop\n\nclass Solution(object):\n def topKFrequent(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n\n result = []\n\n h = []\n for i, n in Counter( nums ).iteritems():\n heappush( h, ( -n, i ) )\n\n for j in xrange( k ):\n _, i = heappop( h )\n result.append( i )\n\n return result\n","sub_path":"347.py","file_name":"347.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"312663901","text":"from typing import List\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nclass Solution:\n def isCousins(self, root: TreeNode, x: int, y: int) -> bool:\n\n res = [[root.val, 0]] if root.val == x or root.val == y else []\n res = self.search(root.left, x, y, 1, root.val, res)\n res = self.search(root.right, x, y, 1, root.val, res)\n print(res)\n if res[0][1] == res[1][1] and res[0][0] != res[1][0]: return True\n return False\n\n\n def search(self, root: TreeNode, x: int, y: int, depth:int, ancestor_val: int, val_list: List[List[int]]):\n if not root: return val_list\n\n if root.val == x or root.val == y:\n val_list.append([ancestor_val, depth])\n\n val_list = self.search(root.left, x, y, depth + 1, root.val, val_list)\n val_list = self.search(root.right, x, y, depth + 1, root.val, val_list)\n return val_list","sub_path":"leetcode/data_structure/tree/cousins_in_binary_tree.py","file_name":"cousins_in_binary_tree.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"578556663","text":"import cv2\nimport numpy as np\n\n\nimg = cv2.imread('10.jpg')\nnewImage=np.zeros(img.shape,np.uint8)\ngray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\ni, j, k = img.shape\n\nfor x in xrange(i):\n for y in xrange(j):\n R = img[x,y,2] * 0.256 + img[x,y,1] * 0.145 + img[x,y,0] * 0.342\n G = img[x,y,2] * 0.349 + img[x,y,1] * 0.686 + img[x,y,0] * 0.168\n B = img[x,y,2] * 0.272 + img[x,y,1] * 0.534 + img[x,y,0] * 0.131\n if R > 255:\n newImage[x,y,2] = 255\n else:\n newImage[x,y,2] = R\n if G > 255:\n newImage[x,y,1] = 255\n else:\n newImage[x,y,1] = G\n if B > 255:\n newImage[x,y,0] = 255\n else:\n newImage[x,y,0] = B\n\ncv2.imwrite('/home/vishnu/sepia_bw/12.jpg',newImage)\ncv2.imwrite('/home/vishnu/sepia_bw/13.jpg',gray)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"color/bw_sep.py","file_name":"bw_sep.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"183780479","text":"import unittest\n\nfrom unittest.mock import patch, MagicMock\nfrom requests import Request\nfrom tekore.sender import (\n Sender, TransientSender, SingletonSender, PersistentSender, RetryingSender\n)\n\n\nclass TestSender(unittest.TestCase):\n def test_sender_cannot_be_instantiated(self):\n with self.assertRaises(TypeError):\n Sender()\n\n\nclass MockSessionFactory:\n prepare_return = 'prepared'\n\n def __init__(self):\n self.instances = []\n\n def __call__(self, *args, **kwargs):\n mock = MagicMock()\n mock.__enter__ = MagicMock(return_value=mock)\n mock.prepare_request = MagicMock(return_value=self.prepare_return)\n\n self.instances.append(mock)\n return mock\n\n\nclass TestSingletonSender(unittest.TestCase):\n def test_instances_share_session(self):\n s1 = SingletonSender()\n s2 = SingletonSender()\n self.assertTrue(s1.session is s2.session)\n\n def test_request_prepared(self):\n mock = MockSessionFactory()\n with patch('tekore.sender.SingletonSender.session', mock()):\n s = SingletonSender()\n r = Request()\n s.send(r)\n mock.instances[0].prepare_request.assert_called_with(r)\n\n def test_keywords_passed_to_session(self):\n mock = MockSessionFactory()\n kwargs = dict(k1='k1', k2='k2')\n with patch('tekore.sender.SingletonSender.session', mock()):\n s = SingletonSender(**kwargs)\n r = Request()\n s.send(r)\n mock.instances[0].send.assert_called_with(\n mock.prepare_return,\n **kwargs\n )\n\n\ndef test_request_prepared(sender_type):\n mock = MockSessionFactory()\n with patch('tekore.sender.Session', mock):\n s = sender_type()\n r = Request()\n s.send(r)\n mock.instances[0].prepare_request.assert_called_with(r)\n\n\ndef test_keywords_passed_to_session(sender_type):\n mock = MockSessionFactory()\n kwargs = dict(k1='k1', k2='k2')\n with patch('tekore.sender.Session', mock):\n s = sender_type(**kwargs)\n s.send(Request())\n mock.instances[0].send.assert_called_with(mock.prepare_return, **kwargs)\n\n\nclass TestPersistentSender(unittest.TestCase):\n @patch('tekore.sender.Session', MagicMock)\n def test_session_is_reused(self):\n s = PersistentSender()\n sess1 = s.session\n s.send(Request())\n s.send(Request())\n sess2 = s.session\n self.assertTrue(sess1 is sess2)\n\n def test_instances_dont_share_session(self):\n s1 = PersistentSender()\n s2 = PersistentSender()\n self.assertTrue(s1.session is not s2.session)\n\n def test_request_prepared(self):\n test_request_prepared(PersistentSender)\n\n def test_keywords_passed_to_session(self):\n test_keywords_passed_to_session(PersistentSender)\n\n\nclass TestTransientSender(unittest.TestCase):\n def test_session_is_not_reused(self):\n mock = MockSessionFactory()\n with patch('tekore.sender.Session', mock):\n s = TransientSender()\n s.send(Request())\n s.send(Request())\n self.assertEqual(len(mock.instances), 2)\n\n def test_request_prepared(self):\n test_request_prepared(TransientSender)\n\n def test_keywords_passed_to_session(self):\n test_keywords_passed_to_session(TransientSender)\n\n\ndef ok_response() -> MagicMock:\n response = MagicMock()\n response.status_code = 200\n return response\n\n\ndef rate_limit_response(retry_after: int = 1) -> MagicMock:\n response = MagicMock()\n response.status_code = 429\n response.headers = {'Retry-After': retry_after}\n return response\n\n\ndef failed_response() -> MagicMock:\n response = MagicMock()\n response.status_code = 500\n return response\n\n\nclass TestRetryingSender(unittest.TestCase):\n def test_rate_limited_request_retried_after_set_seconds(self):\n time = MagicMock()\n sender = MagicMock()\n\n fail = rate_limit_response()\n success = ok_response()\n sender.send.side_effect = [fail, success]\n\n s = RetryingSender(sender=sender)\n with patch('tekore.sender.time', time):\n s.send(Request())\n time.sleep.assert_called_once_with(1)\n\n def test_failing_request_but_no_retries_returns_failed(self):\n sender = MagicMock()\n fail = failed_response()\n success = ok_response()\n sender.send.side_effect = [fail, success]\n\n s = RetryingSender(sender=sender)\n r = s.send(Request())\n self.assertTrue(r is fail)\n\n def test_failing_request_retried_max_times(self):\n sender = MagicMock()\n fail = failed_response()\n success = ok_response()\n sender.send.side_effect = [fail, fail, fail, success]\n\n s = RetryingSender(retries=2, sender=sender)\n with patch('tekore.sender.time', MagicMock()):\n s.send(Request())\n self.assertEqual(sender.send.call_count, 3)\n\n def test_retry_returns_on_first_success(self):\n sender = MagicMock()\n fail = failed_response()\n success = ok_response()\n sender.send.side_effect = [fail, fail, success, fail, success]\n\n s = RetryingSender(retries=5, sender=sender)\n with patch('tekore.sender.time', MagicMock()):\n s.send(Request())\n self.assertEqual(sender.send.call_count, 3)\n\n def test_rate_limited_retry_doesnt_decrease_retry_count(self):\n sender = MagicMock()\n\n fail = failed_response()\n rate = rate_limit_response()\n success = ok_response()\n sender.send.side_effect = [fail, rate, fail, success]\n\n s = RetryingSender(retries=2, sender=sender)\n with patch('tekore.sender.time', MagicMock()):\n s.send(Request())\n\n self.assertEqual(sender.send.call_count, 4)\n\n\nclass TestSenderDefaults(unittest.TestCase):\n def setUp(self):\n from tekore import sender\n self.old_default_type = sender.default_sender_type\n self.old_default_instance = sender.default_sender_instance\n self.old_default_kwargs = sender.default_requests_kwargs\n\n def test_modify_default_sender_type(self):\n instance = MagicMock()\n type_mock = MagicMock(return_value=instance)\n\n from tekore import sender, Spotify\n sender.default_sender_type = type_mock\n\n s = Spotify()\n self.assertIs(s.sender, instance)\n\n def test_modify_default_sender_instance(self):\n instance = MagicMock()\n\n from tekore import sender, Spotify\n sender.default_sender_instance = instance\n\n s = Spotify()\n self.assertIs(s.sender, instance)\n\n def test_instance_has_precedence_over_type(self):\n instance = MagicMock()\n type_mock = MagicMock(return_value=MagicMock())\n\n from tekore import sender, Spotify\n sender.default_sender_type = type_mock\n sender.default_sender_instance = instance\n\n s = Spotify()\n self.assertIs(s.sender, instance)\n\n def test_retrying_sender_as_default_type_recurses(self):\n from tekore import sender\n sender.default_sender_type = sender.RetryingSender\n\n with self.assertRaises(RecursionError):\n RetryingSender()\n\n def test_default_kwargs_used_if_none_specified(self):\n kwargs = {'arg': 'val'}\n\n from tekore import sender\n sender.default_requests_kwargs = kwargs\n s = sender.TransientSender()\n self.assertDictEqual(s.requests_kwargs, kwargs)\n\n def test_default_kwargs_ignored_if_kwargs_specified(self):\n kwargs = {'arg': 'val'}\n\n from tekore import sender\n sender.default_requests_kwargs = kwargs\n s = sender.TransientSender(kw='value')\n self.assertNotIn('arg', s.requests_kwargs)\n\n def tearDown(self):\n from tekore import sender\n sender.default_sender_type = self.old_default_type\n sender.default_sender_instance = self.old_default_instance\n sender.default_requests_kwargs = self.old_default_kwargs\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/sender.py","file_name":"sender.py","file_ext":"py","file_size_in_byte":8083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"512263060","text":"# Purpose\n# Takes in one or multiple .fastq.gz files, unzips, quality filters, and reports unique reads + associated read counts.\n# Output is tsv file named _collapsed.txt. column 1 = read. column 2 = read count.\n\n\n\n\n\n# Usage\n#\tpython x1.collapseSeq.py \t \n\n# Arguments\n#\t\t\tdirectory of the outputted files\n#\t \t\t\tinteger. Number of gigabytes of memory requested for computation\n#\t \t\tinteger. Maximum computation time requested \n#\t\t\t\t\temail to send alerts to \n\n# Inputs\n# directory and basename of the .fastq.gz files. Make sure you omit the .fastq.gz suffix.\n\n# Outputs\n#\tbasename_collapsed_filtered.fastq\tunzipped fastq file from all .fastq.gz files that matched the basename of input\n#\t\t\t\t\t\tfiltered for quality\n\n\n\n\n\n\n\nimport os\nimport sys\n\n# ensure all arguments passed\ntry:\n basename=sys.argv[1] # /dir/to/data/input.fastq\n basename_noDir=basename.split('/')[-1] # input.fastq\n dataDir=basename[:basename.rfind('/')+1] # /dir/to/data/\n outputDir=sys.argv[2]\n mem=sys.argv[3]\n jobHours=sys.argv[4]\n email=sys.argv[5]\nexcept IndexError:\n print(\"Error: Not all arguments passed\")\n\n# Make dirs for submission scripts and batch stderr/stdout files to be saved\nos.system(\"mkdir \"+outputDir+\"stdout 2>/dev/null\")\nos.system(\"mkdir \"+outputDir+\"stderr 2>/dev/null\")\n\n# Script version to use\ncollapseSeq='A.reads2collapsed.sh'\ncollapseSeqPy='0.collapseSeq.py'\n\n# Define Job Name\njobName='collapseSeq_'+basename_noDir\n\n# Create batch submit script\nline_out=\"#!/bin/bash\\n\"\nline_out+=\"#SBATCH --partition=shared\\n\"\nline_out+=\"#SBATCH --job-name=\"+jobName+\"\\n\"\nline_out+=\"#SBATCH --nodes=1\\n\"\nline_out+=\"#SBATCH --ntasks-per-node=1\\n\"\nline_out+=\"#SBATCH --mem=\"+mem+\"G\\n\"\nline_out+=\"#SBATCH --time=\"+jobHours+\":00:00\\n\"\nline_out+=\"#SBATCH --output=\"+outputDir+\"stdout/\"+jobName+\".out.txt\\n\"\nline_out+=\"#SBATCH --error=\"+outputDir+\"stderr/\"+jobName+\".err.txt\\n\"\nline_out+=\"#SBATCH --export=ALL\\n\"\nline_out+=\"#SBATCH --mail-user=\"+email+\"\\n\"\nline_out+=\"#SBATCH --mail-type=ALL\\n\"\nline_out+=\"module load python\\n\" # load package numpy\nline_out+=\"module load scipy\\n\" # load package numpy\nline_out+=\"module load biopython\\n\" # load package biopython\nline_out+=\" \".join([\"bash\",collapseSeq,dataDir,outputDir,basename_noDir]) # reads2BcDict $dataDir $basenam$\n\n# Write and submit batch script\nwith open(\"submit_collapseSeq.sh\",\"w\") as fn:\n fn.write(line_out)\nos.system(\"sbatch submit_collapseSeq.sh\")\n\n# Copy submit script\nos.system(\"mkdir \"+outputDir+\"submit-scripts 2>/dev/null\")\nos.system(\"cp submit_collapseSeq.sh \"+outputDir+\"submit-scripts/\"+jobName+\".submit.sh\")\n\n# Copy script to data file\nos.system(\"mkdir \"+outputDir+\"scripts 2>/dev/null\")\nos.system(' '.join([\"cp\",collapseSeq,outputDir+\"scripts/\"+collapseSeq]))\nos.system(' '.join([\"cp\",collapseSeqPy,outputDir+\"scripts/\"+collapseSeqPy]))\n\n","sub_path":"RNA_library/x1.collapseSeq.py","file_name":"x1.collapseSeq.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"109469906","text":"#!/usr/bin/env python3\n\nimport argparse\nimport logging\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\n\n\n__ENV_VOL_WIKI = \"VOL_WIKI\"\n__ENV_VOL_WIKI_SETTINGS = \"VOL_WIKI_SETTINGS\"\n__ENV_VOL_WIKI_IMAGES = \"VOL_WIKI_IMAGES\"\n__ENV_VOL_DATABASE = \"VOL_WIKI_DATABASE\"\n__ENV_VOL_BACKUP = \"VOL_WIKI_BACKUP\"\n\n__ENV_OUTPUT_FILE = \"wiki.env\"\n__ENV_OUTPUT_PATH = os.path.normpath(os.path.join(os.getcwd(), __ENV_OUTPUT_FILE))\n\n\n# -----------------------------------------------------------------------------\n#\ndef write_config(config: argparse.Namespace) -> None:\n\n data = \"--wiki\\n{}\\n\".format(config.vol_wiki)\n data += \"--database\\n{}\\n\".format(config.vol_database)\n data += \"--backup\\n{}\\n\".format(config.vol_backup)\n\n # Simply write the array to the output file\n with open(__ENV_OUTPUT_PATH, \"w+\") as fd:\n fd.writelines(data)\n\n\n# -----------------------------------------------------------------------------\n#\ndef gather_args():\n\n # If there are arguments, use those\n if len(sys.argv) > 1:\n return sys.argv[1:]\n\n # Next check for a config\n elif os.path.exists(__ENV_OUTPUT_PATH):\n with open(__ENV_OUTPUT_PATH, \"r\") as fd:\n result = [x.strip() for x in fd.readlines()]\n logging.debug(result)\n return result\n\n # Arguments will always fall through but expect to be empty\n return sys.argv[1:]\n\n\n# -----------------------------------------------------------------------------\n#\ndef parse_args(args):\n \"\"\"\n Parse a list of arguments into a configuration object\n\n :param args: of arguments to parse\n :return: struct containing parsed arguments\n \"\"\"\n\n parser = argparse.ArgumentParser(\"Deploy\")\n\n parser.add_argument(\"--wiki\", dest=\"vol_wiki\",\n type=str, help=\"Location on host machine for wiki\")\n parser.add_argument(\"--database\", dest=\"vol_database\",\n type=str, help=\"Location on host machine for wiki's database\")\n parser.add_argument(\"--backup\", dest=\"vol_backup\",\n type=str, help=\"Location on host machine for wiki's database backup output\")\n parser.add_argument(\"--env\", dest=\"env\",\n type=argparse.FileType('r'), help=\"Location of environment arguments\")\n\n parser.add_argument(\"--down\", dest=\"down\", action=\"store_true\", default=False,\n help=\"Optional argument to take down the containers\")\n\n config = parser.parse_args(args)\n\n if config.env is None and config.vol_wiki is None and config.vol_database is None and config.vol_backup is None:\n parser.error(\"'--env' is required or the explicit use of '--wiki', '--database', and '--env'\")\n\n if config.env is not None:\n # Gather the arguments from the file\n env_args = [x.strip() for x in config.env.readlines()]\n logging.debug(env_args)\n\n # Walk through each argument and assign them to the appropriate namespace\n i = 0\n while i < len(env_args):\n if env_args[i] == \"--wiki\":\n config.vol_wiki = env_args[i+1]\n if env_args[i] == \"--database\":\n config.vol_database = env_args[i+1]\n if env_args[i] == \"--backup\":\n config.vol_backup = env_args[i+1]\n i += 2\n\n return config\n\n\n# -----------------------------------------------------------------------------\n#\ndef post_deploy_hacky_stuff(config: argparse.Namespace, env: dict) -> None:\n\n # Hack - 1\n # Copy the LocalSettings.php file into the wiki container if it exists\n if not config.down:\n\n # Define variables\n local_settings_php_path = os.path.join(env[__ENV_VOL_WIKI_SETTINGS], \"LocalSettings.php\")\n\n # Only do this if the file exists (we could be on our initialization step)\n if os.path.exists(local_settings_php_path):\n cmd = [\"docker\", \"exec\", \"-it\", \"wiki_web\", \"cp\", \"/var/www/wiki_settings/LocalSettings.php\",\n \"/var/www/html/LocalSettings.php\"]\n logging.info(\"CMD: {}\".format(cmd))\n subprocess.run(cmd, check=True, env=env)\n\n # Hack - 2\n # This hack is to change the ownership of the mounted volume for the images uploaded to the wiki\n if not config.down:\n cmd = [\"docker\", \"exec\", \"-it\", \"wiki_web\", \"chown\", \"-R\", \"www-data:www-data\", \"/var/www/html\"]\n logging.info(\"CMD: {}\".format(cmd))\n subprocess.run(cmd, check=True, env=env)\n\n\n# -----------------------------------------------------------------------------\n#\ndef get_volumes(config: argparse.Namespace, make_dirs: bool = True) -> list:\n vol_wiki = os.path.normpath(os.path.abspath(config.vol_wiki))\n vol_wiki_images = os.path.join(vol_wiki, \"images\")\n vol_wiki_settings = os.path.join(vol_wiki, \"wiki_settings\")\n vol_database = os.path.normpath(os.path.abspath(config.vol_database))\n vol_backup = os.path.normpath(os.path.abspath(config.vol_backup))\n\n volumes = [vol_wiki, vol_wiki_images, vol_wiki_settings, vol_database, vol_backup]\n\n # Create the directories if necessary\n if make_dirs:\n for vol in volumes:\n if not os.path.exists(vol):\n os.makedirs(vol)\n\n return volumes\n\n\n# -----------------------------------------------------------------------------\n#\ndef deploy_containers():\n\n # Parse them into a runtime config\n config = parse_args(sys.argv[1:])\n\n # Get the absolute paths\n vol_wiki, vol_wiki_images, vol_wiki_settings, vol_database, vol_backup = get_volumes(config)\n\n # Make the directories if they do not exist\n vols = [vol_wiki, vol_database, vol_backup]\n logging.debug(\"Vols: {}\".format(vols))\n for vol in vols:\n if not os.path.exists(vol):\n os.makedirs(vol)\n\n # Build our target environment\n env = os.environ.copy()\n env[__ENV_VOL_WIKI] = vol_wiki\n env[__ENV_VOL_WIKI_IMAGES] = vol_wiki_images\n env[__ENV_VOL_WIKI_SETTINGS] = vol_wiki_settings\n env[__ENV_VOL_DATABASE] = vol_database\n env[__ENV_VOL_BACKUP] = vol_backup\n\n # Locate the compose file\n working_dir = os.path.dirname(os.path.abspath(__file__))\n compose_file = os.path.join(working_dir, \"docker-compose.yml\")\n\n # Root command to run\n exe = [\"docker-compose\"]\n\n # Arguments for the compose file\n file_arg = [\"--file\", compose_file]\n\n # Final docker commands\n build_cmd = [\"build\"]\n deploy_cmd = [\"up\", \"-d\"]\n down_cmd = [\"down\"]\n\n # Then perform the desired action\n if config.down:\n cmd = exe + file_arg + down_cmd\n logging.info(\"CMD: {}\".format(cmd))\n subprocess.run(cmd, check=True, env=env)\n else:\n cmd = exe + file_arg + build_cmd\n logging.info(\"CMD: {}\".format(cmd))\n subprocess.run(cmd, check=True, env=env)\n cmd = exe + file_arg + deploy_cmd\n logging.info(\"CMD: {}\".format(cmd))\n subprocess.run(cmd, check=True, env=env)\n\n # Do hacky things that should probably be handled by the compose.yaml file\n post_deploy_hacky_stuff(config, env)\n\n # Save the configs so the file can be ran again\n write_config(config)\n\n\n# -----------------------------------------------------------------------------\n#\nif __name__ == \"__main__\":\n\n # Configure the logger\n logging.basicConfig(level=logging.DEBUG)\n deploy_containers()\n\n\n","sub_path":"deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":7363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"445228199","text":"#!/usr/bin/python2.5\n# Copyright 2010 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom datetime import datetime\nimport simplejson\nimport sys\n\nfrom model import *\nfrom utils import *\nimport reveal\n\n\nclass Admin(Handler):\n # After a subdomain is deactivated, we still need the admin page to be\n # accessible so we can edit its settings.\n ignore_deactivation = True\n\n def get(self):\n user = users.get_current_user()\n simplejson.encoder.FLOAT_REPR = str\n encoder = simplejson.encoder.JSONEncoder(ensure_ascii=False)\n config_json = dict((name, encoder.encode(self.config[name]))\n for name in self.config.keys())\n self.render('templates/admin.html', user=user,\n subdomains=Subdomain.all(),\n config=self.config, config_json=config_json,\n start_url=self.get_start_url(),\n login_url=users.create_login_url(self.request.url),\n logout_url=users.create_logout_url(self.request.url),\n id=self.env.domain + '/person.')\n\n def post(self):\n if self.params.operation == 'delete':\n # Redirect to the deletion handler with a valid signature.\n action = ('delete', str(self.params.id))\n self.redirect('/delete', id=self.params.id,\n signature=reveal.sign(action))\n\n elif self.params.operation == 'subdomain_create':\n Subdomain(key_name=self.params.subdomain_new).put()\n config.set_for_subdomain( # Provide some defaults.\n self.params.subdomain_new,\n language_menu_options=['en', 'fr'],\n subdomain_titles={'en': 'Earthquake', 'fr': u'S\\xe9isme'},\n keywords='person finder, people finder, person, people, ' +\n 'crisis, survivor, family',\n use_family_name=True,\n use_postal_code=True,\n min_query_word_length=2,\n map_default_zoom=6,\n map_default_center=[0, 0],\n map_size_pixels=[400, 280],\n read_auth_key_required=True,\n search_auth_key_required=True,\n deactivated=False,\n deactivation_message_html='',\n main_page_custom_html='',\n results_page_custom_html='',\n view_page_custom_html='',\n )\n self.redirect('/admin', subdomain=self.params.subdomain_new)\n\n elif self.params.operation == 'subdomain_save':\n values = {}\n for name in [ # These settings are all entered in JSON.\n 'language_menu_options', 'subdomain_titles',\n 'use_family_name', 'family_name_first', 'use_postal_code',\n 'min_query_word_length', 'map_default_zoom',\n 'map_default_center', 'map_size_pixels',\n 'read_auth_key_required', 'search_auth_key_required',\n 'deactivated'\n ]:\n try:\n values[name] = simplejson.loads(self.request.get(name))\n except:\n return self.error(\n 400, 'The setting for %s was not valid JSON.' % name)\n\n for name in ['keywords',\n 'deactivation_message_html',\n 'main_page_custom_html',\n 'results_page_custom_html',\n 'view_page_custom_html']:\n # These settings are literal strings (not JSON).\n values[name] = self.request.get(name)\n\n config.set_for_subdomain(self.subdomain, **values)\n self.redirect('/admin', subdomain=self.subdomain)\n\nif __name__ == '__main__':\n run(('/admin', Admin))\n","sub_path":"app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"148309472","text":"\nimport os\nimport pydicom\nimport pandas as pd\nfrom skimage.color import rgb2gray\nfrom skimage import exposure\nfrom skimage import img_as_float\nfrom skimage import transform\n# import imageio\n# from scipy.misc import imsave\n# import matplotlib.pyplot as plt\nimport argparse\nimport numpy as np\nfrom PIL import Image\n\n# Image crop params\nIMAGE_PARAMS = {0: [2.1, 4, 4],\n 1: [2.5, 3.2, 3.2],\n 2: [1.7, 4.5, 4.5] # [2.5, 3.2, 3.2] # [1.7, 4.5, 4.5]\n } # factor to crop images by: crop ratio, translate_x, translate_y\n\n# loads all image paths to array\ndef load_file_names(cab_dir):\n dcm_files = []\n for subdir, dirs, files in os.walk(cab_dir):\n for file in files:\n if file.lower()[-4:] == \".dcm\":\n dcm_files.append(os.path.join(subdir, file))\n return sorted(dcm_files)\n\n# CROP IMAGES #\ndef crop_image(image, param_num):\n width = image.shape[1]\n height = image.shape[0]\n\n params = IMAGE_PARAMS[int(param_num)]\n\n new_dim = int(width // params[0]) # final image will be square of dim width/2 * width/2\n\n start_col = int(width // params[1]) # column (width position) to start from\n start_row = int(height // params[2]) # row (height position) to start from\n\n cropped_image = image[start_row:start_row + new_dim, start_col:start_col + new_dim]\n return cropped_image\n\n# function to set the image contrast\ndef set_contrast(image, contrast):\n if contrast == 0:\n out_img = image\n elif contrast == 1:\n out_img = exposure.equalize_hist(image)\n elif contrast == 2:\n out_img = exposure.equalize_adapthist(image)\n elif contrast == 3:\n out_img = exposure.rescale_intensity(image)\n\n return out_img\n\ndef get_filename(opt, linking_log):\n mrn_usnum = opt.dcm_dir[1:]\n my_mrn = mrn_usnum.split(\"_\")[0]\n deid = linking_log.loc[linking_log['mrn'] == np.int64(my_mrn)]['deid']\n my_usnum = mrn_usnum.split(\"_\")[1]\n filename = '_'.join([str(int(deid)), my_usnum])\n\n return filename\n\ndef format_np_output(np_arr):\n \"\"\"\n From: https://github.com/utkuozbulak/pytorch-cnn-visualizations/blob/master/src/misc_functions.py\n\n This is a (kind of) bandaid fix to streamline saving procedure.\n It converts all the outputs to the same format which is 3xWxH\n with using sucecssive if clauses.\n Args:\n im_as_arr (Numpy array): Matrix of shape 1xWxH or WxH or 3xWxH\n \"\"\"\n # Phase/Case 1: The np arr only has 2 dimensions\n # Result: Add a dimension at the beginning\n if len(np_arr.shape) == 2:\n np_arr = np.expand_dims(np_arr, axis=0)\n # Phase/Case 2: Np arr has only 1 channel (assuming first dim is channel)\n # Result: Repeat first channel and convert 1xWxH to 3xWxH\n if np_arr.shape[0] == 1:\n np_arr = np.repeat(np_arr, 3, axis=0)\n # Phase/Case 3: Np arr is of shape 3xWxH\n # Result: Convert it to WxHx3 in order to make it saveable by PIL\n if np_arr.shape[0] == 3:\n np_arr = np_arr.transpose(1, 2, 0)\n # Phase/Case 4: NP arr is normalized between 0-1\n # Result: Multiply with 255 and change type to make it saveable by PIL\n if np.max(np_arr) <= 1:\n np_arr = (np_arr*255).astype(np.uint8)\n return np_arr\n\n\ndef save_image(im, path):\n \"\"\"\n Saves a numpy matrix or PIL image as an image\n Args:\n im_as_arr (Numpy array): Matrix of shape DxWxH\n path (str): Path to the image\n \"\"\"\n if isinstance(im, (np.ndarray, np.generic)):\n im = format_np_output(im)\n im = Image.fromarray(im)\n im.save(path)\n\ndef load_images(dcm_files, link_log, lab_file, opt):\n\n img_num = 0\n img_creation_time = []\n manu = []\n img_id = []\n img_label = []\n\n ## debug\n # image_path = dcm_files[0]\n\n for image_path in dcm_files:\n tokens = image_path.split(\"/\")\n # print(tokens)\n\n rootdir_tokens = opt.cabs_rootdir.split(\"/\")\n # print(rootdir_tokens)\n\n # get mrn and sample number\n # print(tokens[len(rootdir_tokens) - 1])\n sample_name = tokens[len(rootdir_tokens) - 1][1:].split(\"_\")\n # print(sample_name)\n mrn = sample_name[0]\n # print(mrn)\n\n ## debug\n # mrn = '2455689'\n\n float_mrn = float(mrn)\n # print(float_mrn)\n\n sample_id = float_mrn\n print(\"sample id: \" + str(int(sample_id)))\n\n # print(link_log.head)\n deid = str(int(link_log.loc[link_log['mrn'] == np.int64(mrn)]['deid']))\n\n try:\n ds = pydicom.dcmread(image_path)\n print(\"Image read in from dicom\")\n\n except:\n print(\"IMAGE PATH ERROR\")\n print(image_path)\n\n try:\n inst_num = ds.InstanceNumber\n img_creation_time.append(inst_num)\n except:\n print(\"Error grabbing instance number\")\n\n img = ds.pixel_array\n print(\"Image transferred to pixel array\")\n img = img_as_float(rgb2gray(img))\n cropped_image = crop_image(img, opt.params) # crop image with i-th params\n resized_image = transform.resize(cropped_image, output_shape=(opt.output_dim, opt.output_dim)) # reduce\n final_img = set_contrast(resized_image, opt.contrast)\n\n mrn_img_id_val = str(int(mrn)) + \"_\" + sample_name[1] + \"_\" + str(inst_num)\n # print(lab_file.head)\n print(\"Image ID: \" + mrn_img_id_val)\n\n try:\n label = lab_file.loc[lab_file['img_id'] == mrn_img_id_val, 'revised_labels'].values[0]\n img_label.append(label)\n print(\"Image label: \" + label)\n\n img_id_val = str(int(deid)) + \"_\" + sample_name[1] + \"_\" + str(inst_num)\n img_id.append(img_id_val)\n print(\"De-id image ID: \" + img_id_val)\n\n img_file_name = img_id_val + \".jpg\"\n print(\"Image file name:\" + img_file_name)\n\n manufacturer = ds.Manufacturer\n manu.append(manufacturer)\n print(\"Manufacturer name: \" + manufacturer)\n\n save_image(final_img, os.path.join(opt.jpg_dump_dir, img_file_name))\n print('Image file written to' + opt.jpg_dump_dir + img_file_name)\n\n except:\n print(\"Image ID not in label file\")\n\n img_num = img_num + 1\n\n # print(\"Image IDs: \")\n # print(img_id)\n # print(\"Image labels: \")\n # print(img_label)\n # print(\"Image manufacturers: \")\n # print(manu)\n df_dict = {'image_ids' : img_id, 'image_label': img_label, 'image_manu': manu}\n out_csv = pd.DataFrame(df_dict)\n return out_csv\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-params', default=1, help=\"parameter settings to crop images \"\n \"(see IMAGE_PARAMS_1 at top of file)\")\n parser.add_argument('-output_dim', default=256, help=\"dimension of output image\")\n parser.add_argument('-rootdir', default='/hpf/largeprojects/agoldenb/lauren/Hydronephrosis/data/load_training_test_sets/',\n help=\"directory of US sequence dicoms\")\n parser.add_argument('-cabs_rootdir', default='/hpf/largeprojects/agoldenb/lauren/Hydronephrosis/all-cabs/',\n help=\"directory of US sequence dicoms\")\n parser.add_argument('-dcm_dir', default='D5048003_1',\n help=\"directory of US sequence dicoms\")\n parser.add_argument('-jpg_dump_dir', default='/hpf/largeprojects/agoldenb/lauren/Hydronephrosis/label_img/',\n help=\"directory of US sequence dicoms\")\n parser.add_argument('-csv_out_dir', default='/hpf/largeprojects/agoldenb/lauren/Hydronephrosis/label_csv/',\n help=\"directory of US sequence dicoms\")\n parser.add_argument('-label_filename', default='view_label_df_20200120.csv',\n help=\"directory of US sequence dicoms\")\n parser.add_argument('-id_linking_filename', default='linking_log_20191120.csv',\n help=\"directory of US sequence dicoms\")\n parser.add_argument(\"--contrast\", default=1, type=int, help=\"Image contrast to train on\")\n\n opt = parser.parse_args() ## comment for debug\n opt.output_dim = int(opt.output_dim)\n\n cab_dir = os.path.join(opt.cabs_rootdir, opt.dcm_dir + \"/\")\n print(\"cab_dir: \" + cab_dir)\n\n my_dcm_files = load_file_names(cab_dir=cab_dir)\n my_linking_log = pd.read_csv(opt.rootdir + '/' + opt.id_linking_filename)\n my_lab_file = pd.read_csv(opt.rootdir + '/' + opt.label_filename)\n\n csv_out = load_images(dcm_files=my_dcm_files, link_log=my_linking_log, lab_file=my_lab_file, opt=opt)\n csv_filename = get_filename(opt, linking_log=my_linking_log) + \".csv\"\n\n print(\"Writing csv file to: \" + opt.csv_out_dir + \"/\" + csv_filename)\n csv_out.to_csv(opt.csv_out_dir + \"/\" + csv_filename)\n\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n####\n####\n####\n # parser.add_argument('-params', default=1, help=\"parameter settings to crop images \"\n # \"(see IMAGE_PARAMS_1 at top of file)\")\n # parser.add_argument('-output_dim', default=256, help=\"dimension of output image\")\n # parser.add_argument('-rootdir', default='C:/Users/larun/Desktop/Data Science Core/Projects/Urology/Front-end-test-files/',\n # help=\"directory of US sequence dicoms\")\n # parser.add_argument('-dcm_dir', default='D5048003_1',\n # help=\"directory of US sequence dicoms\")\n # parser.add_argument('-jpg_dump_dir', default='C:/Users/larun/Desktop/Data Science Core/Projects/Urology/Front-end-test-files/',\n # help=\"directory of US sequence dicoms\")\n # parser.add_argument('-csv_out_dir', default='C:/Users/larun/Desktop/Data Science Core/Projects/Urology/Front-end-test-files/',\n # help=\"directory of US sequence dicoms\")\n # parser.add_argument('-label_filename', default='linking_log_20191120.csv',\n # help=\"directory of US sequence dicoms\")\n # parser.add_argument('-id_linking_filename', default='view_label_df_20191120.csv',\n # help=\"directory of US sequence dicoms\")\n # parser.add_argument(\"--contrast\", default=1, type=int, help=\"Image contrast to train on\")\n\n\n ## comment out after debug\n# class make_opt():\n# def __init__(self):\n# self.params = 1\n# self.output_dim = 256\n# self.rootdir = 'C:/Users/larun/Desktop/Data Science Core/Projects/Urology/Image organization Nov 2019/'\n# self.cabs_rootdir = 'C:/Users/larun/Desktop/Data Science Core/Projects/Urology/Front-end-test-files/'\n# self.dcm_dir = 'D5048003_1'\n# self.jpg_dump_dir = 'C:/Users/larun/Desktop/Data Science Core/Projects/Urology/Front-end-test-files/'\n# self.csv_out_dir = 'C:/Users/larun/Desktop/Data Science Core/Projects/Urology/Front-end-test-files/'\n# self.label_filename = 'view_label_df_20200120.csv'\n# self.id_linking_filename = 'linking_log_20191120.csv'\n# self.contrast = 1\n#\n# opt = make_opt()\n\n","sub_path":"Kidney labels/Preprocessing/preprocess-us-seq-DA.py","file_name":"preprocess-us-seq-DA.py","file_ext":"py","file_size_in_byte":11044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"600835581","text":"from mock import MagicMock\nfrom mock import patch\nimport os\nimport shutil\nimport tempfile\nimport unittest\n\nfrom chainerui import app\nfrom chainerui import db\nfrom chainerui.models.project import Project\n\n\nclass TestApp(unittest.TestCase):\n\n def setUp(self):\n temp_dir = tempfile.mkdtemp(prefix='chainerui_test_app_')\n self._dir = temp_dir\n self._db_path = os.path.join(temp_dir, 'test_app.db')\n self._db_url = 'sqlite:///' + self._db_path\n\n def tearDown(self):\n if db._session is not None:\n db.session.remove()\n db.remove_db()\n if os.path.exists(self._dir):\n shutil.rmtree(self._dir)\n\n def test_server(self):\n args = app.create_parser().parse_args(\n ['--db', self._db_url, 'server', '-H', 'test.domain',\n '-p', '5001', '-d'])\n assert args.host == 'test.domain'\n assert args.port == 5001\n assert args.debug\n assert args.db == self._db_url\n\n mock_app = MagicMock()\n mock_app_creator = MagicMock(return_value=mock_app)\n\n with patch('chainerui.app.create_app', mock_app_creator) as f:\n args.handler(args)\n f.assert_not_called()\n\n db.upgrade()\n args.handler(args)\n f.assert_called_once()\n mock_app.run.assert_called_with(\n host='test.domain', port=5001, debug=True, threaded=True)\n\n def test_project_create(self):\n args = app.create_parser().parse_args(\n ['--db', self._db_url, 'project', 'create', '-d', self._dir,\n '-n', 'test'])\n assert args.project_dir == self._dir\n assert args.project_name == 'test'\n assert args.db == self._db_url\n\n args.handler(args)\n db.upgrade()\n p = db.session.query(Project).filter_by(path_name=self._dir).first()\n assert p is None\n # on Windows/Python2, another session is create, need to remove\n # this session externally (*)\n db._session.remove()\n\n args.handler(args)\n p = db.session.query(Project).filter_by(path_name=self._dir).first()\n assert p is not None\n assert p.path_name == self._dir\n assert p.name == 'test'\n db._session.remove() # same as (*)\n\n args.handler(args) # already registered, confirm not occur error\n ps = db.session.query(Project).filter_by(path_name=self._dir).all()\n assert len(ps) == 1\n\n def test_db_create(self):\n args = app.create_parser().parse_args(\n ['--db', self._db_url, 'db', 'create'])\n assert args.type == 'create'\n assert args.db == self._db_url\n args.handler(args)\n assert os.path.isdir(db._sqlite_default_db_dir())\n assert not db._initialized\n\n def test_db_status(self):\n args = app.create_parser().parse_args(\n ['--db', self._db_url, 'db', 'status'])\n assert args.type == 'status'\n assert args.db == self._db_url\n args.handler(args)\n assert db._initialized\n assert db._external_db\n\n def test_db_upgrade_drop(self):\n args = app.create_parser().parse_args(\n ['--db', self._db_url, 'db', 'upgrade'])\n assert args.type == 'upgrade'\n assert args.db == self._db_url\n args.handler(args)\n assert db._initialized\n assert db._external_db\n\n args = app.create_parser().parse_args(\n ['--db', self._db_url, 'db', 'drop'])\n assert args.type == 'drop'\n assert args.db == self._db_url\n args.handler(args)\n assert not db._initialized\n assert not db._external_db\n\n def test_db_revision(self):\n args = app.create_parser().parse_args(\n ['--db', self._db_url, 'db', 'revision'])\n assert args.type == 'revision'\n assert args.db == self._db_url\n with patch('chainerui.app.db_revision.new_revision') as f:\n args.handler(args)\n assert f.called\n assert db._initialized\n assert db._external_db\n","sub_path":"tests/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":4039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"566624146","text":"import numpy as np\n\n\n\ndef in_field(field):\n formato = ('%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s \\\n %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s \\\n %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s\\\n\t\t %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s')\n # This catalogue is created by cutting_catalogue_liners.in_field\n filename = 'F'+str(field)+'_catalogue_master_hst_liners.txt'\n f = np.loadtxt(filename,dtype='float')\n\n field_number,ID_5,Prob_posiew_5,prob_agn5,prob_sf5,prob_retired5,prob_weak_agn5,\\\n cont_maxprob_5,cont_median_5,rel_error_cont_median_5,rel_error_cont_maxlik_5,\\\n z_maxprob_5,z_median_5,rel_error_z_median_5,\\\n fha_maxprob_5,fha_median_5,rel_error_fha_median_5,rel_error_fha_maxlik_5,lha_median_5,\\\n fnii_maxprob_5,fnii_median_5,rel_error_fnii_median_5,rel_error_fnii_maxlik_5,\\\n ewha_median_5,ewha_maxlik_5,error_ewha_median_5,error_ewha_maxlik_5,lineratio_median_5,lineratio_maxlik_5,error_lineratio_median_5,error_lineratio_maxlik_5,\\\n chisq_5,twolines_5,oneline_5,\\\n ID_total,Prob_posiew_total,prob_agn_total,prob_sf_total,prob_retiredtotal,prob_weak_agntotal,\\\n cont_maxprob_total,cont_median_total,rel_error_cont_median_total,rel_error_cont_maxlik_total,\\\n z_maxprob_total,z_median_total,rel_error_z_median_total,\\\n fha_maxprob_total,fha_median_total,rel_error_fha_median_total,rel_error_fha_maxlik_total,lha_median_total,\\\n fnii_maxprob_total,fnii_median_total,rel_error_fnii_median_total,rel_error_fnii_maxlik_total,\\\n ewha_median_total,ewha_maxlik_total,error_ewha_median_total,error_ewha_maxlik_total,lineratio_median_total,lineratio_maxlik_total,error_lineratio_median_total,error_lineratio_maxlik_total,\\\n chisq_total,twolines_total,oneline_total,\\\n ST_A_IMAGE,ra,dec,Rmag,combo_flag,stages_flag,MC_z,logmass,logmass_cl,flux24,tir,tuv,tir_cl,tuv_cl,\\\n sfr_det,sfr_lo,sfr_hi,sfr_det_cl,sfr_lo_cl,sfr_hi_cl,sed_type = f[:].T\n\n\n ### One line aper5\n cut_one_line_5 = np.where((error_ewha_median_5/(ewha_median_5) < 0.15) & (Prob_posiew_5 > 99.7) & (oneline_5 == 1))[0]\n\n ### One line total aper\n cut_one_line_total = np.where((error_ewha_median_total/(ewha_median_total) < 0.15) & (Prob_posiew_total > 99.7) & (oneline_total == 1))[0]\n\n ###Two lines aper5\n cut_two_lines_5 = np.where((error_ewha_median_5/(ewha_median_5) < 0.15) & (Prob_posiew_5 > 99.7) & (twolines_5 == 1))[0]\n\n ###Two lines total aper\n cut_two_lines_total = np.where((error_ewha_median_total/(ewha_median_total) < 0.15) & (Prob_posiew_total > 99.7) & (twolines_total == 1))[0]\n\n ###Two lines total aper more restricted\n cut_two_lines_total_01 = np.where((error_ewha_median_total/(ewha_median_total) < 0.1) & (Prob_posiew_total > 99.7) & (twolines_total == 1))[0]\n\n ### Two lines and AGN\n cut_two_lines_agn_5 = np.where((error_ewha_median_5/(ewha_median_5) < 0.15) & (Prob_posiew_5 > 99.7) & (twolines_5 == 1) & (prob_agn5 > 99.7))[0]\n\n ### Two lines and SF\n cut_two_lines_sf_5 = np.where((error_ewha_median_5/(ewha_median_5) < 0.15) & (Prob_posiew_5 > 99.7) & (twolines_5 == 1) & (prob_sf5 > 99.7))[0]\n\n\n ### Catalogue with all the galaxies within the z cut in the total aperture measurement\n np.savetxt('F'+str(field)+'_catalogue_total_master_hst_liners_nozcut.txt',f,fmt=formato)\n\n\n ### Catalogue with all the galaxies within the two lines cut in the total aperture measurement\n np.savetxt('F'+str(field)+'_catalogue_cut_two_lines_total_master_hst_liners_nozcut.txt',f[cut_two_lines_total],fmt=formato)\n\n ### Catalogue with all the galaxies within the two lines cut in the total aperture measurement MORE RESTRICTED\n np.savetxt('F'+str(field)+'_catalogue_cut_two_lines_total_01_master_hst_liners_nozcut.txt',f[cut_two_lines_total_01],fmt=formato)\n\n\n ### Catalogue with all the galaxies within the two lines cut in the 5 pixel aperture measurement\n np.savetxt('F'+str(field)+'_catalogue_cut_two_lines_aper5_master_hst_liners_nozcut.txt',f[cut_two_lines_5],fmt=formato)\n\n ### Catalogue with all the galaxies within the one line cut in the total aperture measurement\n np.savetxt('F'+str(field)+'_catalogue_cut_one_line_total_master_hst_liners_nozcut.txt',f[cut_one_line_total],fmt=formato)\n\n\n\n f1 = open('number_of_galaxies_hst_liners_nozcut.txt','a+')\n f1.write('%2i %3i %3i %3i %3i %3i \\n'%(field,len(field_number), len(field_number),len(cut_one_line_total),len(cut_two_lines_total), len(cut_two_lines_5)))\n f1.close()\n","sub_path":"cutting_catalogue_liners_nozcut.py","file_name":"cutting_catalogue_liners_nozcut.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"92110384","text":"'''\nPrograma: URI - problema 1071\nProgramador: Paulo Henrique M. Leite\nData: 21/06/2019\nLinguagem: Python\nAlgoritmo: \nStatus: ACEITO\n'''\n\n# inicializando informação\n\nini = input()\nend = input()\n\naux = 0\nsoma = 0\n\n# processando informação\n\nif ini > end:\n\taux = ini\n\tini = end\n\tend = aux\n\ni = int(ini)\nf = int(end)\n\ni += 1\nf -= 1\nwhile(i <= f):\n\tif i % 2 != 0:\n\t\tsoma = soma + i\n\ti = i + 1\n\n\n# imprimindo informação\nprint(soma)\n\n","sub_path":"uri/1071.py","file_name":"1071.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"495182073","text":"# coding=utf-8\n\n'''\n批量梯度下降\n正确结果\n[[ 0.7502]\n [ 0.0639]]\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Training data set\n# each element in x represents (x0,x1,x2)\n#x = [(1, 0., 3), (1, 1., 3), (1, 2., 3), (1, 3., 2), (1, 4., 4)]\na = np.loadtxt(\"ex2Data/ex2x.dat\",unpack='true')\nm=len(a)\n#往数组中加1列的值为 1\nx=np.column_stack((np.ones((m,1)), a))\n# y[i] is the output of y = theta0 * x[0] + theta1 * x[1] +theta2 * x[2]\n#y = [95.364, 97.217205, 75.195834, 60.105519, 49.342380]\ny = np.loadtxt(\"ex2Data/ex2y.dat\",unpack='true')\n'''\nplt.xlabel(\"age\")\nplt.ylabel(\"height\")\nplt.title(\"house price distribution\")\n#绘制散列点\nplt.scatter(a, y)\n# 绘制线条\n# plt.plot(x,y)\nplt.legend()\nplt.show()\n'''\nepsilon = 0.000001\n# learning rate\nalpha = 0.001\ndiff = [0, 0]\nerror1 = 0\nerror0 = 0\nm = len(x)\n\n# init the parameters to zero\ntheta0 = 0\ntheta1 = 0\ntheta2 = 0\nsum0 = 0\nsum1 = 0\nsum2 = 0\nmaxCycles=1500\nfor k in range(maxCycles):\n# while true:\n # calculate the parameters\n for i in range(m):\n # begin batch gradient descent\n diff[0] = y[i] - (theta0 + theta1 * x[i][1] )\n sum0 = sum0 + alpha * diff[0] * x[i][0]\n sum1 = sum1 + alpha * diff[0] * x[i][1]\n # sum2 = sum2 + alpha * diff[0] * x[i][2]\n # end batch gradient descent\n theta0 = sum0;\n theta1 = sum1;\n # theta2 = sum2;\n # calculate the cost function\n # error1 = 0\n # for lp in range(len(x)):\n # error1 += (y[i] - (theta0 + theta1 * x[i][1])) ** 2 / 2\n #\n # if abs(error1 - error0) < epsilon:\n # break\n # else:\n # error0 = error1\n #\n # print(' theta0 : %f, theta1 : %f error1 : %f' % (theta0, theta1, error1))\n\nprint('Done: theta0 : %f, theta1 : %f' % (theta0, theta1))\n\n\nh1=theta0+theta1*3\nh2=theta0+theta1*7\nprint(h1)\nprint(\"\\n\")\nprint(h2)","sub_path":"code/1.Linear_Regression/batchGD.py","file_name":"batchGD.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"607489581","text":"#!/usr/bin/env python\n\n\nimport logging\nfrom flask import Flask, jsonify\nfrom flask_cors import CORS\nfrom flask_ngrok import run_with_ngrok\n\napp = Flask(__name__)\nlogging.basicConfig(level=logging.INFO)\nlogging.getLogger('flask_cors').level = logging.DEBUG\nCORS(app)\nrun_with_ngrok(app)\n\n\n@app.route(\"/return_json\", methods=[\"POST\"])\ndef returnJson():\n return jsonify({\n 'folder_id': 'yoyo',\n 'img': 'adad',\n 'imgname': 'bibi',\n 'imguniquename': 'kaka'\n })\n\n\n@app.route(\"/\", methods=[\"GET\"])\ndef index():\n return jsonify({'msg': 'success'})\n\n\nif __name__ == '__main__':\n app.run()","sub_path":"apiget/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"406641413","text":"# Class: XYZFile\n# used for getUncertaintyDEM\n# by Whyjay Zheng, Jul 28 2016\n\nimport numpy as np\n\nclass XYZFile:\n\n\tdef __init__(self, fpath=None, refpts_path=None, dem_path=None):\n\t\tself.fpath = fpath\n\t\tself.refpts_path = refpts_path\n\t\tself.dem_path = dem_path\n\t\tself.data = None\n\n\tdef Read(self):\n\n\t\t\"\"\"\n\t\tself.data will be usually a 3- or 4-column np.array\n\t\tcolumn 1: easting\n\t\tcolumn 2: northing\n\t\tcolumn 3: height of the 1st group (usually reference points)\n\t\tcolumn 4: height of the 2nd group (usually DEM points made from grdtrack)\n\t\t\"\"\"\n\n\t\tself.data = np.loadtxt(self.fpath)\n\n\tdef StatisticOutput(self):\n\t\tmad = lambda x : 1.482 * np.median(abs(x - np.median(x)))\n\t\tif self.data.size == 0:\n\t\t\tprint('NOTE: ' + self.dem_path + ' does not cover any ref points.')\n\t\t\treturn [self.dem_path, '', '', '', '', '', '', self.refpts_path]\n\t\telif self.data.shape[1] == 4:\n\t\t\tidx = ~np.isnan(self.data[:, 3])\n\t\t\tdiffval = self.data[idx, 3] - self.data[idx, 2]\n\t\t\toffset_median = np.median(diffval)\n\t\t\toffset_mad = mad(diffval)\n\t\t\tlbound = offset_median - 3. * offset_mad\n\t\t\tubound = offset_median + 3. * offset_mad\n\t\t\tidx2 = np.logical_and(diffval > lbound, diffval < ubound)\n\t\t\tdiffval_trimmed = diffval[idx2]\n\t\t\t# The return value is ready for CsvTable.SaveData method.\n\t\t\t# ['filename', 'date', 'uncertainty', 'mean_offset_wrt_refpts', \\\n\t\t\t# 'trimmed_N', 'trimming_lb', 'trimming_up', 'refpts_file']\n\t\t\t# 'date' is an empty string since we don't specify any date string in .xyz file.\n\t\t\treturn [self.dem_path, '', diffval_trimmed.std(ddof=1), diffval_trimmed.mean(), \\\n\t\t\t len(diffval_trimmed), lbound, ubound, self.refpts_path]\n\t\telif self.data.shape[1] == 3:\n\t\t\tprint(\"Not yet designed.\")\n\t\t\treturn []\n\t\telse:\n\t\t\tprint(\"This program currently doesn't support the xyz file whose column number is not 3 or 4.\")\n\t\t\treturn []\n","sub_path":"dhdt/UtilXYZ.py","file_name":"UtilXYZ.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"200335711","text":"from timeit import timeit\nfrom random import random\n\nrandomList = [random() for num in range(600_000)]\n\ndef qsort(values):\n if len(values) < 2: return values\n return qsort([val for val in values if val < values[0]]) + \\\n [values[0]] + \\\n qsort([val for val in values if val > values[0]])\n\ntime1 = timeit('qsort(randomList)', globals=globals(), number=100)\nprint('super-simple qsort: ' + str(time1))\n","sub_path":"QuickSort/time_quick.py","file_name":"time_quick.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"419530674","text":"# Copyright 2017 Steven E. Lamberson, Jr. \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\n\n\n\nclass Command(object):\n \"\"\"Maps a string (the command) to a function that should be called\n when the string is present.\n \"\"\"\n\n def __init__(self, string=None, function=None):\n \"\"\"Creates the Command object.\"\"\"\n self.function = None\n self.string = ''\n self.subcommands = {}\n if function is not None:\n self.function = function\n if string is not None:\n self.string = string\n\n\n def add_subcommands(self, subcommands, function):\n \"\"\"Create subcommands for this command.\"\"\"\n this_subcommand = subcommands[0]\n if len(subcommands) == 1:\n self.subcommands[this_subcommand] = Command(this_subcommand,\n function)\n else:\n new_subcommands = subcommands[1:]\n self.subcommands[this_subcommand] = Command(this_subcommand)\n self.subcommands[this_subcommand].add_subcommands(new_subcommands,\n function)\n\n\n\nclass Interpreter(object):\n \"\"\"Interprets a string as a command with possible subcommands.\"\"\"\n\n def __init__(self):\n \"\"\"Creates the Interpreter object.\"\"\"\n self._log = logging.getLogger('__name__')\n","sub_path":"acolytegm/interpreter.py","file_name":"interpreter.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"601470894","text":"from ethereum.tools import tester as t\nfrom ethereum import utils, abi\nfrom ethereum.hybrid_casper.casper_initiating_transactions import \\\n viper_rlp_decoder_address, sig_hasher_address, purity_checker_address, casper_abi, purity_checker_abi\nfrom ethereum.hybrid_casper.casper_utils import mk_prepare, mk_commit, mk_logout, induct_validator\nfrom ethereum.hybrid_casper import casper_utils\nfrom viper import compiler\n# from ethereum.slogging import configure_logging, set_level\n# config_string = ':info,eth.vm.log:trace,eth.vm.op:trace,eth.vm.stack:trace,eth.vm.exit:trace,eth.pb.msg:trace,eth.pb.tx:debug'\n# configure_logging(config_string=config_string)\nalloc = {}\nfor i in range(9):\n alloc[utils.int_to_addr(i)] = {'balance': 1}\nalloc[t.a0] = {'balance': 10**22}\nalloc[t.a1] = {'balance': 10**22}\ngenesis = casper_utils.make_casper_genesis(alloc, 5, 100, 0.02, 0.002)\nc = t.Chain(genesis=genesis)\nt.languages['viper'] = compiler.Compiler()\nt.gas_limit = 9999999\nt.STARTGAS = 2000000\nc.mine(1)\n\nEPOCH_LENGTH = c.chain.config['EPOCH_LENGTH']\n\nct = abi.ContractTranslator(purity_checker_abi)\n# Check that the RLP decoding library and the sig hashing library are \"pure\"\nassert utils.big_endian_to_int(c.tx(t.k0, purity_checker_address, 0, ct.encode('submit', [viper_rlp_decoder_address]))) == 1\nassert utils.big_endian_to_int(c.tx(t.k0, purity_checker_address, 0, ct.encode('submit', [sig_hasher_address]))) == 1\n\ncasper = t.ABIContract(c, casper_abi, c.chain.config['CASPER_ADDRESS'])\nc.mine(1)\n\n# Begin the test\n\nprint(\"Starting tests\")\n# Initialize the first epoch\nc.mine(EPOCH_LENGTH - c.head_state.block_number)\n# casper.initialize_epoch(1)\nassert casper.get_nextValidatorIndex() == 1\nassert casper.get_current_epoch() == 1\nprint(\"Epoch initialized\")\n\n# Deposit one validator\ninduct_validator(c, casper, t.k1, 200 * 10**18)\n# Mine two epochs\nc.mine(EPOCH_LENGTH * 3 - c.head_state.block_number)\n# casper.initialize_epoch(2)\n# casper.initialize_epoch(3)\nassert casper.get_total_curdyn_deposits() == 200 * 10**18\nassert casper.get_total_prevdyn_deposits() == 0\n\n_e, _a, _se, _sa = \\\n casper.get_current_epoch(), casper.get_recommended_ancestry_hash(), \\\n casper.get_recommended_source_epoch(), casper.get_recommended_source_ancestry_hash()\nprint(\"Penalty factor: %.8f\" % (casper.get_current_penalty_factor()))\n# Send a prepare message\nprint('pre deposit', casper.get_deposit_size(1), casper.get_total_curdyn_deposits())\nassert casper.get_deposit_size(1) == casper.get_total_curdyn_deposits()\ncasper.prepare(mk_prepare(1, _e, _a, _se, _sa, t.k1))\nprint('Gas consumed for a prepare: %d' % c.last_gas_used(with_tx=True))\nsourcing_hash = utils.sha3(utils.encode_int32(_e) + _a + utils.encode_int32(_se) + _sa)\nassert casper.get_consensus_messages__ancestry_hash_justified(_e, _a)\nassert casper.get_main_hash_justified()\nprint(\"Prepare message processed\")\ntry:\n casper.prepare(mk_prepare(1, 1, '\\x35' * 32, '\\x00' * 32, 0, '\\x00' * 32, t.k0))\n success = True\nexcept:\n success = False\nassert not success\nprint(\"Prepare message fails the second time\")\n# Send a commit message\ncasper.commit(mk_commit(1, _e, _a, 0, t.k1))\nprint('post deposit', casper.get_deposit_size(1))\nprint('Gas consumed for a commit: %d' % c.last_gas_used(with_tx=True))\n# Check that we committed\nassert casper.get_main_hash_finalized()\nprint(\"Commit message processed\")\n# Initialize the fourth epoch\nc.mine(EPOCH_LENGTH * 4 - c.head_state.block_number)\n# casper.initialize_epoch(4)\n# Check that the dynasty increased as expected\nassert casper.get_dynasty() == 4\nprint(casper.get_total_prevdyn_deposits(), casper.get_total_curdyn_deposits())\nprint(\"Second epoch initialized, dynasty increased as expected\")\n_e, _a, _se, _sa = \\\n casper.get_current_epoch(), casper.get_recommended_ancestry_hash(), \\\n casper.get_recommended_source_epoch(), casper.get_recommended_source_ancestry_hash()\n# Send a prepare message\nprint('pre deposit', casper.get_deposit_size(1), casper.get_total_curdyn_deposits())\nassert casper.get_deposit_size(1) == casper.get_total_curdyn_deposits()\ncasper.prepare(mk_prepare(1, _e, _a, _se, _sa, t.k1))\nassert casper.get_main_hash_justified()\n# Send a commit message\nepoch_4_commit = mk_commit(1, _e, _a, 3, t.k1)\ncasper.commit(epoch_4_commit)\nprint('post deposit', casper.get_deposit_size(1))\n# Check that we committed\nassert casper.get_main_hash_finalized()\n# Initialize the fifth epoch\nc.mine(EPOCH_LENGTH * 5 - c.head_state.block_number)\n# casper.initialize_epoch(5)\nprint(casper.get_latest_npf(), casper.get_latest_ncf(), casper.get_latest_resize_factor())\nprint('pre deposit', casper.get_deposit_size(1))\nassert casper.get_total_curdyn_deposits() == casper.get_deposit_size(1)\nprint(\"Fourth epoch prepared and committed, fifth epoch initialized\")\n_e, _a, _se, _sa = \\\n casper.get_current_epoch(), casper.get_recommended_ancestry_hash(), \\\n casper.get_recommended_source_epoch(), casper.get_recommended_source_ancestry_hash()\n# Test the NO_DBL_PREPARE slashing condition\np1 = mk_prepare(1, _e, _a, _se, _sa, t.k1)\np2 = mk_prepare(1, _e, _sa, _se, _sa, t.k1)\nsnapshot = c.snapshot()\ncasper.double_prepare_slash(p1, p2)\nc.revert(snapshot)\nprint(\"NO_DBL_PREPARE slashing condition works\")\n# Test the PREPARE_COMMIT_CONSISTENCY slashing condition\np3 = mk_prepare(1, _e, _a, 0, casper.get_ancestry_hashes(0), t.k1)\nsnapshot = c.snapshot()\ncasper.prepare_commit_inconsistency_slash(p3, epoch_4_commit)\nc.revert(snapshot)\nprint(\"PREPARE_COMMIT_CONSISTENCY slashing condition works\")\n# Finish the fifth epoch\ncasper.prepare(p1)\ncasper.commit(mk_commit(1, _e, _a, 4, t.k1))\nassert casper.get_main_hash_justified()\nassert casper.get_main_hash_finalized()\nds_0_non_finalized = casper.get_deposit_size(1)\nc.mine(EPOCH_LENGTH * 6 - c.head_state.block_number)\n# casper.initialize_epoch(6)\nds_1_non_finalized = casper.get_deposit_size(1)\nprint(\"Non-finalization losses (first epoch): %.4f\" % (1 - ds_1_non_finalized / ds_0_non_finalized))\nassert ds_1_non_finalized < ds_0_non_finalized\nc.mine(EPOCH_LENGTH * 7 - c.head_state.block_number)\n# casper.initialize_epoch(7)\nds_2_non_finalized = casper.get_deposit_size(1)\nprint(\"Non-finalization losses (second epoch): %.4f\" % (1 - ds_2_non_finalized / ds_1_non_finalized))\nc.mine(EPOCH_LENGTH * 8 - c.head_state.block_number)\n# casper.initialize_epoch(8)\nds_3_non_finalized = casper.get_deposit_size(1)\nprint(\"Non-finalization losses (third epoch): %.4f\" % (1 - ds_3_non_finalized / ds_2_non_finalized))\nassert (ds_2_non_finalized - ds_3_non_finalized) > (ds_0_non_finalized - ds_1_non_finalized)\n_e, _a, _se, _sa = \\\n casper.get_current_epoch(), casper.get_recommended_ancestry_hash(), \\\n casper.get_recommended_source_epoch(), casper.get_recommended_source_ancestry_hash()\nprint(casper.get_deposit_size(1))\np4 = mk_prepare(1, _e, _a, _se, _sa, t.k1)\ncasper.prepare(p4)\nprint(casper.get_deposit_size(1))\np4 = mk_prepare(1, _e, _a, _se, _sa, t.k1)\nc4 = mk_commit(1, _e, _a, 5, t.k1)\ncasper.commit(c4)\nprint(casper.get_deposit_size(1))\np4 = mk_prepare(1, _e, _a, _se, _sa, t.k1)\nassert casper.get_main_hash_finalized()\nc.mine(EPOCH_LENGTH * 9 - c.head_state.block_number)\n# casper.initialize_epoch(9)\nprint(casper.get_latest_npf(), casper.get_latest_ncf(), casper.get_latest_resize_factor())\nprint(casper.get_deposit_size(1), casper.get_current_penalty_factor())\nds_after_finalize = casper.get_deposit_size(1)\nassert casper.get_latest_npf() < 0.1 and casper.get_latest_ncf() < 0.1\nassert ds_after_finalize > ds_3_non_finalized\nprint(\"Finalization gains: %.4f\" % (ds_after_finalize / ds_3_non_finalized - 1))\ninduct_validator(c, casper, t.k2, 200 * 10**18)\ninduct_validator(c, casper, t.k3, 200 * 10**18)\ninduct_validator(c, casper, t.k4, 200 * 10**18)\ninduct_validator(c, casper, t.k5, 200 * 10**18)\nc.mine(1)\nassert casper.get_deposit_size(1) == casper.get_total_curdyn_deposits()\n_e, _a, _se, _sa = \\\n casper.get_current_epoch(), casper.get_recommended_ancestry_hash(), \\\n casper.get_recommended_source_epoch(), casper.get_recommended_source_ancestry_hash()\np4 = mk_prepare(1, _e, _a, _se, _sa, t.k1)\ncasper.prepare(p4)\nc4 = mk_commit(1, _e, _a, 8, t.k1)\ncasper.commit(c4)\nc.mine(EPOCH_LENGTH * 10 - c.head_state.block_number)\n# casper.initialize_epoch(10)\n_e, _a, _se, _sa = \\\n casper.get_current_epoch(), casper.get_recommended_ancestry_hash(), \\\n casper.get_recommended_source_epoch(), casper.get_recommended_source_ancestry_hash()\np4 = mk_prepare(1, _e, _a, _se, _sa, t.k1)\ncasper.prepare(p4)\nc4 = mk_commit(1, _e, _a, 9, t.k1)\ncasper.commit(c4)\nc.mine(EPOCH_LENGTH * 11 - c.head_state.block_number)\n# casper.initialize_epoch(11)\nassert abs(sum(map(casper.get_deposit_size, range(1, 6))) - casper.get_total_curdyn_deposits()) < 5\nprint(\"Validator induction works\")\n_e, _a, _se, _sa = \\\n casper.get_current_epoch(), casper.get_recommended_ancestry_hash(), \\\n casper.get_recommended_source_epoch(), casper.get_recommended_source_ancestry_hash()\nfor prepare in [mk_prepare(i, _e, _a, _se, _sa, k) for i, k in zip([1, 2, 3, 4], [t.k1, t.k2, t.k3, t.k4])]:\n casper.prepare(prepare)\nassert casper.get_main_hash_justified()\nc.mine(1)\nfor commit in [mk_commit(i, _e, _a, casper.get_validators__prev_commit_epoch(i), k) for i, k in zip([1, 2, 3, 4], [t.k1, t.k2, t.k3, t.k4])]:\n casper.commit(commit)\nassert casper.get_main_hash_finalized()\nprint(\"Epoch 11 finalized with 4/5 prepares/commits\")\ncasper.logout(mk_logout(1, 11, t.k1))\n\nc.mine(EPOCH_LENGTH * 12 - c.head_state.block_number)\n# casper.initialize_epoch(12)\nassert casper.get_deposit_size(5) < \\\n casper.get_deposit_size(2) == casper.get_deposit_size(3) == casper.get_deposit_size(4)\n\n_e, _a, _se, _sa = \\\n casper.get_current_epoch(), casper.get_recommended_ancestry_hash(), \\\n casper.get_recommended_source_epoch(), casper.get_recommended_source_ancestry_hash()\nfor prepare in [mk_prepare(i, _e, _a, _se, _sa, k) for i, k in zip([1, 2, 3, 4], [t.k1, t.k2, t.k3, t.k4])]:\n casper.prepare(prepare)\nassert casper.get_main_hash_justified()\nc.mine(1)\nfor commit in [mk_commit(i, _e, _a, casper.get_validators__prev_commit_epoch(i), k) for i, k in zip([2, 3, 4, 5], [t.k2, t.k3, t.k4, t.k5])]:\n casper.commit(commit)\nassert casper.get_main_hash_finalized()\n\nprint(\"Epoch 12 finalized with 4/5 prepares/commits\")\nc.mine(EPOCH_LENGTH * 13 - c.head_state.block_number)\n# casper.initialize_epoch(13)\nassert abs(sum(map(casper.get_deposit_size, range(2, 6))) - casper.get_total_curdyn_deposits()) < 5\nassert abs(sum(map(casper.get_deposit_size, range(1, 6))) - casper.get_total_prevdyn_deposits()) < 5\n\n_e, _a, _se, _sa = \\\n casper.get_current_epoch(), casper.get_recommended_ancestry_hash(), \\\n casper.get_recommended_source_epoch(), casper.get_recommended_source_ancestry_hash()\nfor prepare in [mk_prepare(i, _e, _a, _se, _sa, k) for i, k in zip([1, 2, 3, 4], [t.k1, t.k2, t.k3, t.k4])]:\n casper.prepare(prepare)\nassert casper.get_main_hash_justified()\nc.mine(1)\nfor commit in [mk_commit(i, _e, _a, casper.get_validators__prev_commit_epoch(i), k) for i, k in zip([2, 3, 4, 5], [t.k2, t.k3, t.k4, t.k5])]:\n casper.commit(commit)\nassert casper.get_main_hash_finalized()\nprint(\"Epoch 13 finalized with 4/5 prepares/commits\")\n\nc.mine(EPOCH_LENGTH * 14 - c.head_state.block_number)\n# casper.initialize_epoch(14)\nassert abs(sum(map(casper.get_deposit_size, range(2, 6))) - casper.get_total_curdyn_deposits()) < 5\nassert abs(sum(map(casper.get_deposit_size, range(2, 6))) - casper.get_total_prevdyn_deposits()) < 5\n\nprint(\"Verified post-deposit logouts\")\nfor i in range(15, 100):\n c.mine(EPOCH_LENGTH * i - c.head_state.block_number)\n # casper.initialize_epoch(i)\n _e, _a, _se, _sa = \\\n casper.get_current_epoch(), casper.get_recommended_ancestry_hash(), \\\n casper.get_recommended_source_epoch(), casper.get_recommended_source_ancestry_hash()\n for prepare in [mk_prepare(i, _e, _a, _se, _sa, k) for i, k in zip([2, 3], [t.k2, t.k3])]:\n casper.prepare(prepare)\n print(casper.get_main_hash_prepared_frac())\n assert abs(sum(map(casper.get_deposit_size, range(2, 6))) - casper.get_total_curdyn_deposits()) < 5\n assert abs(sum(map(casper.get_deposit_size, range(2, 6))) - casper.get_total_prevdyn_deposits()) < 5\n ovp = (casper.get_deposit_size(2) + casper.get_deposit_size(3)) / casper.get_total_curdyn_deposits()\n print(\"Epoch %d, online validator portion %.4f\" % (i, ovp))\n if ovp >= 0.7:\n assert casper.get_main_hash_justified()\n break\n\nfor commit in [mk_commit(i, _e, _a, casper.get_validators__prev_commit_epoch(i), k) for i, k in zip([2, 3], [t.k2, t.k3])]:\n casper.commit(commit)\n\nassert casper.get_main_hash_finalized()\nassert casper.get_main_hash_committed_frac() >= 0.667\nprint(\"Deposits of remaining validators: %d %d\" % (casper.get_deposit_size(2), casper.get_deposit_size(3)))\nprint(\"Deposits of offline validators: %d %d\" % (casper.get_deposit_size(4), casper.get_deposit_size(5)))\nprint(\"Tests passed\")\n","sub_path":"ethereum/tests/hybrid_casper/test_casper.py","file_name":"test_casper.py","file_ext":"py","file_size_in_byte":12931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"506151001","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Author: Jordi Ballester (Eficent)\n# Copyright 2015 Eficent\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp import api, fields, models, _\nfrom openerp.exceptions import Warning\n\n\nclass CrossoveredBudget(models.Model):\n _inherit = \"crossovered.budget\"\n\n operating_unit_id = fields.Many2one(\n 'operating.unit',\n string='Operating Unit',\n default=lambda self: self.env['res.users'].\n operating_unit_default_get(self._uid),\n )\n\n @api.one\n @api.constrains('operating_unit_id', 'company_id')\n def _check_company_operating_unit(self):\n if self.company_id and self.operating_unit_id and \\\n self.company_id != self.operating_unit_id.company_id:\n raise Warning(_('The Company in the Move Line and in the '\n 'Operating Unit must be the same.'))\n\n\nclass CrossoveredBudgetLines(models.Model):\n _inherit = \"crossovered.budget.lines\"\n\n operating_unit_id = fields.Many2one(\n 'operating.unit',\n related='crossovered_budget_id.operating_unit_id',\n string='Operating Unit', readonly=True, store=True,\n )\n\n # DONE but NOT USED YET\n# @api.one\n# @api.constrains('operating_unit_id', 'analytic_account_id')\n# def _check_analytic_account_operating_unit(self):\n# if self.type not in ('payment', 'receipt'):\n# return True\n# if (\n# self.analytic_account_id and self.operating_unit_id and\n# self.analytic_account_id.operating_unit_id and\n# self.analytic_account_id.operating_unit_idid !=\n# self.operating_unit_id.id\n# ):\n# raise Warning(_('The Analytic Account must have the same '\n# 'Operating Unit as the one indicated in the '\n# 'budget plan'))\n# return True\n","sub_path":"account_budget_operating_unit/models/account_budget.py","file_name":"account_budget.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"372378603","text":"import pytest\nfrom datetime import datetime\n\nfrom app.models.task import Task\n\ndef test_task_constructor():\n desc = \"My task\"\n t = Task(desc)\n assert t.description == desc\n assert t.completed == False\n\n\ndef test_task_properties():\n desc = \"Test task properties\"\n t = Task(desc)\n assert t.description == desc\n \n rename = \"Test task description set\"\n t.description = rename\n assert t.description == rename\n\n assert t.completed == False\n t.completed = 1\n assert t.completed == True\n\n\n# This type of testing is NOT required, but shown for example purposes\ndef test_task_properties_exceptions():\n t = Task(\"Foobar\")\n\n # Since we cannot set completed > 1 we can use pytest\n # to check for python errors using the following syntax.\n with pytest.raises(ValueError):\n t.completed = 2\n \n # Cannot set completed < 0\n with pytest.raises(ValueError):\n t.completed = -1\n\n # Cannot use set property on creation_datetime\n with pytest.raises(AttributeError):\n t.creation_datetime = datetime.now()\n","sub_path":"TheBlackBookMap/tests/test_models/test_task.py","file_name":"test_task.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"21294958","text":"###############################################################################\n### GUI to display hand rom ###\n### Input: Hand rom ###\n### Output: Realtime display of hand rom ###\n###############################################################################\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass GuiHand:\n def __init__(self, max_len=50):\n # Use ggplot style for more sophisticated visuals\n plt.style.use('ggplot')\n \n # Line plot for MCP joint of five digits\n self.line_mcp = [[] for i in range(5)] \n self.line_pip = [[] for i in range(5)]\n self.line_dip = [[] for i in range(5)]\n # To store the joint angles for each digit\n self.y_mcp = [np.zeros(max_len) for i in range(5)]\n self.y_pip = [np.zeros(max_len) for i in range(5)]\n self.y_dip = [np.zeros(max_len) for i in range(5)]\n # x axis value [0, 0.01, ..., 0.99]\n self.x_vec = np.linspace(0,1,max_len+1)[0:-1] \n\n # Call to matplotlib to allow dynamic plotting\n plt.ion() \n \n fig = plt.figure(figsize=(6,3.7))\n ax = fig.add_subplot(111)\n for i in range(5): \n self.line_mcp[i], = ax.plot(self.x_vec, self.y_mcp[i], '-o', markersize=2) \n self.line_pip[i], = ax.plot(self.x_vec, self.y_pip[i], '-o', markersize=2) \n self.line_dip[i], = ax.plot(self.x_vec, self.y_dip[i], '-o', markersize=2)\n \n plt.show()\n\n\n def live_plotter(self, data, mode=0, pause_time=0.001):\n # Extract the data into different types\n data_mcp = [data[9],data[12],data[16],data[20],data[24]]\n data_pip = [data[10],data[13],data[17],data[21],data[25]]\n data_dip = [data[10],data[14],data[18],data[22],data[26]] # Note data[10] is thumb IP so considered dip and pip\n\n ###########\n ### MCP ###\n ###########\n label = ['Thumb', 'Index', 'Middle', 'Ring', 'Little']\n for i, d in enumerate(data_mcp):\n self.y_mcp[i][-1] = d\n # Update the y-data\n self.line_mcp[i].set_ydata(self.y_mcp[i])\n if mode==0: \n self.line_mcp[i].set_label('%s %.2f'%(label[i], d))\n else:\n self.line_mcp[i].set_label('')\n self.y_mcp[i] = np.append(self.y_mcp[i][1:], 0.0) \n\n ###########\n ### PIP ###\n ###########\n for i, d in enumerate(data_pip):\n self.y_pip[i][-1] = d\n # Update the y-data\n self.line_pip[i].set_ydata(self.y_pip[i])\n if mode==1: \n self.line_pip[i].set_label('%s %.2f'%(label[i], d))\n else:\n self.line_pip[i].set_label('')\n self.y_pip[i] = np.append(self.y_pip[i][1:], 0.0) \n\n\n ###########\n ### DIP ###\n ###########\n for i, d in enumerate(data_dip):\n self.y_dip[i][-1] = d\n # Update the y-data\n self.line_dip[i].set_ydata(self.y_dip[i])\n if mode==2: \n self.line_dip[i].set_label('%s %.2f'%(label[i], d))\n else: \n self.line_dip[i].set_label('')\n self.y_dip[i] = np.append(self.y_dip[i][1:], 0.0) \n\n # Adjust the plot visibility according \n if mode==0:\n for i in range(5):\n self.line_mcp[i].set_visible(True)\n self.line_pip[i].set_visible(False)\n self.line_dip[i].set_visible(False)\n # Adjust limits if new data goes beyond bounds\n ylim_min = self.line_mcp[i].axes.get_ylim()[0] \n ylim_max = self.line_mcp[i].axes.get_ylim()[1] \n if np.min(self.y_mcp[i])<=ylim_min or np.max(self.y_mcp[i])>=ylim_max:\n plt.ylim([np.min(self.y_mcp[i])-np.std(self.y_mcp[i]),np.max(self.y_mcp[i])+np.std(self.y_mcp[i])]) \n plt.ylabel('MCP angle (deg)')\n elif mode==1:\n for i in range(5):\n self.line_mcp[i].set_visible(False)\n self.line_pip[i].set_visible(True)\n self.line_dip[i].set_visible(False) \n # Adjust limits if new data goes beyond bounds\n ylim_min = self.line_pip[i].axes.get_ylim()[0] \n ylim_max = self.line_pip[i].axes.get_ylim()[1] \n if np.min(self.y_pip[i])<=ylim_min or np.max(self.y_pip[i])>=ylim_max:\n plt.ylim([np.min(self.y_pip[i])-np.std(self.y_pip[i]),np.max(self.y_pip[i])+np.std(self.y_pip[i])]) \n plt.ylabel('PIP angle (deg)')\n elif mode==2:\n for i in range(5):\n self.line_mcp[i].set_visible(False)\n self.line_pip[i].set_visible(False)\n self.line_dip[i].set_visible(True) \n # Adjust limits if new data goes beyond bounds\n ylim_min = self.line_dip[i].axes.get_ylim()[0] \n ylim_max = self.line_dip[i].axes.get_ylim()[1] \n if np.min(self.y_dip[i])<=ylim_min or np.max(self.y_dip[i])>=ylim_max:\n plt.ylim([np.min(self.y_dip[i])-np.std(self.y_dip[i]),np.max(self.y_dip[i])+np.std(self.y_dip[i])]) \n plt.ylabel('DIP angle (deg)')\n\n # Replot the legend to update the data\n plt.legend(loc='upper left')\n \n # Pauses the data so the figure/axis can catch up\n plt.pause(pause_time)\n \n\n###############################################################################\n### Simple example to test the program ###\n###############################################################################\nif __name__ == '__main__':\n import time\n import keyboard\n gui = GuiHand(max_len=100)\n\n mode = 0\n while True:\n data = np.random.randn(27)\n print(data)\n gui.live_plotter(data, mode)\n\n if keyboard.is_pressed('esc'): # Press escape to end the program\n print('Quitting...')\n break\n if keyboard.is_pressed('m'):\n mode = (mode+1)%3\n print('mode', mode)\n time.sleep(0.3)\n","sub_path":"code/utils_gui.py","file_name":"utils_gui.py","file_ext":"py","file_size_in_byte":6389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"420843685","text":"from microkinetic_toolkit.reactions import Reactions\nfrom ase.build import fcc111\n\n# preparation\nT = 800 # temperature [K]\nP = 100 # total pressure [bar]\nratio = {\"H2\": 1.1, \"CO2\": 1.0} # partial pressure ratio\n\n\n## read reactions from file and set Reactions\nreactions = Reactions.from_csv(\"test.csv\")\n\n## define surface if you like\n#surf = fcc111(\"Ni\", size=[3, 3, 4], vacuum=10.0)\n\n## if you have pre-calculated ase.db\n#reactions.ase_db = \"ase.db\"\n\n# reaction energy evaluation\nreactions.calculator = \"emt\"\ndeltaEs = reactions.get_reaction_energies()\n\n# microkinetic analysis\n## set parameters for kinetics\nreactions.set_kinetic_parameters(alpha=0.5, beta=2.5, sden=1.0e-5, v0=1.0e-5, wcat=1.0e-3, phi=0.5, rho_b=1.0e3)\n\n## calculate rate constant from reaction energies\nks = reactions.get_rate_constants(deltaEs=deltaEs, T=T)\n\n## do_microkinetics\nreactions.do_microkinetics(deltaEs=deltaEs, ks=ks, T=T, P=P, ratio=ratio)\n\n## draw graph\n#reactions.draw_network(rate)\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"544910329","text":"import tkinter as tk\nfrom tkinter import messagebox\nfrom tkinter.filedialog import askopenfilename\nimport os\nimport vlc\nfrom datetime import datetime\n\n\nclass PlayQueueWindow(tk.Frame):\n\n def __init__(self, parent, my_controller):\n \"\"\" Initialize the popup queue window \"\"\"\n tk.Frame.__init__(self, parent)\n\n self._songs_in_queue = []\n self.main_controller = my_controller\n\n self._vlc_instance = vlc.Instance()\n self._player = self._vlc_instance.media_player_new()\n\n self._current_title = None\n\n parent.title('Play Queue')\n\n self.top_frame = tk.Frame(self.master)\n self.bot_frame = tk.Frame(self.master)\n self.mid_frame = tk.Frame(self.master)\n self.top_frame.grid(row=0, padx=30, pady=10)\n self.bot_frame.grid(row=2, padx=30, pady=10)\n self.mid_frame.grid(row=1, padx=30, pady=10)\n\n self.song_listbox = tk.Listbox(self.top_frame, width=40,\n selectmode=tk.BROWSE)\n self.song_scrollbar = tk.Scrollbar(self.top_frame, orient='vertical')\n self.song_scrollbar.config(command=self.song_listbox.yview)\n self.song_listbox.config(yscrollcommand=self.song_scrollbar.set)\n\n self.details = tk.Label(self.mid_frame, text='')\n self.details.grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)\n\n play_button = tk.Button(self.bot_frame, text='Play', width=10, bg=\"lightblue\")\n play_button.grid(row=0, column=0, sticky=tk.E, padx=20, pady=5)\n play_button.bind(\"\", self.do_play)\n\n stop_button = tk.Button(self.bot_frame, text='Stop', width=10, bg=\"lightblue\")\n stop_button.grid(row=0, column=1, sticky=tk.E, padx=20, pady=5)\n stop_button.bind(\"\", self.do_stop)\n\n remove_button = tk.Button(self.bot_frame, text='Remove', width=10, bg=\"red\")\n remove_button.grid(row=2, column=1, sticky=tk.E, padx=20, pady=5)\n remove_button.bind(\"\", self.do_remove)\n\n pause_button = tk.Button(self.bot_frame, text='Pause', width=10, bg=\"lightblue\")\n pause_button.grid(row=1, column=0, sticky=tk.E, padx=20, pady=5)\n pause_button.bind(\"\", self.do_pause)\n\n resume_button = tk.Button(self.bot_frame, text='Resume', width=10, bg=\"lightblue\")\n resume_button.grid(row=1, column=1, sticky=tk.E, padx=20, pady=5)\n resume_button.bind(\"\", self.do_resume)\n\n skip_button = tk.Button(self.bot_frame, text='Skip', width=10, bg=\"lightblue\")\n skip_button.grid(row=2, column=0, sticky=tk.E, padx=20, pady=5)\n skip_button.bind(\"\", self.do_next)\n\n self.song_listbox.pack(side=tk.LEFT, fill=tk.BOTH)\n self.song_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)\n\n\n\n def add_song_to_queue(self, song):\n \"\"\" Adds song to the queue\"\"\"\n song_display = f'{song[\"title\"]} - {song[\"artist\"]}'\n self._songs_in_queue.append(song)\n self.song_listbox.insert(tk.END, song_display)\n\n def do_play(self, event):\n \"\"\"Play a song specified by index. \"\"\"\n self.index = self.song_listbox.index(tk.ACTIVE)\n\n if len(self._songs_in_queue) == 0:\n msg_str = 'No songs loaded on to the song Que'\n messagebox.showinfo(title='Play Error', message=msg_str)\n return\n\n song = self._songs_in_queue[self.index]\n song[\"play_count\"] += 1\n song[\"last_played\"] = datetime.now().strftime(\"%Y-%m-%d\")\n\n self.details[\"text\"] = f'Last Played: {song[\"last_played\"]} Count: {song[\"play_count\"]}'\n file_path = song[\"file_location\"]\n media = self._vlc_instance.media_new_path(file_path)\n self._player.set_media(media)\n self._player.play()\n\n self.main_controller.update_play(song)\n\n\n def do_pause(self, event):\n \"\"\" Pause the player \"\"\"\n if self._player.get_state() == vlc.State.Playing:\n self._player.pause()\n\n def do_resume(self, event):\n \"\"\" Resume playing \"\"\"\n if self._player.get_state() == vlc.State.Paused:\n self._player.pause()\n\n def do_stop(self, event):\n \"\"\" Stop the player \"\"\"\n self._player.stop()\n\n def do_remove(self, event):\n \"\"\" Remove song from the player \"\"\"\n index = self.song_listbox.index(tk.ACTIVE)\n self._player.stop()\n self.song_listbox.delete(index)\n self._songs_in_queue.pop(index)\n\n def do_next(self, event):\n \"\"\" Plays next song in the queue\"\"\"\n self.index += 1\n if self.index + 1> len(self._songs_in_queue):\n messagebox.showinfo(title='Next', message=\"No New Songs in Queue\")\n return\n\n song = self._songs_in_queue[self.index]\n song[\"play_count\"] += 1\n song[\"last_played\"] = datetime.now().strftime(\"%Y-%m-%d\")\n\n self.details[\"text\"] = f'Last Played: {song[\"last_played\"]} Count: {song[\"play_count\"]}'\n file_path = song[\"file_location\"]\n media = self._vlc_instance.media_new_path(file_path)\n self._player.set_media(media)\n self._player.play()\n\n self.main_controller.update_play(song)\n\n","sub_path":"play_queue_window.py","file_name":"play_queue_window.py","file_ext":"py","file_size_in_byte":5155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"359066515","text":"import pandas as pd\nfrom afinn import Afinn\n\n# Cleaning the data and finding the sentiment score for each review text in the dataset.\n\ndf= pd.read_csv(\"reviewsAndTips .csv\",index_col=0)\nlength=df.__len__()\n\nprint(length)\n\ndf=df.dropna()\n\nafinn = Afinn()\npscore = []\n\nfor text in df['Text']:\n pscore.append(afinn.score(text))\n\ndf['pscore'] = pscore\n\ndf.to_csv('sentiment_analysis.csv')\n\n","sub_path":"Task 2/SentimentScoreCalculator.py","file_name":"SentimentScoreCalculator.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"429817824","text":"__author__ = 'Azharul'\n\nimport os\nfrom django.conf import settings\nfrom sqlalchemy import orm, Table, Column, Integer, String, DateTime, Boolean\nfrom core import dbconfig\nfrom core.model import Model, GenericRelation, ListProperty\nfrom core.modules.attachment.enums import E_AttachmentType, E_AttachmentStorageType\nfrom core.modules.attachment.models import Attachment\n\n\ncompany_table = Table('companies', dbconfig.metaData,\n Column('id', Integer, primary_key=True),\n Column('name', String(255)),\n Column('primary_contact_name', String(255)),\n Column('primary_contact_phone', String(255)),\n Column('primary_contact_email', String(255)),\n Column('business_address_1', String(255)),\n Column('business_address_2', String(255)),\n Column('city', String(100)),\n Column('state', String(100)),\n Column('zip', String(100)),\n Column('service_token', String(255)),\n Column('inactive', Boolean),\n Column('deleted', Boolean),\n Column('created_by', Integer),\n Column('updated_by', Integer),\n Column('created', DateTime),\n Column('updated', DateTime))\n\n\nclass CompanyAttachmentRelation(GenericRelation):\n logo = ListProperty(E_AttachmentType.NavBarLogo.index)\n\n\nclass Company(Model):\n attachments = CompanyAttachmentRelation(Attachment)\n\n @property\n def navbar_logo_attachment(self):\n return self.attachments.get_property(E_AttachmentType.NavBarLogo.index).default\n\n @property\n def navbar_logo_name(self):\n return self.navbar_logo_attachment.upload_name if self.navbar_logo_attachment else ''\n\n @property\n def navbar_logo_url(self):\n file_path = None\n default_path = '/static/app/css/images/logo.png'\n if self.navbar_logo_name:\n file_path = 'user_data/attachment/companies/'+str(self.id)+'/'+self.navbar_logo_name\n if self.navbar_logo_attachment.storage_type==E_AttachmentStorageType.Remote.index:\n return \"http:\" + settings.MEDIA_URL + file_path\n\n if file_path and os.path.exists(settings.BASE_DIR + settings.MEDIA_URL + file_path):\n return file_path\n return default_path\n\n\n @property\n def contact_info(self):\n contact = ''\n if self.primary_contact_name:\n contact += \"\"+self.primary_contact_name+\"\"\n if self.primary_contact_phone:\n contact += \"
\"+self.primary_contact_phone\n if self.primary_contact_email:\n contact += \"
\"+self.primary_contact_email\n\n return contact\n\n @property\n def address(self):\n address = ''\n\n if self.business_address_1:\n address += self.business_address_1\n if self.business_address_2:\n address += \"\\n\"+self.business_address_2\n if self.city:\n address += \"\\n\"+self.city\n if self.state:\n address += \"\\n\"+self.state\n if self.zip:\n address += \" - \"+self.zip\n\n return address + '.' if address else address\n\n\ncompany_mapper = orm.mapper(Company, company_table\n )\n\n","sub_path":"server/core/modules/company/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"461464238","text":"import threading\nimport queue\nfrom LCM import *\nfrom Utils import *\n\ndef sender():\n input_to_header = {\n \"score\" : SHEPHERD_HEADER.GOAL_SCORE,\n \"bid\" : SHEPHERD_HEADER.GOAL_BID,\n \"code\" : SHEPHERD_HEADER.POWERUP_APPLICATION,\n }\n\n input_to_alliance = {\n \"gold\" : ALLIANCE_COLOR.GOLD,\n \"blue\" : ALLIANCE_COLOR.BLUE,\n }\n\n input_to_goal = {\n \"a\" : GOAL.A,\n \"b\" : GOAL.B,\n \"c\" : GOAL.C,\n \"d\" : GOAL.D,\n \"e\" : GOAL.E,\n \"gold\" : GOAL.GOLD,\n \"blue\" : GOAL.BLUE,\n }\n\n while True:\n new_input = input_to_header.get(input(\"Command: score bid code \"))\n if new_input in (SHEPHERD_HEADER.GOAL_SCORE, SHEPHERD_HEADER.GOAL_BID):\n goal_letter = input_to_goal.get(input(\"Goal Letter: a b c d e blue gold \"))\n alliance = input_to_alliance.get(input(\"Alliance: blue gold \"))\n if goal_letter is None or alliance is None:\n print(\"Invalid input\")\n continue\n if new_input == SHEPHERD_HEADER.GOAL_SCORE:\n for _ in range(0):\n lcm_send(LCM_TARGETS.SHEPHERD, new_input, {\"alliance\" : alliance,\n \"goal\" : goal_letter})\n lcm_send(LCM_TARGETS.SHEPHERD, new_input, {\"alliance\" : alliance, \"goal\" : goal_letter})\n\n elif new_input == SHEPHERD_HEADER.POWERUP_APPLICATION:\n goal_letter = input_to_goal.get(input(\"Goal Letter: a b c d e blue gold \"))\n alliance = input_to_alliance.get(input(\"Alliance: blue gold \"))\n code = input(\"Code: \")\n if goal_letter is None or alliance is None or code is None:\n print(\"Invalid input\")\n continue\n lcm_send(LCM_TARGETS.SHEPHERD, new_input, {\"alliance\" : alliance,\n \"goal\" : goal_letter,\n \"code\" : code})\n else:\n print(\"Invalid input\")\n\ndef receiver():\n events = queue.Queue()\n lcm_start_read(LCM_TARGETS.SENSORS, events)\n while True:\n event = events.get(True)\n print(event)\n\nif __name__ == \"__main__\":\n sender_thread = threading.Thread(target=sender, name=\"DummySensorSender\")\n recv_thread = threading.Thread(target=receiver, name=\"DummySensorReceiver\")\n sender_thread.start()\n recv_thread.start()\n","sub_path":"shepherd/DummySensors.py","file_name":"DummySensors.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"8776450","text":"from django.conf.urls import url\n\nfrom . import views\n\n\napp_name='posts'\n\nurlpatterns = [\n url(r'^$',views.PostList.as_view(),name='all'),\n url(r'^new/$',views.CreatePost.as_view(),name='create'),\n url(r'^by/(?P[-\\w]+)/$',views.UserPosts.as_view(),name='for_user'),\n url(r'^by/(?P[-\\w]+)/(?P\\d+)/$',views.PostDetail.as_view(),name='single'),\n url(r'^delete/(?P\\d+)/$',views.DeletePost.as_view(),name='delete'),\n url(r'^by/(?P\\d+)/comment/$',views.add_comment_to_post,name='add_comment'),\n \n url(r'^update/(?P\\d+)/$',views.UpdatePost.as_view(),name='update'),\n \n url(r'^comment/(?P\\d+)/approve/$',views.comment_approve,name='comment_approve'),\n url(r'^comment/(?P\\d+)/remove/$',views.comment_remove,name='comment_remove'),\n url(r'^comment/(?P\\d+)/like/$',views.LikePost,name='like'),\n url(r'^event/$',views.EventList.as_view(),name='event_all'),\n url(r'^lcc/$',views.LCCList.as_view(),name='lcc_all'),\n\n ]\n \n\n\n","sub_path":"posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"480487372","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nz,T,Ux,Uy,Uz = np.loadtxt('postProcessing/singleGraph/3000/line_T_Ux_Uy_Uz.xy',delimiter='\\t',dtype=np.float,unpack=True)\nzdata,Uueh,Tueh,Ukim,Tkim,Uxie,Txie = np.loadtxt('xie-2006-data.csv',delimiter=',',dtype=np.float,skiprows=1,unpack=True)\n\nTf = 320.82\nTa = 300\nUinf = 0.56\nH = 0.1\ntheta = (T-Tf)/(Ta-Tf)\nz0 = z/H\nU0 = Ux/Uinf\n\nplt.subplot(1,2,1)\nplt.plot(theta,z0,'r',label='This study, Rb = -0.21')\nplt.plot(Tueh,zdata,'bo',label='Uehara et al 2000, Rb = -0.21')\nplt.plot(Tkim,zdata,'k^',label='Kim & Baik 2001, Rb = -0.27')\nplt.plot(Txie,zdata,'gD',label='Xie et al 2006, Rb = -0.21')\nplt.xlabel(r'$\\theta$')\nplt.ylabel('z/H')\nplt.xlim((-0.1,1.2))\nplt.ylim((0.0,2.0))\nplt.legend(loc=2)\n\nplt.subplot(1,2,2)\nplt.plot(U0,z0,'r')\nplt.plot(Uueh,zdata,'bo')\nplt.plot(Ukim,zdata,'k^')\nplt.plot(Uxie,zdata,'gD')\nplt.xlabel('Ux/U0')\nplt.ylabel('z/H')\nplt.ylim((0.0,2.0))\n\nplt.show()\n","sub_path":"Validation/centerlineplot.py","file_name":"centerlineplot.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"613750406","text":"from odoo import api, fields, models, _\nfrom num2words import num2words\n\n\nclass AccountMove(models.Model):\n _inherit= \"account.move\"\n \n line_ids = fields.One2many('account.move.line', 'move_id', string='Journal Items', copy=True, readonly=True,\n states={'draft': [('readonly', False)]})\n \n quantity = fields.Float(string='Poids',default=1.0, related=\"line_ids.quantity\")\n \n quantity_poids_total = fields.Float(string='somme des poids', digits='Product Unit of Measure', compute=\"_quantity_poids_total\")\n \n \n \n @api.onchange('quantity', 'line_ids')\n def _quantity_poids_total(self):\n for rec in self:\n total = sum(rec.line_ids.mapped('quantity'))\n rec.quantity_poids_total = total\n \n\n agrement = fields.Selection(selection=[('001', '001/92/C'), ('0003', '003/17/CE')], string=\"Agrément\")\n airport = fields.Many2one('optesis.airport', string='Aréoport')\n lta = fields.Char(string='L.T.A')\n transit = fields.Many2one('optesis.transit', string='Transitaire')\n amount_text = fields.Char('Montant en lettres', compute='get_amount_text')\n\n \n @api.depends('amount_total', 'currency_id')\n def get_amount_text(self):\n number_in_word = num2words(self.amount_total, lang='fr')\n self.amount_text = number_in_word and number_in_word.capitalize()\n\n\nclass AccountMoveLine(models.Model):\n _inherit= \"account.move.line\"\n \n quantity = fields.Float(string='Poids',\n default=1.0, digits='Product Unit of Measure',\n help=\"The optional quantity expressed by this line, eg: number of product sold. \"\n \"The quantity is not a legal requirement but is very useful for some reports.\")\n \n\n nb_colis = fields.Float(string='Nombre de colis')\n agrement = fields.Selection(selection=[('001', '001/92/C'), ('0003', '003/17/CE')], related='move_id.agrement', store=True, copy=False, index=True, readonly=False)\n airport = fields.Many2one('optesis.airport', related='move_id.airport', store=True, copy=False, index=True, readonly=False)\n #lta = fields.Many2one('optesis.lta', related='move_id.lta', store=True, copy=False, index=True, readonly=False)\n transit = fields.Many2one('optesis.transit', related='move_id.transit', store=True, copy=False, index=True, readonly=False)\n transformation = fields.Many2one('optesis.transformation', string='Transformation')\n calibre = fields.Many2one('optesis.calibre', string='Calibre')\n \n\n \n @api.model\n def _sale_prepare_sale_line_values(self, order, price):\n \"\"\" Generate the sale.line creation value from the current move line \"\"\"\n self.ensure_one()\n last_so_line = self.env['sale.order.line'].search([('order_id', '=', order.id)], order='sequence desc', limit=1)\n last_sequence = last_so_line.sequence + 1 if last_so_line else 100\n\n fpos = order.fiscal_position_id or order.partner_id.property_account_position_id\n taxes = fpos.map_tax(self.product_id.taxes_id, self.product_id, order.partner_id)\n\n return {\n 'order_id': order.id,\n 'name': self.name,\n 'sequence': last_sequence,\n 'price_unit': price,\n 'tax_id': [x.id for x in taxes],\n 'discount': 0.0,\n 'product_id': self.product_id.id,\n 'transformation': self.transformation_id.id,\n 'calibre': self.calibre_id.id,\n 'product_uom': self.product_uom_id.id,\n 'product_uom_qty': 0.0,\n 'is_expense': True,\n }\n \n @api.model\n def _prepare_analytic_line(self):\n \"\"\" Prepare the values used to create() an account.analytic.line upon validation of an account.move.line having\n an analytic account. This method is intended to be extended in other modules.\n :return list of values to create analytic.line\n :rtype list\n \"\"\"\n result = []\n for move_line in self:\n amount = (move_line.credit or 0.0) - (move_line.debit or 0.0)\n default_name = move_line.name or (move_line.ref or '/' + ' -- ' + (move_line.partner_id and move_line.partner_id.name or '/'))\n result.append({\n 'name': default_name,\n 'date': move_line.date,\n 'account_id': move_line.analytic_account_id.id,\n 'group_id': move_line.analytic_account_id.group_id.id,\n 'tag_ids': [(6, 0, move_line._get_analytic_tag_ids())],\n 'unit_amount': move_line.quantity,\n 'calibre':move_line.calibre,\n 'nb_colis':move_line.nb_colis,\n 'product_id': move_line.product_id and move_line.product_id.id or False,\n 'product_uom_id': move_line.product_uom_id and move_line.product_uom_id.id or False,\n 'amount': amount,\n 'general_account_id': move_line.account_id.id,\n 'ref': move_line.ref,\n 'move_id': move_line.id,\n 'user_id': move_line.move_id.invoice_user_id.id or self._uid,\n 'partner_id': move_line.partner_id.id,\n 'company_id': move_line.analytic_account_id.company_id.id or self.env.company.id,\n })\n return result\n @api.model\n def _copy_data_extend_business_fields(self, values):\n # OVERRIDE to copy the 'purchase_line_id' field as well.\n super(AccountMoveLine, self)._copy_data_extend_business_fields(values)\n values['purchase_line_id'] = self.purchase_line_id.id\n calibre = self.purchase_line_id.calibre\n ","sub_path":"delphinus/models/acccount_move.py","file_name":"acccount_move.py","file_ext":"py","file_size_in_byte":5587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"172239424","text":"#!usr/bin/python3\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.stats as st\nfrom aima3.agents import *\nfrom misio.aima import * \n\ncurrent_position = random.choice([0,1])\nloc = [0, 0]\niter, ac = -1, -1\nflag = False\n\ndef MyAgent(): \n def program(percept): \n global current_position, loc, iter, ac, flag \n location, status = percept \n loc[location[0]] = (1 if status == 'Dirty' else 0) # status\n iter += 1\n ac += 1\n\n if loc[current_position] == 1:\n loc[current_position] = 0\n flag = True\n return 'Suck'\n elif (ac == 0) or (ac == 1 and flag):\n if current_position == 0: return 'Right'\n else: return 'Left'\n elif sum(loc) == 0 and iter < 8: \n return 'NoOp'\n elif loc[current_position] == 0 and current_position == 0:\n iter = 0\n current_position = 1\n return 'Right'\n elif loc[current_position] == 0 and current_position == 1:\n iter = 0\n current_position = 0 \n return 'Left'\n \n return Agent(program)\n\n# params\nno_samples = 50000\nn = 1\nsteps = 50\nconfidence = .95\n\n# default chart\ndef agent_factory_1():\n return MyAgent()\n\ndef env_factory():\n return TrivialVacuumEnvironmentWithChildren(random_dirt_prob=0.05)\n\ndef run_agent(EnvFactory, AgentFactory, n=10, steps=1000):\n envs = [EnvFactory() for i in range(n)]\n return test_agent(AgentFactory, steps, copy.deepcopy(envs))\n\ndata = [run_agent(env_factory, agent_factory_1, n, steps) for _ in range(no_samples)]\n\nprint(f\"Exp. val. {np.mean(data)} - std. dev. {np.std(data)}\")\nprint(st.norm.interval(confidence, loc=np.mean(data), scale=st.sem(data)))\n\nplt.style.use(\"seaborn-deep\")\nplt.hist(data, density=True, bins=20)\nplt.show()","sub_path":"lab1/agent-histogram.py","file_name":"agent-histogram.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"70147897","text":"import pandas as pd\nimport statsmodels.api as sm \nimport numpy as np\nimport statsmodels\n\nclass Lab3(object):\n \n def create_data(self,snp_lines) :\n '''\n Input - the snp_lines parsed at the beginning of the notebook\n Output - You should return the 53 x 3902 dataframe\n '''\n #start code here\n data=np.zeros((53,3902))\n column_name=[]\n cur_list=[]\n for i in range(len(snp_lines)):\n cur_list=snp_lines[i].split()\n column_name.append(str(cur_list[0]+':'+cur_list[1]))\n for j in range(9,len(cur_list)):\n if (cur_list[j]=='0/0'):\n data[j-9][i]=0\n elif(cur_list[j]=='0/1'or cur_list[j]=='1/0'):\n data[j-9][i]=1\n elif(cur_list[j]=='1/1'):\n data[j-9][i]=2\n else:\n data[j-9][i]=np.nan\n df=pd.DataFrame(data,columns=column_name)\n return df\n \n \n \n #end code here\n\n def create_target(self,header_line) :\n '''\n Input - the header_line parsed at the beginning of the notebook\n Output - a list of values(either 0 or 1)\n '''\n #start code here\n data=header_line.split()[9:]\n phenotype=[]\n for i in range(len(data)):\n if data[i][0:4]=='dark':\n phenotype.append(0)\n else:\n phenotype.append(1)\n return phenotype\n #end code here\n \n def logistic_reg_per_snp(self,df) :\n '''\n Input - snp_data dataframe\n Output - list of pvalues and list of betavalues\n '''\n #start code here\n p=[]\n belta=[]\n head=df.columns[0:-1]\n for i in range(len(head)):\n x=sm.add_constant(df[head[i]])\n y=df[df.columns[-1]]\n classifier=sm.Logit(y,x,missing=\"drop\").fit(method='bfgs',disp='False')\n belta.append(round(classifier.params[1],5))\n p.append(round(classifier.pvalues[1],9))\n return p,belta\n #end code here\n \n \n def get_top_snps(self,snp_data,p_values) :\n '''\n Input - snp dataframe with target column and p_values calculated previously\n Output - list of 5 tuples, each with chromosome and position\n '''\n #start code here\n data=snp_data.columns[0:-1]\n maxium=max(p_values)\n p=[]\n output=[]\n while(len(p)<5):\n id=np.argmin(p_values)\n p.append(id)\n p_values[id]=maxium+1\n for idx in p:\n row=data[idx].split(':')\n output.append((row[0],row[1]))\n return output\n \n \n #end code here","sub_path":"Genomics_Lab3/.ipynb_checkpoints/main-checkpoint.py","file_name":"main-checkpoint.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"145716408","text":"KAPASITEETTI = 5\nOLETUSKASVATUS = 5\n\n\nclass IntJoukko:\n def __init__(self, kapasiteetti=None, kasvatuskoko=None):\n self.kapasiteetti = self.kapasiteetti_kasvatuskoko_tsek(kapasiteetti, kapasiteetti, KAPASITEETTI)\n self.kasvatuskoko = self.kapasiteetti_kasvatuskoko_tsek(kasvatuskoko, kapasiteetti, OLETUSKASVATUS)\n self.ljono = [0] * self.kapasiteetti\n self.alkioiden_lkm = 0\n\n def kapasiteetti_kasvatuskoko_tsek(self, arvo, kapasiteetti, ifnone):\n if arvo is None:\n return ifnone\n elif not isinstance(kapasiteetti, int) or kapasiteetti < 0:\n raise Exception(\"Väärä kapasiteetti\") # heitin vaan jotain :D\n else:\n return kapasiteetti\n\n def kuuluu(self, n):\n for i in range(0, self.alkioiden_lkm):\n if n == self.ljono[i]:\n return True \n return False\n\n\n\n def lisaa(self, n):\n if self.alkioiden_lkm == 0:\n self.ljono[0] = n\n self.alkioiden_lkm += 1\n return True\n else:\n pass\n\n if not self.kuuluu(n):\n self.lisaa_n_ei_kuulu(n)\n return True\n\n return False\n\n def lisaa_n_ei_kuulu(self,n):\n self.ljono[self.alkioiden_lkm] = n\n self.alkioiden_lkm += 1\n if self.alkioiden_lkm % len(self.ljono) == 0:\n taulukko_old = self.ljono\n self.kopioi_taulukko(self.ljono, taulukko_old)\n self.ljono = [0] * (self.alkioiden_lkm + self.kasvatuskoko)\n self.kopioi_taulukko(taulukko_old, self.ljono) \n\n def poista(self, n):\n nIndeksi = self.indeksin_etsinta(n)\n if nIndeksi != -1:\n self.listan_lyhentaminen(nIndeksi)\n return True\n\n return False\n\n def indeksin_etsinta(self, n):\n nIndeksi = -1\n for i in range(0, self.alkioiden_lkm):\n if n == self.ljono[i]:\n nIndeksi = i # siis luku löytyy tuosta kohdasta :D\n self.ljono[i] = 0\n break\n return nIndeksi\n\n def listan_lyhentaminen(self, i):\n apu = 0\n for j in range(i, self.alkioiden_lkm - 1):\n apu = self.ljono[j]\n self.ljono[j] = self.ljono[j + 1]\n self.ljono[j + 1] = apu\n\n self.alkioiden_lkm = self.alkioiden_lkm - 1\n\n def kopioi_taulukko(self, a, b):\n for i in range(0, len(a)):\n b[i] = a[i]\n\n def mahtavuus(self):\n return self.alkioiden_lkm\n\n def to_int_list(self):\n taulu = [0] * self.alkioiden_lkm\n\n for i in range(0, len(taulu)):\n taulu[i] = self.ljono[i]\n\n return taulu\n\n @staticmethod\n def yhdiste(a, b):\n x = IntJoukko()\n a_taulu = a.to_int_list()\n b_taulu = b.to_int_list()\n\n for i in range(0, len(a_taulu)):\n x.lisaa(a_taulu[i])\n\n for i in range(0, len(b_taulu)):\n x.lisaa(b_taulu[i])\n\n return x\n\n @staticmethod\n def leikkaus(a, b):\n y = IntJoukko()\n a_taulu = a.to_int_list()\n b_taulu = b.to_int_list()\n\n for i in range(0, len(a_taulu)):\n for j in range(0, len(b_taulu)):\n if a_taulu[i] == b_taulu[j]:\n y.lisaa(b_taulu[j])\n\n return y\n\n @staticmethod\n def erotus(a, b):\n z = IntJoukko()\n a_taulu = a.to_int_list()\n b_taulu = b.to_int_list()\n\n for i in range(0, len(a_taulu)):\n z.lisaa(a_taulu[i])\n\n for i in range(0, len(b_taulu)):\n z.poista(b_taulu[i])\n\n return z\n\n def __str__(self):\n if self.alkioiden_lkm == 0:\n return \"{}\"\n elif self.alkioiden_lkm == 1:\n return \"{\" + str(self.ljono[0]) + \"}\"\n else:\n tuotos = \"{\"\n for i in range(0, self.alkioiden_lkm - 1):\n tuotos = tuotos + str(self.ljono[i])\n tuotos = tuotos + \", \"\n tuotos = tuotos + str(self.ljono[self.alkioiden_lkm - 1])\n tuotos = tuotos + \"}\"\n return tuotos\n","sub_path":"viikko4/int-joukko/src/int_joukko.py","file_name":"int_joukko.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"344657867","text":"from __future__ import division, print_function\n \n\nimport MDAnalysis\nfrom matplotlib import pyplot as plt\nimport matplotlib as mpl\nfrom matplotlib import cm\nimport numpy as np\n\nimport glob, os\n\nmpl.rcParams.update({'axes.labelsize': 50})\nmpl.rcParams.update({'xtick.labelsize': 40})\nmpl.rcParams.update({'ytick.labelsize': 40})\nmpl.rcParams.update({'axes.titlesize':40})\nmpl.rcParams.update({'legend.fontsize':40})\n\nfnames = glob.glob('*/surf_dat.dat')\nlabels = []\nvals = np.zeros((len(fnames), 14), dtype=float)\n\nfor i, fname in enumerate(fnames):\n dirname = os.path.dirname(fname)\n labels.append(dirname)\n vals[i,...] = np.loadtxt(fname)\nlabels = np.array(labels)\n\nname_lup = {'1brs': 'barnase',\n '1ubq': 'ubiquitin',\n '1qgt': 'capsid',\n '1ubq': 'ubiquitin',\n '1ycr': 'MDM2',\n '253l': 'lysozyme',\n '2b97': 'hydrophobin',\n '3hhp': 'malate\\ndehydrogenase'}\n\norder = ['hydrophobin', 'capsid', 'MDM2', 'malate\\ndehydrogenase', 'ubiquitin', 'barnase', 'lysozyme']\n\ncolors = cm.rainbow(np.linspace(0,1,len(order)))\n\norder_idx = np.zeros(len(order), dtype=int)\nfor idx, label in enumerate(labels):\n if name_lup[label] in order:\n order_idx[order.index(name_lup[label])] = idx\n\nvals = vals[order_idx,...]\nlabels = labels[order_idx]\n\nnames = [name_lup[label] for label in labels]\ndipole = {k:v for k,v in zip(np.loadtxt('dipole.dat', usecols=0, dtype=str), np.loadtxt('dipole.dat', usecols=1))}\n\nn_bars = len(labels)\nindices = np.arange(n_bars)\nwidth = 1\n\ngap = 4\n\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,6))\n\n# upper left\nfor idx, name in enumerate(names):\n label = labels[idx]\n n_tot, n_surf, n_res_surf, n_phil_surf, n_phob_surf, n_phob_res, pos_charge_res, neg_charge_res, n_surf_h, n_phob_h, n_hydrophilic_res_atoms, n_hydrophilic_res_atoms_phob, n_hydrophobic_res_atoms, n_hydrophobic_res_atoms_phob = vals[idx] \n this_dipole = dipole[label]\n\n ax1.bar(idx, n_hydrophobic_res_atoms_phob/n_hydrophobic_res_atoms, label=label, color=colors[idx], width=width)\n ax2.bar(idx, n_hydrophilic_res_atoms_phob/n_hydrophilic_res_atoms, label=label, color=colors[idx], width=width)\n\nax1.set_xticks([])\nax1.set_ylim(0.4, 0.9)\nax1.set_title('hydrophobic res')\n\nax2.set_xticks([])\nax2.set_ylim(0.4, 0.9)\nax2.set_title('hydrophilic res')\n\nfig.tight_layout()\nfig.subplots_adjust(hspace=0.3)\nfig.savefig('/Users/nickrego/Desktop/blah.pdf', transparent=True)\n\n\n","sub_path":"scratch/prot_hydrophobicity_comm_scripts/fig_hydrophobic_frac.py","file_name":"fig_hydrophobic_frac.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"314355768","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass LogisticsShopStatusDTO(object):\n\n def __init__(self):\n self._audit_desc = None\n self._logistics_code = None\n self._logistics_name = None\n self._status = None\n\n @property\n def audit_desc(self):\n return self._audit_desc\n\n @audit_desc.setter\n def audit_desc(self, value):\n self._audit_desc = value\n @property\n def logistics_code(self):\n return self._logistics_code\n\n @logistics_code.setter\n def logistics_code(self, value):\n self._logistics_code = value\n @property\n def logistics_name(self):\n return self._logistics_name\n\n @logistics_name.setter\n def logistics_name(self, value):\n self._logistics_name = value\n @property\n def status(self):\n return self._status\n\n @status.setter\n def status(self, value):\n self._status = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.audit_desc:\n if hasattr(self.audit_desc, 'to_alipay_dict'):\n params['audit_desc'] = self.audit_desc.to_alipay_dict()\n else:\n params['audit_desc'] = self.audit_desc\n if self.logistics_code:\n if hasattr(self.logistics_code, 'to_alipay_dict'):\n params['logistics_code'] = self.logistics_code.to_alipay_dict()\n else:\n params['logistics_code'] = self.logistics_code\n if self.logistics_name:\n if hasattr(self.logistics_name, 'to_alipay_dict'):\n params['logistics_name'] = self.logistics_name.to_alipay_dict()\n else:\n params['logistics_name'] = self.logistics_name\n if self.status:\n if hasattr(self.status, 'to_alipay_dict'):\n params['status'] = self.status.to_alipay_dict()\n else:\n params['status'] = self.status\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = LogisticsShopStatusDTO()\n if 'audit_desc' in d:\n o.audit_desc = d['audit_desc']\n if 'logistics_code' in d:\n o.logistics_code = d['logistics_code']\n if 'logistics_name' in d:\n o.logistics_name = d['logistics_name']\n if 'status' in d:\n o.status = d['status']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/LogisticsShopStatusDTO.py","file_name":"LogisticsShopStatusDTO.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"466679937","text":"\"\"\"\nCopyright (c) 2014, Samsung Electronics Co.,Ltd.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nThe views and conclusions contained in the software and documentation are those\nof the authors and should not be interpreted as representing official policies,\neither expressed or implied, of Samsung Electronics Co.,Ltd..\n\"\"\"\n\n\"\"\"\nopencl4py - OpenCL cffi bindings and helper classes.\nURL: https://github.com/ajkxyz/opencl4py\nOriginal author: Alexey Kazantsev \n\"\"\"\n\n\"\"\"\nTests some of the api in opencl4py package.\n\"\"\"\nimport unittest\nimport logging\nimport opencl4py as cl\nimport os\n\n\nclass Test(unittest.TestCase):\n def setUp(self):\n logging.basicConfig(level=logging.DEBUG)\n self.old_env = os.environ.get(\"PYOPENCL_CTX\")\n if self.old_env is None:\n os.environ[\"PYOPENCL_CTX\"] = \"0:0\"\n self.src_test = (\n \"\"\"\n #include \"test.cl\"\n \"\"\")\n self.include_dirs = (\"\", os.path.dirname(__file__), \".\")\n\n def tearDown(self):\n if self.old_env is None:\n del os.environ[\"PYOPENCL_CTX\"]\n else:\n os.environ[\"PYOPENCL_CTX\"] = self.old_env\n del self.old_env\n\n def test_constants(self):\n self.assertEqual(cl.CL_DEVICE_TYPE_CPU, 2)\n self.assertEqual(cl.CL_DEVICE_TYPE_GPU, 4)\n self.assertEqual(cl.CL_DEVICE_TYPE_ACCELERATOR, 8)\n self.assertEqual(cl.CL_DEVICE_TYPE_CUSTOM, 16)\n self.assertEqual(cl.CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, 1)\n self.assertEqual(cl.CL_MAP_READ, 1)\n self.assertEqual(cl.CL_MAP_WRITE, 2)\n self.assertEqual(cl.CL_MAP_WRITE_INVALIDATE_REGION, 4)\n self.assertEqual(cl.CL_MEM_READ_WRITE, 1)\n self.assertEqual(cl.CL_MEM_WRITE_ONLY, 2)\n self.assertEqual(cl.CL_MEM_READ_ONLY, 4)\n self.assertEqual(cl.CL_MEM_USE_HOST_PTR, 8)\n self.assertEqual(cl.CL_MEM_ALLOC_HOST_PTR, 16)\n self.assertEqual(cl.CL_MEM_COPY_HOST_PTR, 32)\n\n def test_dump_devices(self):\n platforms = cl.Platforms()\n s = platforms.dump_devices()\n del s\n\n def test_create_context(self):\n platforms = cl.Platforms()\n ctx = cl.Context(platforms.platforms[0],\n platforms.platforms[0].devices[0:1])\n del ctx\n\n def test_create_some_context(self):\n platforms = cl.Platforms()\n ctx = platforms.create_some_context()\n del ctx\n\n def test_realign_numpy_array(self):\n try:\n import numpy\n except ImportError: # for pypy\n try:\n import numpypy as numpy\n except ImportError:\n raise ImportError(\"Could not import numpy\")\n a = numpy.empty(1000, dtype=numpy.float32)\n a = cl.realign_array(a, 1056, numpy)\n self.assertEqual(a.__array_interface__[\"data\"][0] % 1056, 0)\n\n def test_device_info(self):\n platforms = cl.Platforms()\n ctx = platforms.create_some_context()\n dev = ctx.devices[0]\n self.assertGreater(dev.max_work_item_dimensions, 0)\n self.assertEqual(len(dev.max_work_item_sizes),\n dev.max_work_item_dimensions)\n for size in dev.max_work_item_sizes:\n self.assertGreater(size, 0)\n self.assertIsInstance(dev.driver_version.encode(\"utf-8\"), bytes)\n self.assertGreater(len(dev.driver_version), 0)\n try:\n self.assertIsInstance(dev.built_in_kernels, list)\n for krn in dev.built_in_kernels:\n self.assertIsInstance(krn, str)\n self.assertGreater(len(krn), 0)\n except cl.CLRuntimeError as e:\n if dev.version >= 1.2:\n raise\n self.assertEqual(e.code, -30)\n self.assertIsInstance(dev.extensions, list)\n for ext in dev.extensions:\n self.assertIsInstance(ext.encode(\"utf-8\"), bytes)\n self.assertGreater(len(ext), 0)\n self.assertGreater(dev.preferred_vector_width_int, 0)\n self.assertGreater(dev.max_work_group_size, 1)\n self.assertTrue(dev.available)\n\n def test_program_info(self):\n platforms = cl.Platforms()\n ctx = platforms.create_some_context()\n prg = ctx.create_program(self.src_test, self.include_dirs)\n self.assertGreater(prg.reference_count, 0)\n try:\n self.assertEqual(prg.num_kernels, 1)\n names = prg.kernel_names\n self.assertIsInstance(names, list)\n self.assertEqual(len(names), 1)\n self.assertEqual(names[0], \"test\")\n except cl.CLRuntimeError as e:\n if prg.devices[0].version >= 1.2:\n raise\n self.assertEqual(e.code, -30)\n bins = prg.binaries\n self.assertEqual(len(bins), 1)\n self.assertIsInstance(bins[0], bytes)\n self.assertGreater(len(bins[0]), 0)\n\n def test_kernel_info(self):\n platforms = cl.Platforms()\n ctx = platforms.create_some_context()\n prg = ctx.create_program(self.src_test, self.include_dirs)\n krn = prg.get_kernel(\"test\")\n self.assertGreater(krn.reference_count, 0)\n self.assertEqual(krn.num_args, 3)\n try:\n self.assertEqual(krn.attributes, \"vec_type_hint(float4)\")\n except cl.CLRuntimeError as e:\n self.assertEqual(e.code, -30)\n\n def test_binary(self):\n platforms = cl.Platforms()\n ctx = platforms.create_some_context()\n prg = ctx.create_program(self.src_test, self.include_dirs)\n binary = prg.binaries[0]\n prg = ctx.create_program([binary], binary=True)\n krn = prg.get_kernel(\"test\")\n\n def set_kernel_args(self):\n platforms = cl.Platforms()\n ctx = platforms.create_some_context()\n prg = ctx.create_program(self.src_test, self.include_dirs)\n krn = prg.get_kernel(\"test\")\n queue = ctx.create_queue(ctx.devices[0])\n global_size = [a.size]\n local_size = None\n\n krn.set_args(cl.skip(3))\n self.assertRaises(CLRuntimeError,\n queue.execute_kernel(krn, global_size, local_size))\n krn.set_args(cl.skip. cl.skip, cl.skip)\n self.assertRaises(CLRuntimeError,\n queue.execute_kernel(krn, global_size, local_size))\n krn.set_args(cl.skip(1). cl.skip(1), cl.skip(1))\n self.assertRaises(CLRuntimeError,\n queue.execute_kernel(krn, global_size, local_size))\n krn.set_args(cl.skip(1000))\n self.assertRaises(CLRuntimeError,\n queue.execute_kernel(krn, global_size, local_size))\n self.assertRaises(ValueError, cl.skip, 0)\n self.assertRaises(ValueError, cl.skip, -1)\n\n c = numpy.array([1.2345], dtype=numpy.float32)\n krn.set_args(cl.skip(2), c)\n self.assertRaises(CLRuntimeError,\n queue.execute_kernel(krn, global_size, local_size))\n krn.set_args(cl.skip, cl.skip, c)\n self.assertRaises(CLRuntimeError,\n queue.execute_kernel(krn, global_size, local_size))\n\n def test_api_numpy(self):\n try:\n import numpy\n except ImportError: # for pypy\n try:\n import numpypy as numpy\n except ImportError:\n raise ImportError(\"Could not import numpy\")\n # Create platform, context, program, kernel and queue\n platforms = cl.Platforms()\n ctx = platforms.create_some_context()\n prg = ctx.create_program(self.src_test, self.include_dirs)\n krn = prg.get_kernel(\"test\")\n queue = ctx.create_queue(ctx.devices[0])\n\n # Create arrays with some values for testing\n a = numpy.arange(100000, dtype=numpy.float32)\n b = numpy.cos(a)\n a = numpy.sin(a)\n a_copy = a.copy()\n\n # Prepare arrays for use with map_buffer\n a = cl.realign_array(a, queue.device.memalign, numpy)\n b = cl.realign_array(b, queue.device.memalign, numpy)\n c = numpy.array([1.2345], dtype=numpy.float32)\n d = a + b * c[0]\n\n # Create buffers\n a_ = ctx.create_buffer(cl.CL_MEM_READ_WRITE | cl.CL_MEM_USE_HOST_PTR,\n a)\n b_ = ctx.create_buffer(cl.CL_MEM_READ_WRITE | cl.CL_MEM_USE_HOST_PTR,\n b)\n\n # Set kernel arguments\n krn.set_args(a_, b_, c[0:1])\n\n # Execute kernel\n global_size = [a.size]\n local_size = None\n queue.execute_kernel(krn, global_size, local_size, need_event=False)\n\n # Get results back from the device by map_buffer\n ev, ptr = queue.map_buffer(a_, cl.CL_MAP_READ, a.nbytes)\n del ev\n ev = queue.unmap_buffer(a_, ptr)\n ev.wait()\n self.assertLess(numpy.fabs(a - d).max(), 0.0001,\n \"Incorrect result after map_buffer\")\n\n # Get results back from the device by read_buffer\n aa = numpy.zeros(a.shape, dtype=a.dtype)\n queue.read_buffer(a_, aa)\n self.assertLess(numpy.fabs(aa - d).max(), 0.0001,\n \"Incorrect result after read_buffer\")\n\n # Refill buffer with stored copy by map_buffer with event\n ev, ptr = queue.map_buffer(\n a_, cl.CL_MAP_WRITE if queue.device.version < 1.1999\n else cl.CL_MAP_WRITE_INVALIDATE_REGION, a.nbytes,\n blocking=False, need_event=True)\n ev.wait()\n a[:] = a_copy[:]\n ev = queue.unmap_buffer(a_, ptr)\n\n # Execute kernel\n ev = queue.execute_kernel(krn, global_size, local_size, wait_for=(ev,))\n # Get results back from the device by map_buffer\n ev, ptr = queue.map_buffer(a_, cl.CL_MAP_READ, a.nbytes,\n wait_for=(ev,), need_event=True)\n ev.wait()\n ev = queue.unmap_buffer(a_, ptr)\n ev.wait()\n self.assertLess(numpy.fabs(a - d).max(), 0.0001,\n \"Incorrect result after map_buffer\")\n\n # Refill buffer with stored copy by write_buffer\n ev = queue.write_buffer(a_, a_copy, blocking=False, need_event=True)\n\n # Execute kernel\n ev = queue.execute_kernel(krn, global_size, local_size, wait_for=(ev,))\n # Get results back from the device by map_buffer\n ev, ptr = queue.map_buffer(a_, cl.CL_MAP_READ, a.nbytes,\n wait_for=(ev,), need_event=True)\n ev.wait()\n ev = queue.unmap_buffer(a_, ptr)\n ev.wait()\n self.assertLess(numpy.fabs(a - d).max(), 0.0001,\n \"Incorrect result after map_buffer\")\n\n def test_api_nonumpy(self):\n import math\n # Create platform, context, program, kernel and queue\n platforms = cl.Platforms()\n ctx = platforms.create_some_context()\n prg = ctx.create_program(self.src_test, self.include_dirs)\n krn = prg.get_kernel(\"test\")\n # Create command queue\n queue = ctx.create_queue(ctx.devices[0])\n\n # Create arrays with some values for testing\n N = 100000\n _a = cl.ffi.new(\"float[]\", N + queue.device.memalign)\n sz = int(cl.ffi.cast(\"size_t\", _a))\n if sz % queue.device.memalign != 0:\n sz += queue.device.memalign - (sz % queue.device.memalign)\n a = cl.ffi.cast(\"float*\", sz)\n else:\n a = _a\n _b = cl.ffi.new(\"float[]\", N + queue.device.memalign)\n sz = int(cl.ffi.cast(\"size_t\", _b))\n if sz % queue.device.memalign != 0:\n sz += queue.device.memalign - (sz % queue.device.memalign)\n b = cl.ffi.cast(\"float*\", sz)\n else:\n b = _b\n c = cl.ffi.new(\"float[]\", 1)\n c[0] = 1.2345\n d = cl.ffi.new(\"float[]\", N)\n sz = cl.ffi.sizeof(d)\n for i, t in enumerate(d):\n a[i] = math.sin(i)\n b[i] = math.cos(i)\n d[i] = a[i] + b[i] * c[0]\n a_copy = cl.ffi.new(\"float[]\", N)\n a_copy[0:N] = a[0:N]\n\n # Create buffers\n a_ = ctx.create_buffer(cl.CL_MEM_READ_WRITE | cl.CL_MEM_USE_HOST_PTR,\n a, size=sz)\n b_ = ctx.create_buffer(cl.CL_MEM_READ_WRITE | cl.CL_MEM_USE_HOST_PTR,\n b, size=sz)\n\n # Set kernel arguments\n krn.set_arg(0, a_)\n krn.set_arg(1, b_)\n krn.set_arg(2, cl.ffi.cast(\"const void*\", c), cl.ffi.sizeof(c))\n\n # Execute kernel\n global_size = [N]\n local_size = None\n queue.execute_kernel(krn, global_size, local_size, need_event=False)\n\n # Get results back from the device by map_buffer\n ev, ptr = queue.map_buffer(a_, cl.CL_MAP_READ, sz)\n del ev\n ev = queue.unmap_buffer(a_, ptr)\n ev.wait()\n mx = 0\n for i, t in enumerate(d):\n mx = max(mx, math.fabs(a[i] - t))\n self.assertLess(mx, 0.0001, \"Incorrect result after map_buffer\")\n\n # Get results back from the device by read_buffer\n aa = cl.ffi.new(\"float[]\", N)\n queue.read_buffer(a_, aa, size=sz)\n mx = 0\n for i, t in enumerate(d):\n mx = max(mx, math.fabs(aa[i] - t))\n self.assertLess(mx, 0.0001, \"Incorrect result after read_buffer\")\n\n # Refill buffer with stored copy by map_buffer with event\n ev, ptr = queue.map_buffer(\n a_, cl.CL_MAP_WRITE if queue.device.version < 1.1999\n else cl.CL_MAP_WRITE_INVALIDATE_REGION, sz,\n blocking=False, need_event=True)\n ev.wait()\n a[0:N] = a_copy[0:N]\n ev = queue.unmap_buffer(a_, ptr)\n\n # Execute kernel\n ev = queue.execute_kernel(krn, global_size, local_size, wait_for=(ev,))\n # Get results back from the device by map_buffer\n ev, ptr = queue.map_buffer(a_, cl.CL_MAP_READ, sz,\n wait_for=(ev,), need_event=True)\n ev.wait()\n ev = queue.unmap_buffer(a_, ptr)\n ev.wait()\n mx = 0\n for i, t in enumerate(d):\n mx = max(mx, math.fabs(a[i] - t))\n self.assertLess(mx, 0.0001, \"Incorrect result after map_buffer\")\n\n # Refill buffer with stored copy by write_buffer\n ev = queue.write_buffer(a_, a_copy, size=sz,\n blocking=False, need_event=True)\n\n # Execute kernel\n ev = queue.execute_kernel(krn, global_size, local_size, wait_for=(ev,))\n # Get results back from the device by map_buffer\n ev, ptr = queue.map_buffer(a_, cl.CL_MAP_READ, sz,\n wait_for=(ev,), need_event=True)\n ev.wait()\n ev = queue.unmap_buffer(a_, ptr)\n ev.wait()\n mx = 0\n for i, t in enumerate(d):\n mx = max(mx, math.fabs(a[i] - t))\n self.assertLess(mx, 0.0001, \"Incorrect result after map_buffer\")\n\n del _b\n del _a\n\n def test_event_profiling(self):\n import numpy\n # Create platform, context, program, kernel and queue\n platforms = cl.Platforms()\n ctx = platforms.create_some_context()\n prg = ctx.create_program(self.src_test, self.include_dirs)\n krn = prg.get_kernel(\"test\")\n queue = ctx.create_queue(ctx.devices[0], cl.CL_QUEUE_PROFILING_ENABLE)\n\n # Create arrays with some values for testing\n a = numpy.arange(100000, dtype=numpy.float32)\n b = numpy.cos(a)\n a = numpy.sin(a)\n c = numpy.array([1.2345], dtype=numpy.float32)\n\n # Create buffers\n a_ = ctx.create_buffer(cl.CL_MEM_READ_WRITE | cl.CL_MEM_COPY_HOST_PTR,\n a)\n b_ = ctx.create_buffer(cl.CL_MEM_READ_ONLY | cl.CL_MEM_COPY_HOST_PTR,\n b)\n\n # Set kernel arguments\n krn.set_arg(0, a_)\n krn.set_arg(1, b_)\n krn.set_arg(2, c[0:1])\n\n # Execute kernel\n ev = queue.execute_kernel(krn, [a.size], None)\n ev.wait()\n\n try:\n vles, errs = ev.get_profiling_info()\n self.assertEqual(vles, ev.profiling_values)\n self.assertEqual(errs, ev.profiling_errors)\n except cl.CLRuntimeError:\n pass\n for name, vle in ev.profiling_values.items():\n err = ev.profiling_errors[name]\n self.assertTrue((vle and not err) or (not vle and err))\n self.assertEqual(type(vle), float)\n self.assertEqual(type(err), int)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":17687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"253376274","text":"class Solution:\n def partition(self, nums, p, r):\n l = p - 1\n while p < r:\n if nums[p] >= nums[r]:\n l += 1\n nums[l], nums[p] = nums[p], nums[l]\n p += 1\n nums[l + 1], nums[r] = nums[r], nums[l + 1]\n return l + 1\n\n\n # def quickSort(self, nums, s, e):\n # if s < e:\n # mid = self.partition(nums, s, e)\n # self.quickSort(nums, s, mid - 1)\n # self.quickSort(nums, mid + 1, e)\n\n\n def findKthLargest(self, nums, k):\n if nums:\n pos = self.partition(nums, 0, len(nums) - 1)\n if k < pos + 1:\n return self.findKthLargest(nums[:pos], k)\n elif k > pos + 1:\n return self.findKthLargest(nums[pos + 1:], k - pos - 1)\n else:\n return nums[pos]\n\nif __name__ == \"__main__\":\n s_instance = Solution()\n nums = [3, 2, 1, 5, 6, 6, 4]\n print(s_instance.findKthLargest(nums, 4))\n","sub_path":"algorithm/Kth Largest Element in An Array/demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"12291919","text":"#Code For City 02: Jaipur\nimport random\ndef randomSolution(tsp):\n cities = list(range(len(tsp)))\n solution = []\n for i in range (len(tsp)):\n randomCity = cities[random.randint(0,len(cities)-1)]\n solution.append(randomCity)\n cities.remove(randomCity)\n \n \n return solution\n\ndef routeLen(tsp,solution):\n routelen =0\n for i in range(len(solution)):\n routelen += tsp[solution[i-1]] [solution[i]]\n \n return routelen \n \n\ndef getneibours(solution):\n neibours =[]\n length =[]\n for i in range (len(solution)):\n for j in range (i+1,len(solution)):\n neibour = solution.copy()\n neibour[i] = solution[j]\n neibour[j] =solution[i]\n neibours.append(neibour)\n \n return neibours \n \n\ndef getsoln(tsp,neibours):\n bestlen =routeLen(tsp,neibours[0])\n bestsoln = neibours[0]\n for neibour in neibours:\n \n currentroutelen =routeLen(tsp,neibour)\n if currentroutelen Amber Fort,1->Nahargarh Fort,2->Hawa Mahal,3->Jal Mahal,4->Jantar Mantar ]\")\n print(\"Current Optimal(Random) Solution: \")\n currentsoln = randomSolution(tsp)\n print(currentsoln)\n currentroutelen =routeLen(tsp,currentsoln)\n print(\"Total Distance:\")\n print(currentroutelen)\n neibour =getneibours(currentsoln)\n print(\"All possible Ways for Sightseeing are: \")\n print(neibour)\n bestsolution ,bestsolutionlen = getsoln(tsp,neibour)\n \n while bestsolutionlen ', self.click)\n self.bind('', self.restart)\n self.bind('', self.exit)\n\n self.gamestate=STATE_TITLE_SCREEN\n self.title_screen()\n\n self.board=[[EMPTY] * TILES for i in range(TILES)]\n\n def title_screen(self):\n self.canvas.delete('all')\n self.canvas.create_rectangle(0, 0, WINDOW_SIZE, WINDOW_SIZE, fill=TITLE_COLOR, outline='')\n self.canvas.create_text(WINDOW_SIZE/2, WINDOW_SIZE/3, text='TIC TAC TOE', fill=BG_COLOR, font=(FONT, int(-WINDOW_SIZE/12), 'bold'))\n self.canvas.create_text(int(WINDOW_SIZE/2), int(WINDOW_SIZE/2.5), text='[play]', fill=BG_COLOR, font=(FONT, int(-WINDOW_SIZE/25)))\n self.canvas.create_text(int(WINDOW_SIZE/2), int(WINDOW_SIZE/1.25), text='first move:', fill=BG_COLOR, font=(FONT, int(-WINDOW_SIZE/25)))\n self.canvas.create_text(int(WINDOW_SIZE/2), int(WINDOW_SIZE/1.15), text=('X' if FIRST_PLAYER==1 else 'O'), \n fill=X_COLOR if FIRST_PLAYER==1 else O_COLOR, font=(FONT, int(-WINDOW_SIZE/12)))\n\n def new_board(self):\n self.canvas.delete('all')\n\n self.board=[[EMPTY] * TILES for i in range(TILES)]\n\n for n in range(1, TILES):\n # vertikálně\n self.canvas.create_line(CELL_SIZE*n, 0, CELL_SIZE*n, WINDOW_SIZE, width=GRID_LINE_WIDTH, fill=GRID_COLOR)\n # horizontálně\n self.canvas.create_line(0, CELL_SIZE*n, WINDOW_SIZE, CELL_SIZE*n, width=GRID_LINE_WIDTH, fill=GRID_COLOR)\n\n def gameover_screen(self, result):\n self.canvas.delete('all')\n if result == 'X WINS':\n result_text = 'X wins'\n result_color = X_COLOR\n elif result == 'O WINS':\n result_text = 'O wins'\n result_color = O_COLOR\n elif result == 'DRAW':\n result_text = 'Draw'\n result_color = DRAW_SCREEN_COLOR\n\n self.canvas.create_rectangle(0, 0, WINDOW_SIZE, WINDOW_SIZE, fill=result_color, outline='')\n self.canvas.create_text(int(WINDOW_SIZE/2), int(WINDOW_SIZE/2), text=result_text, fill=BG_COLOR, font=(FONT, int(-WINDOW_SIZE/6), 'bold'))\n self.canvas.create_text(int(WINDOW_SIZE/2), int(WINDOW_SIZE/1.65), text='[click to play again]', fill=BG_COLOR, font=(FONT, int(-WINDOW_SIZE/25)))\n\n # Logika hry\n def click(self, event):\n x = self.pixels_to_grid(event.x)\n y = self.pixels_to_grid(event.y)\n\n if self.gamestate == STATE_TITLE_SCREEN:\n self.new_board()\n self.gamestate = FIRST_PLAYER\n\n elif (self.gamestate == STATE_X_TURN and self.board[y][x] == EMPTY):\n self.new_move(X, x, y)\n\n if self.has_won(X):\n self.gamestate = STATE_GAME_OVER\n self.gameover_screen('X WINS')\n elif self.is_a_draw():\n self.gamestate = STATE_GAME_OVER\n self.gameover_screen('DRAW')\n else:\n self.gamestate = STATE_O_TURN\n\n elif (self.gamestate == STATE_O_TURN and self.board[y][x] == EMPTY):\n self.new_move(O, x, y)\n\n if self.has_won(O):\n self.gamestate = STATE_GAME_OVER\n self.gameover_screen('O WINS')\n elif self.is_a_draw():\n self.gamestate = STATE_GAME_OVER\n self.gameover_screen('DRAW')\n else:\n self.gamestate = STATE_X_TURN\n\n elif self.gamestate == STATE_GAME_OVER:\n self.new_board()\n self.gamestate = FIRST_PLAYER\n\n for i in self.board:\n print(i)\n print(\"---\")\n\n # Logické vykonání tahu\n def new_move(self, player, grid_x, grid_y):\n if player == X:\n self.board[grid_y][grid_x] = X\n self.draw_X(grid_x, grid_y)\n\n elif player == O:\n self.board[grid_y][grid_x] = O\n self.draw_O(grid_x, grid_y)\n\n # Vykreslení daného symbolu do buňky, kterou hráč označil\n def draw_X(self, grid_x, grid_y):\n x = self.grid_to_pixels(grid_x)\n y = self.grid_to_pixels(grid_y)\n delta = CELL_SIZE/2*SYMBOL_SIZE\n\n self.canvas.create_line(x-delta, y-delta, x+delta, y+delta, width=SYMBOL_WIDTH, fill=X_COLOR)\n self.canvas.create_line(x+delta, y-delta, x-delta, y+delta, width=SYMBOL_WIDTH, fill=X_COLOR)\n\n def draw_O(self, grid_x, grid_y):\n x = self.grid_to_pixels(grid_x)\n y = self.grid_to_pixels(grid_y)\n delta = CELL_SIZE/2*SYMBOL_SIZE\n\n self.canvas.create_oval(x-delta, y-delta, x+delta, y+delta, width=SYMBOL_WIDTH, outline=O_COLOR)\n\n # Logika ukončení hry (výhra, remíza)\n def has_won(self, symbol):\n for x in range(TILES):\n for y in range(TILES-4):\n if self.board[x][y] == self.board[x][y+1] == self.board[x][y+2] == self.board[x][y+3] == self.board[x][y+4] == symbol:\n return True\n\n for y in range(TILES):\n for x in range(TILES-4):\n if self.board[x][y] == self.board[x+1][y] == self.board[x+2][y] == self.board[x+3][y] == self.board[x+4][y] == symbol:\n return True\n \n for x in range(TILES-4):\n for y in range(TILES-4):\n if self.board[x][y] == self.board[x+1][y+1] == self.board[x+2][y+2] == self.board[x+3][y+3] == self.board[x+4][y+4] == symbol:\n return True\n \n for x in range(TILES-4):\n for y in range(TILES-4):\n if self.board[x][y+4] == self.board[x+1][y+3] == self.board[x+2][y+2] == self.board[x+3][y+1] == self.board[x+4][y] == symbol:\n return True\n \n return False\n\n def is_a_draw(self):\n for row in self.board:\n if EMPTY in row:\n return False\n return True\n\n # Funkce umožňující detekci buňky, na kterou zrovna hráč klikl\n def pixels_to_grid(self, pixel_coord):\n if pixel_coord >= WINDOW_SIZE:\n pixel_coord = WINDOW_SIZE - 1 \n\n grid_coord = int(pixel_coord / CELL_SIZE)\n return grid_coord\n\n # Funkce sloužící k úmístění symbolu do středu buňky\n def grid_to_pixels(self, grid_coord):\n pixel_coord = grid_coord * CELL_SIZE + CELL_SIZE / 2\n return pixel_coord\n\n def restart(self, event):\n self.gamestate=STATE_TITLE_SCREEN\n self.title_screen()\n\n def exit(self, event):\n self.destroy()\n\ndef main():\n root = Game()\n root.mainloop()\n\nmain()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"614207568","text":"from flask import Flask, render_template, request, json\nimport re\napp = Flask(__name__)\n\ndef isNumber(user_input):\n\tit_is = False\n\ttry:\n\t\tfloat(user_input)\n\t\tit_is = True\n\texcept ValueError:\n\t\tit_is = False\n\treturn it_is\n\ndef swap(arr):\n\taux = 0\n\tn =len(arr)\n\ti = 0\n\tj = n-1\n\n\twhile i < n:\n\t\tif i < j:\n\t\t\taux = arr[i]\n\t\t\tarr[i] = arr[j]\n\t\t\tarr[j] = aux\n\t\tj = j - 1\n\t\ti = i + 1\n\n\treturn arr\n\ndef amplificar(arr,amp):\n\taux = 0\n\tret = []\n\tn =len(arr)\n\ti = 0\n\n\twhile i < n:\n\t\tret.append(float(arr[i])*amp)\n\t\ti = i + 1\n\n\treturn ret\n\n#Donde arr1 y arr2 son arrays, c1 y c2 son los ceros donde comienza cada array y n es la veces que se realizara la suma\ndef suma(arr1,arr2,c1,c2,n):\n\tarrRes=[]\n\ti=0\n\tr=c1-c2\n\tarrLen1 = len(arr1)\n\tarrLen2 = len(arr2)\n\twhile i= arrLen2:\n\t\t\t\t\tarrRes.append(float(arr1[i]))\n\t\t\t\telse:\n\t\t\t\t\tarrRes.append(float(arr2[i-r]))\n\t\ti=i+1\n\treturn arrRes\n\ndef resta(arr1,arr2,c1,c2,n):\n\tarrRes=[]\n\ti=0\n\tr=c1-c2\n\trAbs=0\n\tif r<0:\n\t\trAbs=abs(r)\n\tarrLen1 = len(arr1)\n\tarrLen2 = len(arr2)\n\n\twhile i= arrLen2:\n\t\t\t\t\t\tarrRes.append(float(arr1[i]))\n\t\t\t\t\telse:\n\t\t\t\t\t\tarrRes.append(float(arr2[i-rAbs])*(-1))\n\t\ti=i+1\n\treturn arrRes\n\n#Donde arr1 y arr2 son arrays, c1 y c2 son los ceros donde comienza cada array y n es la veces que se realizara la suma\ndef multi(arr1,arr2,c1,c2,n):\n\tarrRes=[]\n\ti=0\n\tr=c1-c2\n\tarrLen1 = len(arr1)\n\tarrLen2 = len(arr2)\n\n\twhile i 0:\n\t\twhile i < d:\n\t\t\tret.append(0)\n\t\t\ti = i + 1\n\telse:\n\t\twhile i > d:\n\t\t\tret.insert(0,0)\n\t\t\ti = i - 1\n\treturn ret\n\ndef diezmar(arr,c,d):\n\ti = 0\n\tn = len(arr)\n\tarrRes = []\n\taux = 0\n\twhile i < n:\n\t\taux = d*i\n\t\tif i < c:\t\n\t\t\tif c - aux > 0:\n\t\t\t\tarrRes.append(float(arr[c - int(aux)]))\n\t\t\telse:\n\t\t\t\tarrRes.append(0)\n\t\telse:\n\t\t\tif i == c:\n\t\t\t\tarrRes.append(float(arr[i]))\n\t\t\telse:\n\t\t\t\tif c + aux < n:\n\t\t\t\t\tarrRes.append(float(arr[c + int(aux)]))\n\t\t\t\telse:\n\t\t\t\t\tarrRes.append(0)\n\t\ti = i + 1\n\treturn arrRes\ndef convolucionar(arr1,arr2):\n\tcLen = len(arr1) + len(arr2) - 1\n\tauxLen1 = 0\n\tres = []\n\tconv = []\n\taux = []\n\twhileAux = 0\n\ti = 0\n\tj = 0\n\n\n\tfor a in arr1:\n\t\taux = []\n\t\tfor b in arr2:\n\t\t\taux.append(float(a)*float(b))\n\t\tconv.append(aux)\n\n\tauxLen1 = len(conv)\n\twhile i < cLen:\n\n\t\twhileAux = 0\n\t\tj = 0\n\t\twhile j <= i:\n\t\t\tif j < auxLen1:\n\t\t\t\tif i-j < len(conv[j]):\n\t\t\t\t\twhileAux += conv[j][i-j]\n\t\t\tj += 1\n\n\t\tres.append(whileAux)\n\t\ti += 1\n\treturn res\n\ndef interpolar(arr,c,n):\n\tres = []\n\tj=0\n\tk=0\n\n\tfor a in arr:\n\t\ti = 0\n\t\tres.append(float(a))\n\t\twhile i < n-1:\n\t\t\tres.append(float(a))\n\t\t\ti += 1\n\t\t\tif k < c:\n\t\t\t\tj += 1\n\t\tk += 0\n\treturn res,j\n\n\"\"\"\ndef interpolar(arr,c,n):\n\tres = []\n\tj=0\n\tk=0\n\taux=0\n\n\tfor a in arr:\n\t\tni = float(a)\n\t\tnf = float(arr[k+1])\n\t\taux = (abs(ni)-abs(nf))/n\n\t\tres.append(ni)\n\n\t\ti = 0\n\t\twhile i < n-1:\n\t\t\tif ni > nf:\n\t\t\t\tres.append(ni-(aux*(i+1)))\n\t\t\telse:\n\t\t\t\tres.append(ni+(aux*(i+1)))\n\n\t\t\ti += 1\n\t\t\tif k < c:\n\t\t\t\tj += 1\n\t\tk += 0\n\treturn res,j\n\"\"\"\n\t\t\n@app.route(\"/\")\ndef main():\n return render_template('index.html')\n\n@app.route('/showSignUp')\ndef showSignUp():\n return render_template('signup.html')\n\n@app.route('/signUp',methods=['POST'])\ndef signUp():\n\t# read the posted values from the UI\n\t_secuencia1 = request.form['secuencia1']\n\t_secuencia2 = request.form['secuencia2']\n\t_amp = request.form['amp']\n\t_desp = request.form['desp']\n\t_diezmar = request.form['diezmar']\n\t_interp = request.form['interp']\n\n\tcero1=[]\n\tcero2=[]\n\tsu = []\n\tmult = []\n\tceroR=0\n\tauxLen=0\n\tceroAux=0\n\ti=0\n \n\t# validate the received values\n\tif _secuencia1 and _secuencia2:\n\t\ti=0\n\t\tsecuencia2 = _secuencia2.split(\",\")\n\t\tsecuencia1 = _secuencia1.split(\",\")\n\t\tsLen1 = len(secuencia1)\n\t\tsLen2 = len(secuencia2)\n\t\tfor s1 in secuencia1:\n\t\t\tif not isNumber(s1):\n\t\t\t\tc = re.findall(\"[-+]?[.]?[\\d]+(?:,\\d\\d\\d)*[\\.]?\\d*(?:[eE][-+]?\\d+)?\", s1)\n\t\t\t\tsecuencia1[i]=c[0]\n\t\t\t\tcero1=[i,c[0]]\n\t\t\ti=i+1\n\t\t\t\t\n\t\ti=0\n\t\tfor s2 in secuencia2:\n\t\t\tif not isNumber(s2):\n\t\t\t\tc = re.findall(\"[-+]?[.]?[\\d]+(?:,\\d\\d\\d)*[\\.]?\\d*(?:[eE][-+]?\\d+)?\", s2)\n\t\t\t\tsecuencia2[i]=c[0]\n\t\t\t\tcero2=[i,c[0]]\n\t\t\ti=i+1\n\n\t\tif len(cero1) > 0 and len(cero2) > 0:\n\t\t\tif cero1[0]>cero2[0]:\n\t\t\t\tceroR=cero1[0]-cero2[0]\n\t\n\t\t\t\tif sLen1>sLen2:\n\t\t\t\t\tauxLen = sLen1\n\t\t\t\telse:\n\t\t\t\t\tauxLen = (sLen2-cero2[0])+cero1[0]\n\t\t\t\t\n\t\t\t\tsu = suma(secuencia1,secuencia2,cero1[0],cero2[0],auxLen)\n\t\t\t\tmult = multi(secuencia1,secuencia2,cero1[0],cero2[0],auxLen)\n\t\n\t\t\telse:\n\t\t\t\tceroR=cero2[0]-cero1[0]\n\t\n\t\t\t\tif sLen2>sLen1:\n\t\t\t\t\tauxLen = sLen2\n\t\t\t\telse:\n\t\t\t\t\tauxLen = (sLen1-cero1[0])+cero2[0]\n\t\n\t\t\t\tsu = suma(secuencia2,secuencia1,cero2[0],cero1[0],auxLen)\n\t\t\t\tmult = multi(secuencia2,secuencia1,cero2[0],cero1[0],auxLen)\n\n\t\t\t\n\t\t\tdiv1 = division(secuencia1,secuencia2,cero1[0],cero2[0],auxLen)\n\t\t\tdiv2 = division(secuencia2,secuencia1,cero2[0],cero1[0],auxLen)\n\t\t\trest1 = resta(secuencia1,secuencia2,cero1[0],cero2[0],auxLen)\n\t\t\trest2 = resta(secuencia2,secuencia1,cero2[0],cero1[0],auxLen)\n\n\t\t\tamp1 = amplificar(secuencia1,float(_amp))\n\t\t\tamp2 = amplificar(secuencia2,float(_amp))\n\t\t\tdesp1 = desplazar(secuencia1,float(_desp))\n\t\t\tdesp2 = desplazar(secuencia2,float(_desp))\n\t\t\tdiez1 = diezmar(secuencia1,cero1[0],float(_diezmar))\n\t\t\tdiez2 = diezmar(secuencia2,cero2[0],float(_diezmar))\n\t\t\tconv = convolucionar(secuencia1,secuencia2)\n\t\t\tinterp1,ceroI1 = interpolar(secuencia1,cero1[0],float(_interp))\n\t\t\tinterp2,ceroI2 = interpolar(secuencia2,cero2[0],float(_interp))\n\n\t\t\t#NO PONER NINGUNA FUNCION DEBAJO DEL REFLEJO\n\t\t\trefl1 = swap(secuencia1)\n\t\t\trefl2 = swap(secuencia2)\n\t\t\t\n\n\t\t\t#Saca los valores del eje x\n\t\t\tx = []\n\t\t\tx1 = []\n\t\t\tx2 = []\n\t\t\txC = []\n\t\t\txI1 = []\n\t\t\txI2 = []\n\t\t\ti = 0\n\n\t\t\tfor elem in secuencia1:\n\t\t\t\tx1.append(i-cero1[0])\n\t\t\t\ti = i+1\n\t\t\ti = 0\n\t\t\tfor elem in secuencia2:\n\t\t\t\tx2.append(i-cero2[0])\n\t\t\t\ti = i+1\n\n\t\t\ti = 0\n\t\t\tceroConv = cero1[0]+cero2[0]\n\t\t\tfor elem in conv:\n\t\t\t\txC.append(i-ceroConv)\n\t\t\t\ti = i+1\n\n\t\t\ti = 0\n\t\t\tfor elem in interp1:\n\t\t\t\txI1.append(i-ceroI1)\n\t\t\t\ti = i+1\n\n\t\t\ti = 0\n\t\t\tfor elem in interp2:\n\t\t\t\txI2.append(i-ceroI2)\n\t\t\t\ti = i+1\n\n\t\t\tif sLen1 > sLen2:\n\t\t\t\tceroAux = cero1[0]\n\t\t\t\tx = x1\n\t\t\telse:\n\t\t\t\tceroAux = cero2[0]\n\t\t\t\tx = x2\n\n\n\t\t\tsecuencia1 = [float(a) for a in secuencia1]\n\t\t\tsecuencia2 = [float(a) for a in secuencia2]\n\t\t\trefl1 = [float(a) for a in refl1]\n\t\t\trefl2 = [float(a) for a in refl2]\n\t\t\treturn json.dumps({'grafica1':[secuencia1,x1],'grafica2':[secuencia2,x2],'suma':[su,x],'multiplicacion':[mult,x],'division1':[div1,x],'division2':[div2,x],'resta1':[rest1,x],'resta2':[rest2,x],\"reflejo1\":[refl1,x1],\"reflejo2\":[refl2,x2],\"amplificacion1\":[amp1,x1],\"amplificacion2\":[amp2,x2],\"desplazamiento1\":[amp1,x1],\"desplazamiento2\":[amp2,x2],\"desplazamiento1\":[desp1,x1],\"desplazamiento2\":[desp2,x2],\"diezmacion1\":[diez1,x1],\"diezmacion2\":[diez2,x2],\"interpolacion1\":[interp1,xI1],\"interpolacion2\":[interp2,xI2],\"convolucion\":[conv,xC]}) \n\t\telse:\n\t\t\treturn json.dumps({'html':'No ingreso ceros'})\n\telse:\n\t\treturn json.dumps({'html':'No ingreso todos los campos'})\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"163053846","text":"def ler_matriz(ordem):\n\tmat = []\n\tfor i in range(ordem):\n\t\tlinha = []\n\t\tfor j in range(ordem):\n\t\t\tn = int(input(\"Informe matriz[{}][{}]: \".format(i, j)))\n\t\t\tlinha.append(n)\n\t\tmat.append(linha)\n\treturn mat\n\ndef imprime_matriz(matriz, ordem):\n\tfor i in range(ordem):\n\t\tfor j in range(ordem):\n\t\t\tprint(\"{:3}\".format(matriz[i][j]), end=\" \")\n\t\tprint()\n\ndef multiplica_matriz(matriz, num):\n\tfor i in range(4):\n\t\tfor j in range(4):\n\t\t\tmatriz[i][j] *= num \n\n#Principal....\nprint(\"Leitura da matriz:\")\nmatriz = ler_matriz(4)\n\nnum = int(input(\"Informe o número para mutiplicar: \"))\n\nmultiplica_matriz(matriz, num)\n\nprint(\"\\nImpressão da matriz:\")\nimprime_matriz(matriz, 4)\n","sub_path":"material/respostas_exercicios/lista12_2/exe4.py","file_name":"exe4.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"477082108","text":"from collections import OrderedDict\nimport pandas as pd\nimport numpy as np\n\ndef get_securities_in_sector(sector,df,sector_mapping):\n secs = list(df[df[sector_mapping] == sector].index.values)\n return [i for n, i in enumerate(secs) if i not in secs[:n]]\n\ndef get_peer_data(sector,df,sector_mapping):\n\n peer_univ = get_securities_in_sector(sector,df,sector_mapping)\n peer_tbl = df.loc[peer_univ,:]\n return peer_tbl\n\ndef arrange_data_for_gui(security,tbl,mappings):\n # df to dictionary for easier access\n sec_tbl = tbl.loc[[security],:].reset_index()\n tbl_dict = {c:sec_tbl[c].tolist()[0] for c in sec_tbl.columns}\n\n gui_data = {}\n gui_data[\"name\"] = tbl_dict[mappings['id_field']]\n gui_data[\"des\"] = tbl_dict[mappings['description_field']]\n gui_data[\"industry\"] = tbl_dict[mappings['sector_field']] if tbl_dict[mappings['id_field']] != 0 else 'Not Covered'\n\n gui_data[\"internal_score\"] = tbl_dict[mappings['internal_score']]\n gui_data[\"third_party_score\"] = tbl_dict[mappings['third_party_score']]\n gui_data[\"third_party_score_date\"] = tbl_dict[mappings['third_party_score_date']].strftime('%Y-%m-%d')\n gui_data[\"tbl_data\"] = sec_tbl.loc[:,mappings['factor_score_fields']]\n gui_data[\"peer_data\"] = get_peer_data(gui_data[\"industry\"],tbl,mappings['sector_field']).loc[:,mappings['factor_score_fields']].reset_index()\n return gui_data\n\ndef get_grid_map_data_from_df(df,group1,group2,weight_type):\n totals = df.groupby(by=[group1,group2]).sum().unstack().stack(dropna=False).fillna(0)\n return totals.reset_index().pivot(index=group2,columns=group1,values=weight_type)\n\ndef compute_sector_df(dictionary,date,mappings):\n return dictionary[date][[mappings['group_field'],mappings['total_score_field']]].groupby(mappings['group_field']).median().sort_values(mappings['total_score_field'],ascending=False)[[mappings['total_score_field']]]\n\ndef compute_score_hist_df(score_df,mappings):\n return score_df.reset_index().pivot_table(index=mappings['id_field'],columns=mappings['date_field'],values=mappings['total_score_field'],aggfunc = max)\n\ndef highlight_positive():\n return '''function(params){\n if (params.value < 0) {\n return {color: 'red'};\n } else {\n return {color: 'forestgreen'};\n }\n }\n '''\n\ndef highlight_scores():\n return '''function(params){\n if (params.value > 3) {\n return {color: 'red'};\n } else if (params.value===3){\n return {color: '#ff6600'};\n } else if (params.value === 1){\n return {color:'#93C02D'};\n }\n else{\n return{color: 'DarkOrange'};\n }\n }'''\n","sub_path":"bqdash/.ipynb_checkpoints/calc_functions-checkpoint.py","file_name":"calc_functions-checkpoint.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"44389089","text":"import requests\nfrom bs4 import BeautifulSoup\n\n# https://buzzorange.com/techorange/?s=AR+VR\n# https://buzzorange.com/techorange/page/2/?s=AR+VR\nf = open('D:\\\\source\\\\BD.txt', 'a', encoding='UTF-8')\nk = 1\nlinks = []\nj = 0\nurl = \"https://buzzorange.com/techorange/?s=%E5%A4%A7%E6%95%B8%E6%93%9A\"\nx = 1\nwhile x < 97:\n res = requests.get(url, headers={\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36\"})\n res.encoding = 'utf'\n soup = BeautifulSoup(res.text, \"lxml\")\n res.close()\n for souplink in soup.select(\" header > h4\"):\n links.append(souplink.a['href'])\n feedres = requests.get(links[j], headers={\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36\"})\n feedres.encoding = 'utf'\n soupfeeds = BeautifulSoup(feedres.text, \"lxml\")\n feedres.close()\n print(\"value\"+str(k))\n dfList=\"\"\n for soupfeed in soupfeeds.select(\n '#main p'): # 用for迴圈取 會按照網頁

順序依序取出\n article = soupfeed.get_text(strip=True)\n article2 = article.rstrip()\n dfList = dfList + article2\n f.write(dfList + \"\\n\\n\")\n j += 1\n k += 1\n x += 1\n url = \"https://buzzorange.com/techorange/page/\" + str(x) + \"/?s=%E5%A4%A7%E6%95%B8%E6%93%9A\"\n print(\"page\" + str(x))\nf.close()\n","sub_path":"buzzorangeBD.py","file_name":"buzzorangeBD.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"82834458","text":"import os\r\nimport speech_recognition as sr\r\n\r\nr = sr.Recognizer()\r\nwith sr.Microphone() as source:\r\n print(\"Say something!\")\r\n audio = r.listen(source)\r\n\r\n cmd = r.recognize_sphinx(audio)\r\n print(cmd)\r\n\r\n if cmd == \"hello\":\r\n \tprint(\"Hello\")\r\n if cmd == \"how are you\":\r\n \tos.system(\"espeak \\\" Fine thanks\\\" \")","sub_path":"bob_controller_jquery/scripts/speech_rec.py","file_name":"speech_rec.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"361179822","text":"import datetime\nimport json\nimport logging\n\nimport boto3\nfrom botocore.exceptions import ClientError\n\nfrom . import alexa\n\n\nENV_NAMES = {\n 'dev': 'dev',\n 'development': 'dev',\n 'stage': 'stage',\n 'prod': 'prod',\n 'production': 'prod'\n}\n\n\nCF_STATES = [\n # http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html#w1ab2c15c17c21c13\n 'CREATE_COMPLETE',\n 'CREATE_IN_PROGRESS',\n 'CREATE_FAILED',\n 'DELETE_COMPLETE',\n 'DELETE_FAILED',\n 'DELETE_IN_PROGRESS',\n 'REVIEW_IN_PROGRESS',\n 'ROLLBACK_COMPLETE',\n 'ROLLBACK_FAILED',\n 'ROLLBACK_IN_PROGRESS',\n 'UPDATE_COMPLETE',\n 'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS',\n 'UPDATE_IN_PROGRESS',\n 'UPDATE_ROLLBACK_COMPLETE',\n 'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',\n 'UPDATE_ROLLBACK_FAILED',\n 'UPDATE_ROLLBACK_IN_PROGRESS'\n]\n\n\ndef get_timestamp():\n return '{} UTC'.format(str(datetime.datetime.utcnow().isoformat(sep=' ', timespec='minutes')))\n\n\ndef deploy(request, session, my_env):\n try:\n requested_env = ENV_NAMES[request['intent']['slots']['Environment']['value'].lower()]\n requested_version = '.'.join([\n request['intent']['slots']['MajorVersion']['value'],\n request['intent']['slots']['MinorVersion']['value'],\n request['intent']['slots']['PatchVersion']['value']\n ])\n except KeyError:\n response_string = \"Tell me a full version number and environment name, or I'm not doing anything.\"\n return alexa.build_response(session=session, response_string=response_string)\n\n logger = logging.getLogger()\n logger.info(f'Pear website version requested: {requested_version}')\n\n client = boto3.client('lambda')\n lambda_response = client.invoke(\n FunctionName=f'pear_deployer_{my_env}',\n InvocationType='RequestResponse',\n Payload=json.dumps({'request': 'deploy', 'version': requested_version, 'environment': requested_env})\n )\n logger.info('Response to deploy request: {}'.format(lambda_response))\n if lambda_response['StatusCode'] == 200 and not lambda_response.get('FunctionError'):\n response_string = 'Ok, fine.'\n card_string = f'Started deploy of {requested_version} to {requested_env} at {get_timestamp()}.'\n return alexa.build_response(session=session, response_string=response_string, card_string=card_string)\n elif lambda_response['StatusCode'] == 200 and lambda_response.get('FunctionError'):\n error_response = json.loads(lambda_response['Payload'].read())\n logger.info(f'Error: {error_response}')\n error = error_response['errorType']\n error_message = error_response['errorMessage']\n if error == 'VersionUnavailableError':\n latest_version = error_message.split(':')[-1].strip()\n response_string = f\"You blockhead. {requested_version} doesn't exist. Latest is {latest_version}.\"\n return alexa.build_response(session=session, response_string=response_string)\n elif error == 'ClientError':\n if '(AccessDenied)' in error_message:\n response_string = f\"I'm too classy to touch {requested_env}.\"\n return alexa.build_response(session=session, response_string=response_string)\n elif f'Stack [pear-{requested_env}] does not exist' in error_message:\n response_string = f\"I couldn't find {requested_env}.\"\n return alexa.build_response(session=session, response_string=response_string)\n elif 'No updates are to be performed' in error_message:\n response_string = \"That's already running. There's nothing to do.\"\n return alexa.build_response(session=session, response_string=response_string)\n elif 'state and can not be updated.' in error_message:\n states = [s for s in CF_STATES if s in error_message]\n assert len(states) == 1, 'Stacks can only have one state.'\n state = states[0].replace('_', ' ')\n response_string = f\"Pear's state is {state}, so I can't deploy right now.\"\n return alexa.build_response(session=session, response_string=response_string)\n else:\n response_string = 'I started the deploy, but there was a problem.'\n card_string = f'Error starting deploy of {requested_version} to {requested_env} at {get_timestamp()}.'\n return alexa.build_response(session=session, response_string=response_string, card_string=card_string)\n return alexa.build_response(session=session, response_string=\"I couldn't start the deploy.\")\n\n\ndef status(request, session, my_env):\n try:\n requested_env = ENV_NAMES[request['intent']['slots']['Environment']['value'].lower()]\n except KeyError:\n response_string = 'You have to tell me an environment name.'\n return alexa.build_response(session=session, response_string=response_string)\n\n client = boto3.client('lambda')\n lambda_response = client.invoke(\n FunctionName=f'pear_deployer_{my_env}',\n InvocationType='RequestResponse',\n Payload=json.dumps({'request': 'status', 'environment': requested_env})\n )\n response_data = json.loads(lambda_response['Payload'].read())\n logger = logging.getLogger()\n logger.info(f'Response to status request: {lambda_response}')\n logger.info(f'Error: {response_data}')\n if lambda_response['StatusCode'] == 200 and not lambda_response.get('FunctionError'):\n state = response_data['stack_status'].replace('_', ' ')\n response_string = f'Version is {response_data[\"version\"]}. State is {state}.'\n return alexa.build_response(session=session, response_string=response_string)\n elif lambda_response['StatusCode'] == 200 and lambda_response.get('FunctionError'):\n error = response_data['errorType']\n error_message = response_data['errorMessage']\n if error == 'ClientError':\n if '(AccessDenied)' in error_message:\n response_string = f\"I'm too classy to touch {requested_env}.\"\n return alexa.build_response(session=session, response_string=response_string)\n elif f'Stack with id pear-{requested_env} does not exist' in error_message:\n response_string = f\"I couldn't find {requested_env}.\"\n return alexa.build_response(session=session, response_string=response_string)\n return alexa.build_response(session=session, response_string=\"I couldn't get status.\")\n\n\ndef honeypot(request, session, my_env):\n client = boto3.client('sns')\n paginator = client.get_paginator('list_topics')\n topics = list()\n for page in paginator.paginate():\n topics.extend([topic['TopicArn'] for topic in page['Topics']])\n alerts_arns = [arn for arn in topics if arn.endswith(f'pear_alerts_{my_env}')]\n assert len(alerts_arns) == 1, 'There should only be one alerts topic per Pear environment.'\n alerts_arn = alerts_arns[0]\n logger = logging.getLogger()\n logger.info(f'Sending honeypot alert to this SNS topic: {alerts_arn}')\n sns_response = client.publish(TopicArn=alerts_arn, Message='Pear honeypot triggered.')\n logger.info(f'Response to SNS request: {sns_response}')\n if sns_response['ResponseMetadata']['HTTPStatusCode'] == 200:\n response_string = 'Access granted. Have fun.'\n card_string = f'Honeypot triggered at {get_timestamp()}. Alert sent to admins.'\n else:\n response_string = 'Something went wrong.'\n card_string = f'Honeypot triggered at {get_timestamp()}. Alert to admins failed.'\n return alexa.build_response(session=session, response_string=response_string, card_string=card_string)\n","sub_path":"lambda_functions/deployer_alexa_skill/deployer_alexa_skill/pear.py","file_name":"pear.py","file_ext":"py","file_size_in_byte":7714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"621345311","text":"from r7insight import R7InsightHandler\nimport logging\nimport time\nimport bluetooth\nimport Adafruit_DHT\nimport datetime\n\nserver_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )\n\nport = 25\nmacAddr = \"B8:27:EB:63:E4:8B\"\nserver_sock.bind((\"\",port))\nserver_sock.listen(1)\n\nlog = logging.getLogger('r7insight')\nlog.setLevel(logging.INFO)\ntest = R7InsightHandler(\"\", 'eu')\n\nlog.addHandler(test)\nsensorID= \"Varun\"\n\nclient_sock,address = server_sock.accept()\nprint (\"Accepted connection from \",address)\nwhile True:\n\tdata = client_sock.recv(1024)\n\tprint (data)\n\t\n\thumidity, temperature = Adafruit_DHT.read_retry(11, 4)\n\tlog.info(data)\n\tnow =datetime.datetime.now()\n\tlog_text = \"{0}\\t SensorID={1}, Temperature = {2}, Humidity = {3}\".format(now,sensorID,temperature,humidity)\n\tlog.info(log_text)\n\tprint(log_text)\n\nclient_sock.close()\nserver_sock.close()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"138324894","text":"\"\"\"Implementation of pop function\"\"\"\n\nimport ctypes # provides low-level arrays\nimport math\nclass DynamicArray:\n \"\"\"A dynamic array class akin to a simplified Python list.\"\"\"\n\n def __init__(self):\n \"\"\"Create an empty array.\"\"\"\n self._n = 0 # count actual elements\n self._capacity = 1 # default array capacity\n self._A = self._make_array(self._capacity) # low-level array\n\n def __len__(self):\n \"\"\"Return number of elements stored in the array.\"\"\"\n return self._n\n\n def __getitem__(self, k):\n \"\"\"Return element at index k.\"\"\"\n if 0 <= k < self._n:\n return self._A[k] # retrieve from array\n elif k == -1 and self._n != 0:\n return self._A[-1]\n else:\n raise IndexError('invalid index')\n\n def append(self, obj):\n \"\"\"Add object to end of the array.\"\"\"\n if self._n == self._capacity: # not enough room\n self._resize(2 * self._capacity) # so double capacity\n self._A[self._n] = obj\n self._n += 1\n\n def _resize(self, c): # nonpublic utitity\n \"\"\"Resize internal array to capacity c.\"\"\"\n B = self._make_array(c) # new (bigger) array\n for k in range(self._n): # for each existing value\n B[k] = self._A[k]\n self._A = B # use the bigger array\n self._capacity = c\n\n def _make_array(self, c): # nonpublic utitity\n \"\"\"Return new array with capacity c.\"\"\"\n return (c * ctypes.py_object)() # see ctypes documentation\n\n def insert(self, k, value):\n \"\"\"Insert value at index k, shifting subsequent values rightward.\"\"\"\n # (for simplicity, we assume 0 <= k <= n in this verion)\n if self._n == self._capacity: # not enough room\n new_A = self._make_array(2 * self._capacity) \n for i in range(k):\n new_A[i] = self._A[i]\n new_A[k] = value\n for j in range(k,self._capacity):\n new_A[j + 1] = self._A[j]\n self._A = new_A\n self._capacity = 2 * self._capacity\n else:\n for j in range(self._n, k, -1): # shift rightmost first\n self._A[j] = self._A[j-1]\n self._A[k] = value # store newest element\n self._n += 1\n\n def remove(self, value):\n \"\"\"Remove first occurrence of value (or raise ValueError).\"\"\"\n # note: we do not consider shrinking the dynamic array in this version\n for k in range(self._n):\n if self._A[k] == value: # found a match!\n for j in range(k, self._n - 1): # shift others to fill gap\n self._A[j] = self._A[j+1]\n self._A[self._n - 1] = None # help garbage collection\n self._n -= 1 # we have one less item\n return # exit immediately\n raise ValueError('value not found') # only reached if no match\n \"\"\"Needed in order to be able to print array (getitem too)\"\"\"\n def __len__(self):\n return self._n\n\n def pop(self):\n \"\"\"Pop is going to resize the array to N/2 any time the number of \n elements goes below N/4, where N stands for capacity\"\"\"\n self._n -= 1\n if self._n <= math.floor(self._capacity/4):\n self._resize(math.floor(self._capacity/2))\n print(\"Capacity reduction took place\")\n\nif __name__ == '__main__':\n array = DynamicArray()\n array.append(3)\n array.append(4)\n \"\"\"Capacity is full\"\"\"\n array.insert(1,10)\n array.append(4)\n array.append(4)\n array.append(4)\n array.append(4)\n \n \"\"\"Array class does not know how to print itself. This is why we iterate\"\"\"\n print(\"Array after continuous pops :\")\n for i in range(len(array)):\n array.pop()\n for j in range(len(array)):\n print(array[j])\n print(\"=====\")\n print()\n\n\n\n\n\n","sub_path":"chap5-Array-Based_Sequences/C-5.16.py","file_name":"C-5.16.py","file_ext":"py","file_size_in_byte":4285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"362482429","text":"'''\n市场深度单,即 GetDepth 返回数据中 Bids 、Asks 数组中的元素的数据结构。\n{\n Price\t:价格\n Amount\t:数量\n}\n'''\nimport copy\n\n\nclass MarketOrder:\n \"\"\"\n Abstract class of a market data\n \"\"\"\n class Side:\n ORDER_TYPE_BUY = 0\n ORDER_TYPE_SELL = 1\n NONE = 2\n\n class Status:\n ORDER_STATE_PENDING = 0 #未完成\n ORDER_STATE_CLOSED = 1 #已完成\n ORDER_STATE_CANCELED = 2 #已取消\n\n def __init__(self):\n \"\"\"\n Constructor\n \"\"\"\n pass\n\n def __init__(self, price=0.0, amount=0.0):\n \"\"\"\n Constructor\n \"\"\"\n self.Price = price\n self.Amount = amount\n\n def copy(self):\n return copy.deepcopy(self)\n\n @staticmethod\n def parse_side(value):\n \"\"\"\n Decode the value to Side (BUY/SELL)\n :param value: Integer or string\n :return: Side (NONE, BUY, SELL)\n \"\"\"\n if type(value) != int:\n value = value.lower()\n if value == 'buy' or value == 'bid' or value == 'b':\n return MarketOrder.Side.ORDER_TYPE_BUY\n elif value == 'sell' or value == 'ask' or value == 's':\n return MarketOrder.Side.ORDER_TYPE_SELL\n else:\n return MarketOrder.Side.NONE\n\n if value == 1:\n return MarketOrder.Side.ORDER_TYPE_BUY\n elif value == 2:\n return MarketOrder.Side.ORDER_TYPE_SELL\n else:\n raise Exception(\"Cannot parse the side (%s)\" % value)\n\n\n\n","sub_path":"util/model/MarketOrder.py","file_name":"MarketOrder.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"457709153","text":"import json\nimport unittest\n\nfrom .instances import frontik_test_app\n\n\nclass TestJsonResponse(unittest.TestCase):\n def test_validation(self):\n response = frontik_test_app.get_page('validate_arguments?list=1&list=2&string=safestring', notpl=True)\n\n data = json.loads(response.content)\n self.assertEqual([1, 2], data['list'])\n self.assertEqual('safestring', data['string'])\n\n def test_validation_failed(self):\n response = frontik_test_app.get_page('validate_arguments?list=1&list=2&string=un/safe', notpl=True)\n\n self.assertEqual(response.status_code, 400)\n\n def test_validation_model(self):\n response = frontik_test_app.get_page('validate_arguments?list=1&list=2&string=nword&model=true', notpl=True)\n\n data = json.loads(response.content)\n self.assertEqual([1, 2], data['list'])\n self.assertEqual('customString', data['string'])\n","sub_path":"tests/test_arguments.py","file_name":"test_arguments.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"299226574","text":"# Copyright (c) 2016-present, Facebook, Inc.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport argparse\nimport atexit\nimport json\nimport logging\nimport os\nimport subprocess\nfrom logging import Logger\nfrom typing import List, Optional\n\nfrom .. import json_rpc\nfrom ..analysis_directory import AnalysisDirectory\nfrom ..configuration import Configuration\nfrom ..project_files_monitor import MonitorException, ProjectFilesMonitor\nfrom .command import (\n ClientException,\n ExitCode,\n IncrementalStyle,\n Result,\n State,\n typeshed_search_path,\n)\nfrom .reporting import Reporting\nfrom .start import Start\n\n\nLOG: Logger = logging.getLogger(__name__)\n\n\ndef _convert_to_result(response: json_rpc.Response) -> Result:\n error_code = ExitCode.FAILURE if response.error else ExitCode.SUCCESS\n return Result(output=json.dumps(response.result), code=error_code)\n\n\nclass Incremental(Reporting):\n NAME = \"incremental\"\n\n def __init__(\n self,\n arguments: argparse.Namespace,\n original_directory: str,\n configuration: Optional[Configuration] = None,\n analysis_directory: Optional[AnalysisDirectory] = None,\n ) -> None:\n super(Incremental, self).__init__(\n arguments, original_directory, configuration, analysis_directory\n )\n self._nonblocking: bool = arguments.nonblocking\n self._incremental_style: bool = arguments.incremental_style\n self._no_start_server: bool = arguments.no_start\n self._no_watchman: bool = getattr(arguments, \"no_watchman\", False)\n\n @classmethod\n def add_subparser(cls, parser: argparse._SubParsersAction) -> None:\n incremental_help = \"\"\"\n Connects to a running Pyre server and returns the current type errors for your\n project. If no server exists for your projects, starts a new one. Running `pyre`\n implicitly runs `pyre incremental`.\n\n By default, incremental checks ensure that all dependencies of changed files are\n analyzed before returning results. If you'd like to get partial type checking\n results eagerly, you can run `pyre incremental --nonblocking`.\n \"\"\"\n incremental = parser.add_parser(cls.NAME, epilog=incremental_help)\n incremental.set_defaults(command=cls)\n incremental.add_argument(\n \"--nonblocking\",\n action=\"store_true\",\n help=(\n \"Ask the server to return partial results immediately, \"\n \"even if analysis is still in progress.\"\n ),\n )\n incremental.add_argument(\n \"--incremental-style\",\n type=IncrementalStyle,\n choices=list(IncrementalStyle),\n default=IncrementalStyle.FINE_GRAINED,\n help=\"How to approach doing incremental checks.\",\n )\n incremental.add_argument(\n \"--no-start\", action=\"store_true\", help=argparse.SUPPRESS\n )\n # This is mostly to allow `restart` to pass on the flag to `start`.\n incremental.add_argument(\n \"--no-watchman\", action=\"store_true\", help=argparse.SUPPRESS\n )\n\n def _run(self) -> None:\n if (not self._no_start_server) and self._state() == State.DEAD:\n LOG.warning(\"Starting server at `%s`.\", self._analysis_directory.get_root())\n arguments = self._arguments\n arguments.no_watchman = self._no_watchman\n arguments.terminal = False\n arguments.store_type_check_resolution = False\n exit_code = (\n Start(\n arguments,\n self._original_directory,\n self._configuration,\n self._analysis_directory,\n )\n .run()\n .exit_code()\n )\n if exit_code != ExitCode.SUCCESS:\n self._exit_code = ExitCode.FAILURE\n return\n else:\n self._refresh_file_monitor()\n\n if self._state() != State.DEAD:\n LOG.info(\"Waiting for server...\")\n\n request = json_rpc.Request(method=\"displayTypeErrors\", parameters={\"files\": []})\n self._send_and_handle_socket_request(request, self._version_hash)\n\n def _socket_result_handler(self, result: Result) -> None:\n errors = self._get_errors(result)\n self._print(errors)\n if errors:\n self._exit_code = ExitCode.FOUND_ERRORS\n\n def _flags(self) -> List[str]:\n flags = super()._flags()\n flags.extend([\"-expected-binary-version\", self._configuration.version_hash])\n\n search_path = self._configuration.search_path + typeshed_search_path(\n self._configuration.typeshed\n )\n if search_path:\n flags.extend([\"-search-path\", \",\".join(search_path)])\n\n excludes = self._configuration.excludes\n for exclude in excludes:\n flags.extend([\"-exclude\", exclude])\n\n extensions = self._configuration.extensions\n for extension in extensions:\n flags.extend([\"-extension\", extension])\n\n if self._nonblocking:\n flags.append(\"-nonblocking\")\n\n return flags\n\n def _read_stderr(self, _stream) -> None:\n stderr_file = os.path.join(self._log_directory, \"server/server.stdout\")\n with subprocess.Popen(\n [\"tail\", \"--follow\", \"--lines=0\", stderr_file],\n stdout=subprocess.PIPE,\n stderr=subprocess.DEVNULL,\n text=True,\n ) as stderr_tail:\n atexit.register(stderr_tail.terminate)\n super(Incremental, self)._read_stderr(stderr_tail.stdout)\n\n def _refresh_file_monitor(self) -> None:\n if self._no_watchman:\n return\n if not ProjectFilesMonitor.is_alive(self._configuration):\n LOG.info(\"File monitor is not running.\")\n try:\n ProjectFilesMonitor(\n self._configuration,\n self._current_directory,\n self._analysis_directory,\n ).daemonize()\n LOG.info(\"Restarted file monitor.\")\n except MonitorException as exception:\n LOG.warning(\"Failed to restart file monitor: %s\", exception)\n","sub_path":"client/commands/incremental.py","file_name":"incremental.py","file_ext":"py","file_size_in_byte":6323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"508435114","text":"# MATSIKO BRUNO 2020/BSE/165/PS\n# DAVID NYAMIYALE 2020/BSE/057/PS\n# MAWANDA DENNIS 2020/BSE/155/PS\n# AKANDWANAHO NICKSON 2020/BSE/006/PS\n\n# while loop that starts at the last character in a string and works it way backwords to the start of string.\n# print each letter on seperate line except back words\n\nstringname = input('enter the string to be reversed')\nstringlength = len(stringname)\nwhile ( stringlength > 0 ):\n print(stringname[stringlength - 1])\n stringlength = stringlength - 1","sub_path":"src/chapter6/exercise1.py","file_name":"exercise1.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"35832299","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2004-2013 Mag. Christian Tanzer. All rights reserved\n# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at\n# ****************************************************************************\n#\n# This module is licensed under the terms of the BSD 3-Clause License\n# .\n# ****************************************************************************\n#\n#++\n# Name\n# TFL.Units.Liquid\n#\n# Purpose\n# Liquid capacity units\n#\n# Revision Dates\n# 8-Aug-2004 (CT) Creation\n# ««revision-date»»···\n#--\n\nfrom _TFL import TFL\nimport _TFL._Meta.Object\nimport _TFL._Units.Kind\nimport _TFL._Units.Volume\n\nclass Liquid (TFL.Units.Kind) :\n \"\"\"Units of liquid capacity\n\n >>> Liquid (1)\n 1\n >>> Liquid (1.0, \"oz\")\n 0.029573\n >>> Liquid (1.0, \"dr\")\n 0.003696625\n >>> Liquid (1.0, \"gal\")\n 3.785344\n >>> Liquid (1.0, \"pt\")\n 0.473168\n \"\"\"\n\n Volume = TFL.Units.Volume\n Unit = TFL.Units.Unit\n\n base_unit = Unit (\"liter\", 1.0, \"l\")\n _ounce = 0.029573\n _units = \\\n (\n # SI prefixes\n Unit (\"nanoliter\", TFL.Units.nano, \"nl\")\n , Unit (\"microliter\", TFL.Units.micro, \"ul\")\n , Unit (\"milliliter\", TFL.Units.milli, \"ml\")\n , Unit (\"centiliter\", TFL.Units.centi, \"cl\")\n , Unit (\"deciliter\", TFL.Units.deci, \"dl\")\n , Unit (\"hectoliter\", TFL.Units.hecto, \"hl\")\n , Unit (\"kiloliter\", TFL.Units.kilo, \"kl\")\n , Unit (\"cubic_decimeter\", 1.0)\n , Unit (\"cubic_meter\", 1000.0)\n # US customary units\n , Unit (\"ounce\", _ounce, \"oz\")\n , Unit (\"drop\", _ounce / 360)\n , Unit (\"drams\", _ounce / 8, \"dr\")\n , Unit (\"teaspoon\", _ounce / 6, \"tsp\")\n , Unit (\"tablespoon\", _ounce / 2, \"tb\")\n , Unit (\"cup\", _ounce * 8)\n , Unit (\"pint\", _ounce * 16, \"pt\")\n , Unit (\"quart\", _ounce * 32, \"qt\")\n , Unit (\"gallon\", _ounce * 128, \"gal\")\n )\n\n# end class Liquid\n\nif __name__ != \"__main__\" :\n TFL.Units._Export (\"*\")\n### __END__ TFL.Units.Liquid\n","sub_path":"Functions/venv/lib/python3.6/site-packages/_TFL/_Units/Liquid.py","file_name":"Liquid.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"228059963","text":"import sys, sqlite3, jdatetime\nfrom PyQt5 import QtWidgets, QtGui, QtCore\nfrom AddSamplingDetails import *\n\nclass Form_DialogAddSamplingDetails(QtWidgets.QDialog):\n def __init__(self):\n super().__init__()\n self.statusmode = 0\n self.project_id = 0\n self.ui = Ui_DialogAddSamplingDetails()\n self.ui.setupUi(self)\n self.ui.comboBoxYear.currentIndexChanged.connect(self.TrigerMount)\n self.ui.comboBoxMount.currentIndexChanged.connect(self.TrigerDay)\n self.ui.pushButtonCancelSampling.clicked.connect(self.close)\n self.ui.pushButtonCreateSampling.clicked.connect(self.CreateNewSampling)\n\n def TrigerMount(self):\n if self.ui.comboBoxYear.currentIndex() == 0:\n self.ui.comboBoxMount.clear()\n self.ui.comboBoxMount.addItem(\"ماه\")\n self.ui.comboBoxMount.setEnabled(False)\n else:\n self.ui.comboBoxMount.setEnabled(True)\n self.ui.comboBoxMount.clear()\n self.ui.comboBoxMount.addItem(\"ماه\")\n for i in range(1, 13):\n self.ui.comboBoxMount.addItem(str(i).zfill(2))\n\n def TrigerDay(self):\n if self.ui.comboBoxMount.currentIndex() == 0:\n self.ui.comboBoxDay.clear()\n self.ui.comboBoxDay.addItem(\"روز\")\n self.ui.comboBoxDay.setEnabled(False)\n else:\n self.ui.comboBoxDay.setEnabled(True)\n self.ui.comboBoxDay.clear()\n self.ui.comboBoxDay.addItem(\"روز\")\n cond = self.ui.comboBoxYear.itemText(self.ui.comboBoxYear.currentIndex()) not in (\"1399\", \"1403\", \"1408\")\n Mount = self.ui.comboBoxMount.currentIndex()\n if cond:\n if 0 < Mount < 7:\n for i in range(1,32):\n self.ui.comboBoxDay.addItem(str(i).zfill(2))\n elif 6 < Mount < 12:\n for i in range(1,31):\n self.ui.comboBoxDay.addItem(str(i).zfill(2))\n else:\n for i in range(1,30):\n self.ui.comboBoxDay.addItem(str(i).zfill(2))\n else:\n if 0 < Mount < 7:\n for i in range(1,32):\n self.ui.comboBoxDay.addItem(str(i).zfill(2))\n elif 6 < Mount < 13:\n for i in range(1,31):\n self.ui.comboBoxDay.addItem(str(i).zfill(2))\n\n def setProjectID(self, project_id):\n self.project_id = project_id\n\n def isValid_fc(self):\n Valid_fc = (\n self.ui.lineEdit_fc.text().isdigit()\n or\n self.ui.lineEdit_fc.text().replace('.','',1).isdigit())\n if not Valid_fc:\n return False\n return True\n \n def CreateNewSampling(self):\n fillCondition =(\n self.ui.comboBoxElement.currentIndex() == 0,\n len(self.ui.lineEditStory.text()) == 0,\n len(self.ui.lineEditLevel.text()) == 0,\n not self.ui.comboBoxDay.isEnabled(),\n self.ui.comboBoxDay.currentIndex()== 0,\n len(self.ui.lineEdit_fc.text()) == 0,\n self.ui.comboBoxCementType.currentIndex() == 0\n )\n if any(fillCondition):\n QMB = QtWidgets.QMessageBox.critical(self, \"خطا\", \"لطفاً همه فیلدها را تکمیل نمایید.\")\n return\n else:\n if not self.isValid_fc():\n QMB = QtWidgets.QMessageBox.critical(self, \"خطا\", \"مقاومت مشخصه وارد شده نامعتبر است.\")\n return\n else:\n try:\n conn = sqlite3.connect('MainDB.db')\n cur = conn.cursor()\n sampling_date = jdatetime.datetime(int(self.ui.comboBoxYear.currentText()),int(self.ui.comboBoxMount.currentText()), int(self.ui.comboBoxDay.currentText()), locale='fa_IR')\n SamplingInput = (\n self.project_id,\n self.ui.comboBoxElement.currentText(),\n self.ui.lineEditStory.text(),\n self.ui.lineEditLevel.text(),\n sampling_date.strftime(\"%Y/%m/%d\"),\n self.ui.lineEdit_fc.text(),\n self.ui.comboBoxCementType.currentText()\n )\n sqlexpr = \"INSERT INTO Sampling (ProjectID, Element, Story, Level, SamplingDate, fc, CementType) VALUES (?, ?, ?, ?, ?, ?, ?)\"\n cur.execute(sqlexpr, SamplingInput)\n conn.commit()\n print(\"New Samplign Added\")\n self.statusmode = 1\n except sqlite3.Error as err:\n print(err)\n finally:\n conn.close()\n self.close()\n return self.statusmode\n\n# if __name__ ==\"__main__\":\n# app = QtWidgets.QApplication(sys.argv)\n# w = Form_DialogAddSamplingDetails()\n# w.show()\n# sys.exit(app.exec_())","sub_path":"AddSamplingDetailsCall.pyw","file_name":"AddSamplingDetailsCall.pyw","file_ext":"pyw","file_size_in_byte":5073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"147721595","text":"# :coding: utf-8\n# :copyright: Copyright (c) 2015 ftrack\n\nimport getpass\nimport sys\nimport pprint\nimport logging\n\nimport ftrack\nimport ftrack_connect.application\n\n\nclass LaunchApplicationAction(object):\n '''Discover and launch action.'''\n\n identifier = 'ftrack-connect-launch-apps'\n\n def __init__(self, applicationStore, launcher):\n '''Initialise action with *applicationStore* and *launcher*.\n\n *applicationStore* should be an instance of\n :class:`ftrack_connect.application.ApplicationStore`.\n\n *launcher* should be an instance of\n :class:`ftrack_connect.application.ApplicationLauncher`.\n\n '''\n super(LaunchApplicationAction, self).__init__()\n\n self.logger = logging.getLogger(\n __name__ + '.' + self.__class__.__name__\n )\n\n self.applicationStore = applicationStore\n self.launcher = launcher\n\n def register(self):\n '''Register discover actions on logged in user.'''\n ftrack.EVENT_HUB.subscribe(\n 'topic=ftrack.action.discover and source.user.username={0}'.format(\n getpass.getuser()\n ),\n self.discover\n )\n\n ftrack.EVENT_HUB.subscribe(\n 'topic=ftrack.action.launch and source.user.username={0} '\n 'and data.actionIdentifier={1}'.format(\n getpass.getuser(), self.identifier\n ),\n self.launch\n )\n\n def validateSelection(self, selection):\n '''Return true if the selection is valid.\n '''\n self.logger.info(selection)\n\n return True\n\n def discover(self, event):\n '''Return discovered applications.'''\n items = []\n data = event['data']\n selection = data.get('selection', [])\n\n if not self.validateSelection(selection):\n return\n\n applications = self.applicationStore.applications\n applications = sorted(\n applications, key=lambda application: application['label']\n )\n\n for application in applications:\n applicationIdentifier = application['identifier']\n label = application['label']\n items.append({\n 'actionIdentifier': self.identifier,\n 'label': label,\n 'variant': application.get('variant', None),\n 'icon': application.get('icon', 'default'),\n 'applicationIdentifier': applicationIdentifier\n })\n\n return {\n 'items': items\n }\n\n def launch(self, event):\n '''Handle *event*.\n\n event['data'] should contain:\n\n *applicationIdentifier* to identify which application to start.\n\n '''\n items = []\n data = event['data']\n selection = data.get('selection', [])\n\n # if not self.validateArtist(selection):\n # return\n\n applicationIdentifier = (\n event['data']['applicationIdentifier']\n )\n\n context = event['data'].copy()\n\n self.logger.info(\"YEAH\")\n\n # Here you can modify the context setting extra data etc\n # which can be retrieved by parsing the FTRACK_CONNECT_EVENT\n # environment variable in the application.\n\n return self.launcher.launch(\n applicationIdentifier, context\n )\n\n\nclass ApplicationStore(ftrack_connect.application.ApplicationStore):\n\n def _discoverApplications(self):\n '''Return a list of applications that can be launched from this host.\n\n An application should be of the form:\n\n dict(\n 'identifier': 'name_version',\n 'label': 'Name version',\n 'path': 'Absolute path to the file',\n 'version': 'Version of the application',\n 'icon': 'URL or name of predefined icon'\n )\n\n '''\n applications = []\n\n if sys.platform == 'darwin':\n prefix = ['/', 'Applications']\n\n applications.extend(self._searchFilesystem(\n expression=prefix + [\n 'Python*', 'Python.app'\n ],\n label='Python',\n variant='{version}',\n applicationIdentifier='python_{version}',\n icon='http://www.unixstickers.com/image/data/stickers/python/python.sh.png'\n ))\n\n elif sys.platform == 'win32':\n prefix = ['C:\\\\', 'Program Files.*']\n\n applications.extend(self._searchFilesystem(\n expression=[\n 'C:\\\\', 'Python*', 'python.exe'\n ],\n label='Python',\n variant='{version}',\n applicationIdentifier='python_{version}',\n icon='http://www.unixstickers.com/image/data/stickers/python/python.sh.png'\n ))\n\n self.logger.debug(\n 'Discovered applications:\\n{0}'.format(\n pprint.pformat(applications)\n )\n )\n\n return applications\n\n\ndef register(registry, **kw):\n '''Register hooks.'''\n if registry is not ftrack.EVENT_HANDLERS:\n # Exit to avoid registering this plugin again.\n return\n # Create store containing applications.\n applicationStore = ApplicationStore()\n\n # Create a launcher with the store containing applications.\n launcher = ftrack_connect.application.ApplicationLauncher(\n applicationStore\n )\n\n # Create action and register to respond to discover and launch actions.\n action = LaunchApplicationAction(applicationStore, launcher)\n action.register()\n","sub_path":"actions/resource/hook/launch_python.py","file_name":"launch_python.py","file_ext":"py","file_size_in_byte":5596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"217934919","text":"# Copyright 2014-2016 by Akira Yoshiyama .\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\n\"\"\"\nResource class and its manager for volumes on Block Storage V1 API\n\"\"\"\n\nfrom osclient2 import base\nfrom osclient2 import mapper\n\n\nclass Snapshot(base.Resource):\n \"\"\"resource class for volumes on Block Storage V1 API\"\"\"\n\n\nclass Manager(base.Manager):\n \"\"\"manager class for roles on Block Storage V1 API\"\"\"\n\n service_type = 'volume'\n url_resource_path = '/snapshots'\n url_resource_list_path = '/snapshots/detail'\n json_resource_key = 'snapshot'\n json_resources_key = 'snapshots'\n\n resource_class = Snapshot\n attr_mapping = [\n ('id', 'id', mapper.Noop, 'Snapshot ID (string)'),\n ('name', 'display_name', mapper.Noop, 'Snapshot name (string)'),\n ('description', 'display_description', mapper.Noop,\n 'Description (string)'),\n ('size', 'size', mapper.Noop, 'Volume size in GB (int)'),\n ('status', 'status', mapper.Noop, 'Snapshot status (string)'),\n ('volume', 'volume_id',\n mapper.Resource('cinder.v1.volume'), 'Source Volume object'),\n ('progress', 'os-extended-snapshot-attributes:progress', mapper.Noop,\n 'progress (string)'),\n ('project', 'os-extended-snapshot-attributes:project_id',\n mapper.Resource('project'), 'Project (object)'),\n ('metadata', 'metadata', mapper.Noop, 'Snapshot metadata (dict)'),\n ('created_at', 'created_at', mapper.DateTime,\n 'Created timestamp (datetime)'),\n ('updated_at', 'updated_at', mapper.DateTime,\n 'Created timestamp (datetime)'),\n ]\n\n def create(self, name=None, description=None, volume=None,\n force=False):\n return super(Manager, self).create(name=name,\n description=description,\n volume=volume,\n force=force)\n\n def update(self, id):\n raise NotImplementedError()\n","sub_path":"osclient2/cinder/v1/snapshot.py","file_name":"snapshot.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"469200827","text":"import torch\nimport torchvision\nfrom torchvision import transforms\nfrom torch import nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom datetime import datetime\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom model import ResNet\nfrom model import ResidualBlock\nfrom torch.utils.tensorboard import SummaryWriter\n\n'''搭建ResNet18神经网络实现CIFAR-10数据集的图像分类'''\n# metrics = {\n# 'accuracy: ': accuracy_score,\n# 'precision: ': lambda x, y: precision_score(x, y, average='macro'),\n# 'recall: ': lambda x, y: recall_score(x, y, average='macro'),\n# 'confustion matrix: \\n': confusion_matrix\n# }\n\n# 检查GPU是否可用\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# 设定超参数\nnum_epoch = 10\nbatch_size = 100\n\n# 数据下载与预处理\ntrain_transform = transforms.Compose([\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\n])\n\ntest_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\n])\n\ntrain_set = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=train_transform)\ntrain_loader = torch.utils.data.DataLoader(train_set, batch_size=batch_size,\n shuffle=True, num_workers=2)\n\ntest_set = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=test_transform)\ntest_loader = torch.utils.data.DataLoader(test_set, batch_size=batch_size,\n shuffle=False, num_workers=2)\n\n\ndef adjust_learning_rate(optimizer, epoch):\n \"\"\"Sets the learning rate to the initial LR decayed by 10 every 30 epochs\"\"\"\n lr = 0.1 * (0.1 ** (epoch // 3))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\nif __name__ == '__main__':\n # 用于实验的三种优化器\n optims = ['Adam', 'Adagrad', 'SGD']\n for optim in optims:\n lr0 = 0.1\n actfun = 'sigmoid'\n # 计算实验耗时\n start_time = datetime.now()\n net = ResNet(ResidualBlock, actfun=actfun).to(device)\n print(net)\n # 创建tensorboard文件夹\n writer_train_loss = SummaryWriter('./runs/train/' + actfun)\n writer_test_acc = SummaryWriter('./runs/test/' + actfun)\n\n # 损失函数使用交叉熵损失函数\n loss_function = nn.CrossEntropyLoss()\n\n # train_loss = []\n # train_accu = []\n # accuracy = []\n if optim == 'Adam':\n optimizer0 = torch.optim.Adam(net.parameters(), lr=lr0, betas=(0.9, 0.99))\n elif optim == 'Adagrad':\n optimizer0 = torch.optim.Adagrad(net.parameters(), lr=0.01, lr_decay=0, weight_decay=0, initial_accumulator_value=0)\n elif optim == 'SGD':\n optimizer0 = torch.optim.SGD(net.parameters(), lr=lr0)\n\n for epoch in range(num_epoch):\n print('\\nEpoch: %d' % (epoch + 1))\n if epoch > 0 and epoch % 3 == 0:\n lr0 *= 0.1\n print('learning_rate=', lr0)\n \n adjust_learning_rate(optimizer0, epoch)\n net.train()\n sum_loss = 0.0\n correct = 0.0\n total = 0.0\n # 每个i对应一个iteration\n for i, data in enumerate(train_loader, 0):\n length = len(train_loader)\n inputs, labels = data\n inputs, labels = inputs.to(device), labels.to(device)\n # 将模型的参数梯度初始化为0\n optimizer0.zero_grad()\n\n outputs = net(inputs)\n # 下三行代码用于输出网络结构,但是效果不是很好,隐去\n # with SummaryWriter(comment='ResNet-18') as w:\n # w.add_graph(net, (inputs,))\n # print(\"ResNet:\", outputs.shape)\n # 求算损失\n loss = loss_function(outputs, labels)\n # 反向传播\n loss.backward()\n # 更新参数\n optimizer0.step()\n\n sum_loss += loss.item()\n # 取得分最高的那个类 (outputs.data的索引号)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += predicted.eq(labels.data).sum()\n if i % 100 == 99:\n # print('[epoch:%d, iter:%d] Loss: %.03f | Acc: %.3f%% '\n # % (epoch + 1, (i + 1), sum_loss / (i + 1), 100. * correct / total))\n # # train_loss.append(sum_loss / (i + 1))\n # writer_train_loss_lr0.add_scalar('training loss',\n # sum_loss / (i + 1),\n # epoch * len(train_loader) + i)\n print('[epoch:%d, iter:%d] Loss: %.03f | Acc: %.3f%% '\n % (epoch + 1, (i + 1), loss.item(), 100. * correct / total))\n # 也可以用如下的平均损失替代\n # train_loss.append(sum_loss / (i + 1))\n # 每个iteration向tensorboard日志中写入一次训练loss\n writer_train_loss.add_scalar('training loss',\n loss.item(),\n epoch * len(train_loader) + i)\n # train_accu.append(correct / total)\n # 进行测试时不需要求算梯度,提高运算速度\n with torch.no_grad():\n correct = 0\n total = 0\n for data in test_loader:\n net.eval()\n images, labels = data\n images, labels = images.to(device), labels.to(device)\n outputs = net(images)\n # 取得分最高的那个类 (outputs.data的索引号)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum()\n # 每个epoch向tensorboard中写入一次测试集准确率\n writer_test_acc.add_scalar('test accuracy',\n correct / total,\n epoch + 1)\n # accuracy.append(correct / total)\n\n print('Test\\'s accuracy is: %.3f%%' % (100 * correct / total))\n # 计算结束时间\n end_time = datetime.now()\n run_time = end_time - start_time\n\n print('Train has finished, total epoch is %d' % num_epoch)\n print(run_time)\n\n #\n # plt.figure(figsize=(10, 6))\n # plt.subplot(1, 2, 1)\n # plt.plot(range(1, len(train_loss) + 1), train_loss)\n # matplotlib.rcParams['font.sans-serif'] = ['SimHei']\n # matplotlib.rcParams['axes.unicode_minus'] = False\n # plt.xlabel(\"迭代次数/次\")\n # plt.ylabel(\"训练集损失\")\n # plt.title(\"训练集损失-迭代次数\")\n #\n # plt.subplot(1, 2, 2)\n # plt.plot(range(1, len(accuracy) + 1), accuracy,\n # marker='o', mec='r', mfc='w', label='test_accuracy')\n # plt.plot(range(1, len(train_accu) + 1), train_accu,\n # marker='*', ms=10, label='train_accuracy')\n # plt.legend()\n # plt.xlabel(\"epoch\")\n # plt.ylabel(\"准确率\")\n # plt.title(\"训练集与测试集准确率-epoch\")\n # plt.show()\n","sub_path":"cifar10_optimizer.py","file_name":"cifar10_optimizer.py","file_ext":"py","file_size_in_byte":7610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"514065530","text":"#https://linuxhint.com/google_search_api_python/\n\nG_API_KEY = 'AIzaSyAeVsQo5zymUz7DLj1aF_u8NYBbuhWrYqU'\nG_CSE_ID = '007428344889812528205:huvjasy6h0c'\n\nfrom googleapiclient.discovery import build\nmy_api_key = G_API_KEY\nmy_cse_id = G_CSE_ID\n\n\ndef google_search(search_term, api_key, cse_id, **kwargs):\n service = build(\"customsearch\", \"v1\", developerKey=api_key)\n res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()\n return res\n\n\nresult = google_search(\"Hoàng Tử Sơn Ca\", my_api_key, my_cse_id)\nprint(result)\n","sub_path":"gsearch.py","file_name":"gsearch.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"610470128","text":"\"\"\"\nDefines the serializers used in user REST api views.\n\"\"\"\n# pylint: disable=missing-class-docstring\n\nfrom django.db.utils import IntegrityError\nfrom rest_framework import serializers\n\nfrom user_auth.models import UserGroup\nfrom users.models import AppUser\n\n\nclass GroupSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = UserGroup\n fields = ['name', 'authority']\n\n\nclass AppUserListSerializer(serializers.ModelSerializer):\n groups = GroupSerializer(many=True)\n\n class Meta:\n model = AppUser\n fields = [\n 'id',\n 'username',\n 'email',\n 'is_superuser',\n 'groups']\n\n\nclass AppUserCreateSerializer(serializers.ModelSerializer):\n class Meta:\n model = AppUser\n fields = []\n\n def create(self, validated_data):\n try:\n return super().create(validated_data)\n except IntegrityError as ex:\n raise serializers.ValidationError({\"detail\": ex.__cause__})\n\n\nclass GroupRetrieveSerializer(serializers.ModelSerializer):\n class Meta:\n model = UserGroup\n fields = ['name']\n\n\nclass AppUserRetrieveSerializer(serializers.ModelSerializer):\n groups = GroupSerializer(many=True)\n # groups = serializers.SerializerMethodField()\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n class Meta:\n model = AppUser\n fields = [\n 'id',\n 'username',\n 'email',\n 'first_name',\n 'last_name',\n 'is_superuser',\n 'groups',\n 'avatar']\n\n # def get_groups(self, instance):\n # return GroupRetrieveSerializer(\n # instance.groups.all(), many=True, context=self.context).data\n\n\nclass AppUserUpdateSerializer(serializers.ModelSerializer):\n groups = GroupSerializer(many=True, read_only=True)\n\n class Meta:\n model = AppUser\n fields = [\n 'id',\n 'username',\n 'email',\n 'is_superuser',\n 'first_name',\n 'last_name',\n 'groups',\n 'avatar']\n extra_kwargs = {\n 'username': {'read_only': True},\n 'email': {'read_only': True},\n 'is_superuser': {'read_only': True},\n }\n\n def update(self, instance, validated_data):\n try:\n return super().update(instance, validated_data)\n except IntegrityError as ex:\n raise serializers.ValidationError({\"detail\": ex.__cause__})\n","sub_path":"users/api/app_user/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"535341998","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016-2018\n# Author: Marc van Dijk (marcvdijk@gmail.com)\n# file: io_dot_format.py\n\n\"\"\"\nFunctions for exporting and importing graphs to and from graph description\nlanguage (DOT) format\n\"\"\"\n\nimport logging\nimport json\nimport re\nimport shlex\n\nfrom graphit import __module__, version, Graph\nfrom graphit.graph_py2to3 import StringIO, PY_PRIMITIVES\nfrom graphit.graph_exceptions import GraphitException\nfrom graphit.graph_io.io_helpers import coarse_type, open_anything, StreamReader\n\ndirection_splitter = re.compile('(--|->)')\nattribute_splitter = re.compile('(?<=[^0-9]),(?=[^0-9]+)')\n\nlogger = logging.getLogger(__module__)\n\n__all__ = ['write_dot', 'read_dot']\n\n\ndef parse_graph_type(reader, graph):\n \"\"\"\n Parse the start of a DOT graph and set a new Graphit graph for it.\n\n DOT syntax defines a graph as:\n\n <'graph' or 'digraph'> <\"optional title\"> {\n\n :param reader: StreamReader instance\n :type reader: StreamReader\n :param graph: Graph object to import DOT data in\n :type graph: :graphit:Graph\n\n :return: Graphit Graph\n :rtype: :graphit:Graph\n \"\"\"\n\n line, graph_type = reader.read_upto_block(['graph', 'digraph'], keep=True)\n if graph_type:\n line, char = reader.read_upto_char('{')\n line = shlex.split(line)\n if line:\n graph.data['title'] = line[0]\n\n graph.directed = True if graph_type == 'digraph' else False\n graph.data['auto_nid'] = False\n\n logging.info('Graph type \"{0}\" with title: {1}'.format(graph_type, graph.data.get('title', '')))\n return graph\n\n return None\n\n\ndef parse_edge(line, graph, attr=None):\n \"\"\"\n Add DOT edges to the graphit Graph\n\n :param line: line with edges to parse\n :type line: :py:str\n :param graph: Graph to add edges to\n :type graph: :graphit:Graph\n :param attr: attributes to add to edges\n :type attr: :py:dict\n\n :return: added edges\n :rtype: :py:list\n \"\"\"\n\n added_edges = []\n attr = attr or {}\n\n edges = [e.strip() for e in direction_splitter.split(line)]\n for n in [i for i, x in enumerate(edges) if x in ('--', '->')]:\n start_edge, direction, target_edge = edges[n-1:n+2]\n target_edge = target_edge.strip(' {} ').split()\n\n directed = True if direction == '->' else False\n for edge in target_edge:\n node_from_edge = start_edge not in graph.nodes or edge not in graph.nodes\n added_edges.append(graph.add_edge(start_edge, edge,\n directed=directed,\n node_from_edge=node_from_edge,\n **attr))\n\n return added_edges\n\n\ndef parse_attributes(line):\n \"\"\"\n Parse DOT keyword attributes\n\n :param line: line with attributes to parse\n :type line: :py:str\n\n :return: attributes\n :rtype: :py:dict\n \"\"\"\n\n part = ' '.join(shlex.split(line))\n block = attribute_splitter.split(part)\n\n attributes = {}\n for attr in block:\n attr = attr.split('=')\n attributes[attr[0].strip()] = coarse_type(attr[1].strip())\n\n return attributes\n\n\ndef parse_nodes(line, graph):\n \"\"\"\n Add DOT nodes to the graphit Graph\n\n :param line: line with nodes to parse\n :type line: :py:str\n :param graph: Graph to add nodes to\n :type graph: :graphit:Graph\n\n :return: added nodes\n :rtype: :py:list\n \"\"\"\n\n nodes = [l.strip(',') for l in shlex.split(line)]\n\n for node in nodes:\n if node not in graph.nodes:\n graph.add_node(node)\n\n return nodes\n\n\ndef read_dot(dot, graph=None):\n \"\"\"\n Read graph in DOT format\n\n :param dot: DOT graph data.\n :type dot: File, string, stream or URL\n :param graph: Graph object to import DOT data in\n :type graph: :graphit:Graph\n\n :return: Graph object\n :rtype: :graphit:Graph\n \"\"\"\n\n dot_stream = StreamReader(open_anything(dot))\n\n # User defined or default Graph object\n if graph is None:\n graph = Graph()\n elif not isinstance(graph, Graph):\n raise GraphitException('Unsupported graph type {0}'.format(type(graph)))\n\n block = None\n node_attr = {}\n edges = []\n nodes = []\n\n parse = True\n init_graph = False\n while parse or dot_stream.has_more:\n\n # Parse start graph block\n if not init_graph:\n graph = parse_graph_type(dot_stream, graph)\n if graph is not None:\n init_graph = True\n\n # Parse up to DOT reserved chars\n line, char = dot_stream.read_upto_char(('\\n', ';', '[', ']', '}'))\n line = line.strip() if line else ''\n\n if line:\n\n # Comment line\n if line[0] in ('/', '#'):\n logging.info('Skip DOT comment line: \"{0}\"'.format(line))\n\n # Read till end of line\n if char != '\\n':\n dot_stream.read_upto_char('\\n')\n\n # Grouping not supported\n elif line[0] == '{':\n nxt_line, nxt_char = dot_stream.read_upto_char('}')\n logging.info('Skip group: {0}{1}{2}{3}'.format(line, char, nxt_line, nxt_char))\n\n # Subgraphs\n elif 'subgraph' in line:\n block = 'subgraph'\n node_attr[block] = shlex.split(line)[1]\n\n # Node attribute block\n elif 'node' in line:\n block = 'node'\n node_attr = {}\n\n # Parse edges\n elif '--' in line or '->' in line:\n\n attr = {}\n if char == '[':\n attr = parse_attributes(dot_stream.read_upto_char(']')[0])\n edges.extend(parse_edge(line, graph, attr=attr))\n\n else:\n if '=' in line:\n if block in ('subgraph', 'node'):\n node_attr.update(parse_attributes(line))\n else:\n graph.data.update(parse_attributes(line))\n else:\n nodes.extend(parse_nodes(line, graph))\n\n elif (char == '}' and block == 'subgraph') or block == 'node':\n logging.info('Stop parsing {0} group at position: {1}'.format(block, dot_stream.block_pos[1]))\n\n nodes.extend(list(set(sum(edges, ()))))\n for node in nodes:\n graph.nodes[node].update(node_attr)\n\n node_attr = {}\n edges = []\n nodes = []\n block = None\n\n else:\n parse = False\n\n return graph\n\n\ndef write_dot(graph, graph_name=None):\n \"\"\"\n DOT graphs are either directional (digraph) or undirectional, mixed mode\n is not supported.\n\n Nodes and edges are all exported separably, short hand notations are not\n supported. Grouping and supgraphs are not supported.\n Graph attributes in graph.data, graph.edges and graph.nodes will be\n exported as DOT directives regardless if they are official GraphVis DOT\n graph directives as listed in the reference documentation:\n https://www.graphviz.org/doc/info/attrs.html\n\n Dot reserved rendering keywords part of the graphs global attributes in\n graph.data or part of the node and edge attributes are exported as part\n of the DOT graph.\n\n :param graph: Graph object to export\n :type graph: :graphit:Graph\n :param graph_name: name of the 'graph' or 'digraph'. Uses the 'title'\n attribute in graph.data by default, else graph_name\n :type graph_name: :py:str\n\n :return: DOT graph representation\n :rtype: :py:str\n \"\"\"\n\n indent = ' ' * 4\n link = '->' if graph.directed else '--'\n\n # Create empty file buffer\n string_buffer = StringIO()\n\n # Write header comment and graph container\n graph_name = graph.data.get('title', graph_name or 'graph')\n string_buffer.write('//Created by {0} version {1}\\n'.format(__module__, version()))\n string_buffer.write('{0} \"{1}\" {2}\\n'.format('digraph' if graph.directed else 'graph', graph_name, '{'))\n\n # Write global DOT directives\n for dot_key, dot_value in graph.data.items():\n if isinstance(dot_value, PY_PRIMITIVES) and not dot_key.startswith('$'):\n string_buffer.write('{0}{1}={2}\\n'.format(indent, dot_key, json.dumps(dot_value)))\n\n # Export nodes\n string_buffer.write('{0}//nodes\\n'.format(indent))\n for node in graph.iternodes():\n attr = ['{0}={1}'.format(k, json.dumps(v)) for k, v in node.nodes[node.nid].items() if\n isinstance(v, PY_PRIMITIVES) and not k.startswith('$')]\n if attr:\n string_buffer.write('{0}{1} [{2}];\\n'.format(indent, node.nid, ','.join(attr)))\n\n # Export adjacency\n string_buffer.write('{0}//edges\\n'.format(indent))\n done = []\n for edge in graph.edges:\n if edge not in done:\n edges = sorted([edge, edge[::-1]])\n\n attr = []\n for e in edges:\n attr.extend(['{0}={1}'.format(k, json.dumps(v)) for k, v in graph.edges[e].items()\n if isinstance(v, PY_PRIMITIVES) and not k.startswith('$')])\n\n start, end = edges[0]\n if attr:\n string_buffer.write('{0}{1} {2} {3} [{4}];\\n'.format(indent, start, link, end, ','.join(attr)))\n else:\n string_buffer.write('{0}{1} {2} {3};\\n'.format(indent, start, link, end))\n\n done.extend(edges)\n\n # Closing curly brace\n string_buffer.write('}\\n')\n\n # Reset buffer cursor\n string_buffer.seek(0)\n return string_buffer.read()\n","sub_path":"graphit/graph_io/io_dot_format.py","file_name":"io_dot_format.py","file_ext":"py","file_size_in_byte":9772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"553959676","text":"import json\n\n\nasync def test_cars_get(cli):\n resp = await cli.get('/cars')\n assert resp.status == 200\n resp = await resp.json()\n assert resp\n\n\nasync def test_cars_post(cli):\n data = {\n 'year': 1997, 'mileage': 20000, 'price': 100500, 'body_type': 'Hatchback',\n 'transmission': 'Automatic', 'fuel_type': 'Diesel', 'exterior_color': 'White',\n }\n resp = await cli.post('/cars', data=json.dumps(data))\n assert resp.status == 200\n resp = await resp.json()\n assert '_id' in resp\n assert '$oid' in resp['_id']\n","sub_path":"tests/api/test_car.py","file_name":"test_car.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"155083476","text":"from google.appengine.api import search\nfrom google.appengine.ext import (\n deferred,\n ndb,\n)\nfrom protorpc import (\n message_types,\n)\nimport endpoints\nimport tap\nimport tap.endpoints\n\nfrom api import api\nimport message\nimport model\n\nrate_limit = tap.endpoints.rate_limit(rate=50, size=50, key=tap.endpoints.get_user_id_or_ip, tag=\"timecard:api\")\n\nclass user(object):\n @staticmethod\n @ndb.tasklet\n def store(user):\n key = model.User.gen_key(user.user_id())\n entity = yield key.get_async()\n if entity is None:\n entity = model.User(key=key)\n entity.name = user.name\n entity.language = user.language\n entity.put_async()\n UserSearchIndex.update(user)\n\n@api.api_class(resource_name=\"me\", path=\"me\")\nclass Me(tap.endpoints.CRUDService):\n\n @endpoints.method(message_types.VoidMessage, message.UserResponse)\n @ndb.toplevel\n @rate_limit\n def get(self, _request):\n user_key = model.User.gen_key(tap.endpoints.get_user_id())\n entity = yield user_key.get_async()\n if entity is None:\n raise endpoints.NotFoundException()\n\n raise ndb.Return(message.UserResponse(\n key = entity.key.string_id(),\n name = entity.name,\n language = entity.language,\n ))\n\n @endpoints.method(message.UserRequestNew, message.UserResponse)\n @ndb.toplevel\n @rate_limit\n def create(self, request):\n user_key = model.User.gen_key(tap.endpoints.get_user_id())\n entity = yield user_key.get_async()\n if entity is not None:\n raise endpoints.ForbiddenException()\n\n entity = model.User(\n key = user_key,\n name = request.name,\n )\n\n language = request.language\n if language is None:\n accept_language = self.request_state.headers.get(\"Accept-Language\")\n if accept_language:\n for lang in [locale.split(\";\", 1)[0].replace(\"-\", \"_\") for locale in accept_language.split(\",\")]:\n if lang in model.LANGUAGE_CHOICES_VALUES:\n language = lang\n if language is not None:\n entity.language = language\n\n try:\n future = entity.put_async()\n future.check_success()\n except Exception as e:\n raise endpoints.BadRequestException(e.message)\n UserSearchIndex.update(entity)\n raise ndb.Return(message.UserResponse(\n key = entity.key.string_id(),\n name = entity.name,\n language = entity.language,\n ))\n\n @endpoints.method(message.UserRequest, message.UserResponse)\n @ndb.toplevel\n @rate_limit\n def update(self, request):\n user_key = model.User.gen_key(tap.endpoints.get_user_id())\n entity = yield user_key.get_async()\n if entity is None:\n raise endpoints.BadRequestException()\n\n modified = False\n for field in request.all_fields():\n name = field.name\n if name == \"key\":\n continue\n value = request.__getattribute__(name)\n if value is None:\n continue\n entity.__setattr__(name, value)\n modified = True\n else:\n if modified is False:\n raise endpoints.BadRequestException()\n try:\n future = entity.put_async()\n future.check_success()\n except Exception as e:\n raise endpoints.BadRequestException(e.message)\n UserSearchIndex.update(entity)\n raise ndb.Return(message.UserResponse(\n key = entity.key.string_id(),\n name = entity.name,\n language = entity.language,\n ))\n\n @endpoints.method(message.UserRequestDelete, message_types.VoidMessage)\n @ndb.toplevel\n @rate_limit\n def delete(self, request):\n user_id = tap.endpoints.get_user_id()\n if request.key != user_id:\n raise endpoints.BadRequestException()\n user_key = model.User.gen_key(user_id)\n entity = yield user_key.get_async()\n if entity is None:\n raise endpoints.NotFoundException()\n if request.name != entity.name:\n raise endpoints.BadRequestException()\n\n query = model.Project.query(model.Project.admin == user_key)\n result = yield query.get_async(keys_only=True)\n if result:\n raise endpoints.ForbiddenException()\n\n future = entity.key.delete_async()\n if future.check_success():\n raise future.get_exception()\n deferred.defer(UserSearchIndex.delete, user_id)\n raise ndb.Return(message_types.VoidMessage())\n\n@api.api_class(resource_name=\"user\", path=\"user\")\nclass User(tap.endpoints.CRUDService):\n\n @endpoints.method(message.UserRequestListCollection, message.UserResponseCollection)\n @ndb.toplevel\n @rate_limit\n def list(self, request):\n key_list = list()\n for user_receive_list in request.items:\n key_list.append(model.User.gen_key(user_receive_list.key))\n if key_list:\n entities = yield ndb.get_multi_async(key_list)\n else:\n raise endpoints.BadRequestException(\"Bad query\")\n items = list()\n for user in entities:\n if user is None:\n continue\n items.append(message.UserResponse(key=user.user_id,\n name=user.name,\n language=user.language))\n raise ndb.Return(message.UserResponseCollection(\n items = items,\n ))\n\n @endpoints.method(message.UserRequestSearch, message.UserResponseCollection)\n @ndb.toplevel\n @rate_limit\n def search(self, request):\n if len(request.query.encode(\"utf-8\")) < 3:\n raise endpoints.BadRequestException(\"Bad query\")\n query = search.Query(\n query_string = request.query,\n options = search.QueryOptions(\n limit = 20,\n cursor = search.Cursor(web_safe_string=request.pagination),\n ids_only = True,\n ),\n )\n key_list = list()\n documents = UserSearchIndex.search_index.search(query)\n for document in documents:\n key_list.append(ndb.Key(model.User, document.doc_id))\n items = list()\n if key_list:\n entities = yield ndb.get_multi_async(key_list)\n for user in entities:\n if user is None:\n continue\n items.append(message.UserResponse(key=user.user_id,\n name=user.name,\n language=user.language))\n if documents.cursor:\n cursor_string = documents.cursor.web_safe_string\n else:\n cursor_string = None\n raise ndb.Return(message.UserResponseCollection(\n items = items,\n pagination = cursor_string,\n ))\n\nclass UserSearchIndex(object):\n\n search_index = search.Index(name=\"timecard:user\")\n\n @classmethod\n def update(cls, user):\n deferred.defer(cls.put, user.user_id, user.name)\n\n @classmethod\n def put(cls, doc_id, name):\n cls.search_index.put(search.Document(\n doc_id = doc_id,\n fields = [search.TextField(name=\"a\", value=name)],\n ))\n\n @classmethod\n def delete(cls, doc_id):\n cls.search_index.delete(doc_id)\n","sub_path":"gae/main_api/v1/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":6698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"134485303","text":"class BaseDedados:\r\n def __init__(self):\r\n self.__dados = {}\r\n def inserir_cliente(self,id,nome):\r\n if 'clientes' not in self.__dados:\r\n self.__dados['clientes']={id: nome}\r\n else:\r\n self.__dados['clientes'].update({id:nome})\r\n def lista_clientes(self):\r\n for id,nome in self.__dados['clientes'].items():\r\n print(id,nome)\r\n def apaga_cliente(self,id):\r\n del self.__dados['clientes'][id]\r\n\r\n\r\nbd = BaseDedados()\r\n\r\nbd.inserir_cliente(1,'Eduardo')\r\nbd.inserir_cliente(2,'Joao')\r\nbd.inserir_cliente(3,'Maria')\r\nbd.inserir_cliente(4,'Pedro')\r\n\r\nbd.lista_clientes()\r\nprint()\r\nbd.apaga_cliente(3)\r\nbd.lista_clientes()","sub_path":"encapsulamento.py","file_name":"encapsulamento.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"464970911","text":"# -*- coding:utf-8 -*-\n# @Script: main.py\n# @Author: Zhiwei.Yang\n# @Email: tencrance@gmail.com\n# @Create At: 2018-08-26 02:11:48\n# @Last Modified By: Zhiwei.Yang\n# @Last Modified At: 2018-08-26 02:17:16\n# @Description: This is description.\n\n\n\nimport requests\nfrom bs4 import Tag\nfrom bs4 import BeautifulSoup\n \n \ndef getHtml(url):\n page = requests.get(url)\n html =page.text\n return html\n \ndef getText(html):\n get_text = Tag.get_text\n soup = BeautifulSoup(html, 'html.parser')\n \n author_info = soup.find_all('div', class_='info')\n listauthor = [x.get_text() for x in author_info]\n \n list_info = soup.find_all('div', class_='reply-div')\n listtext = [x.get_text() for x in list_info]\n \n # global i\n if i > 1:\n listtext = [\"\"] + listtext\n \n for x in range(len(listauthor)):\n if \"kkndme\" in listauthor[x]:\n print (listtext[x].strip())\n \nif __name__=='__main__':\n for i in range(1,6):\n url = (\"http://bbs.tianya.cn/m/post-house-252774-%s.shtml\" % str(i))\n html = getHtml(url)\n getText(html)\n","sub_path":"web_crawl/tianya/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"291064654","text":"from collections import Counter\nfrom Bio import SeqIO\ndef determineGCCount(dnaString):\n\tcount = Counter(dnaString)\n\tcCount = count['C']\n\tgCount = count['G']\n\tpercentage = (gCount+cCount)/ len(dnaString)\n\treturn percentage * 100\n\n\nstring = []\nrecordID = []\ntestDict = {}\nwith open(\"rosalind_gc.txt\") as f:\n\tfor record in SeqIO.parse(f, \"fasta\"):\n\t\tstring.append(\"{}\".format(record.seq))\n\t\trecordID.append(record.id)\nf.close()\n\nfor x in range(0,len(string)):\n\ttest = string[x]\n\ttestDict.update({recordID[x]:determineGCCount(test)})\n\n#print(string)\n#print(recordID)\nprint(testDict)\n","sub_path":"Rosalind/GCContent.py","file_name":"GCContent.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"302059585","text":"import ai\r\nimport bi\r\nimport ci\r\nimport di\r\nimport ei\r\nimport csv\r\nfrom bs4 import BeautifulSoup\r\n\r\nprint('특허 정보 검색프로그램을 실행합니다.')\r\nfn = '개인과제data.txt'\r\n\r\nprint('원하시는 검색조건의 숫자를 입력하세요' , '\\n', '1) 출원인 입력하여 특허찾기 2) 발명가 입력하여 특허찾기 3) 키워드 입력하여 특허찾기 4) 특정 특허의 특허 설명 5) 본 데이터내의 특허 정보 정리')\r\n\r\na = input('1 or 2 or 3 or 4 or 5 : ')\r\n\r\nif a == '1' :\r\n print('출원인을 검색하여 특허 찾기를 선택하셨습니다.')\r\n language = input('출원인의 이름을 어떤 언어로 입력하시겠습니까? (\\'한글\\' 또는 \\'영어\\'로 입력해주세요) : ')\r\n\r\n if language == '한글' :\r\n print('출원인 - 한글이름으로 찾기를 선택하셨습니다. ')\r\n name = input('찾고자하는 출원인의 이름을 입력해주세요. (출원인 목록을 확인하려면 1번을 눌러주세요.) : ')\r\n print('잠시만 기다려 주세요..')\r\n try :\r\n if name == '1' :\r\n ai.find_all_applicant(fn)\r\n name = input('출원인의 이름을 입력해주세요. : ')\r\n print('잠시만 기다려 주세요..')\r\n ai.find_apllicant(fn,name)\r\n else:\r\n ai.find_apllicant(fn,name)\r\n \r\n except Exception :\r\n print('이름을 확인해 주세요!')\r\n\r\n elif language == '영어':\r\n name = input('Please typing English name that you want to find. (If you want check the list of applicants, input number 1) : ')\r\n print('Pleas waiting..')\r\n try :\r\n if name == '1' :\r\n ai.find_all_applicant_eng(fn)\r\n name = input('Please typing English name that you want to find. : ')\r\n ai.find_apllicant_eng(fn,name)\r\n else:\r\n ai.find_apllicant_eng(fn,name)\r\n \r\n except Exception :\r\n print('Please Check name! ')\r\n else :\r\n print('\\'한글\\' 또는 \\'영어\\'를 입력해주세요.')\r\n\r\n \r\nelif a == '2' :\r\n print('\\n','발명인을 검색하여 특허 찾기를 선택하셨습니다.')\r\n language = input('발명인의 이름을 어떤 언어로 입력하시겠습니까? (\\'한글\\' 또는 \\'영어\\'로 입력해주세요) : ')\r\n\r\n if language == '한글' :\r\n name = input('찾고자하는 발명인의 이름을 입력해주세요. (발명인의 목록을 확인하려면 1번을 눌러주세요.) :')\r\n\r\n if name == '1' :\r\n bi.find_all_inventor(fn)\r\n name = input('발명인의 이름을 입력해주세요. : ')\r\n print('로딩 중입니다..')\r\n bi.find_inventor(fn,name)\r\n else:\r\n print('로딩 중입니다..')\r\n bi.find_inventor(fn,name)\r\n\r\n elif language == '영어':\r\n name = input('Please typing English name that you want to find. (If you want check the list of Inventors, input number 1) : ')\r\n print('Pleas waiting..')\r\n try :\r\n if name == '1' :\r\n \r\n bi.find_all_inventor_eng(fn)\r\n name = input('Please typing English name that you want to find. : ')\r\n bi.find_inventor_eng(fn,name)\r\n \r\n else:\r\n bi.find_inventor_eng(fn,name)\r\n except Exception :\r\n print('Please Check name! ')\r\n else :\r\n print('\\'한글\\' 또는 \\'영어\\'를 입력해주세요.')\r\n\r\nelif a == '3':\r\n print('키워드을 검색하여 특허 찾기를 선택하셨습니다.')\r\n print('로딩 중입니다..') \r\n ci.find_key_title(fn)\r\n\r\n\r\nelif a == '4':\r\n print('\\n', '특정 특허의 특허 설명 찾기를 선택하셨습니다.')\r\n name = input('찾고자하는 특허명을 입력해주세요. (특허 목록을 출력하려면 \\'특허-목록\\'을 입력해주세요.): ')\r\n \r\n\r\n if name == '특허-목록':\r\n \r\n di.find_titles(fn,name)\r\n name = input('찾고자하는 특허명을 입력해주세요.:')\r\n print('로딩 중입니다.. ')\r\n di.find_claims(fn, name)\r\n\r\n \r\n else :\r\n print('로딩 중입니다..')\r\n di.find_claims(fn, name)\r\n \r\nelif a == '5' :\r\n print('본 데이터 내의 특허 명, 출원인, 발명가, 특허 초록, 특허 설명을 출력 및 저장하는 프로그램입니다. ')\r\n print('로딩 중입니다..','\\n')\r\n ei.write_Invent(fn)\r\n\r\n\r\nelse :\r\n print('입력 번호를 확인 후 다시 시도해주세요.')\r\n","sub_path":"개인과제/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"609996598","text":"from setuptools import setup,find_packages\n\n\nimport os\nhere = os.path.abspath(os.path.dirname(__file__))\nreadme = open(os.path.join(here, 'README.md'), 'r').read()\nchangelog = open(os.path.join(here, 'README.md'), 'r').read()\n\nsetup(name='ppss_auth',\n version='0.7.4.1',\n description='simple auth scheme for pyramid, based on Mako template and sqlalchemy backend',\n long_description=readme + \"\\n\\n\\n\" + changelog,\n long_description_content_type=\"text/markdown\",\n author='pdepmcp',\n author_email='d.cariboni@pingpongstars.it',\n license='MIT',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Operating System :: OS Independent',\n 'Framework :: Pyramid',\n 'Topic :: Internet :: WWW/HTTP :: Session',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 2.7',\n ],\n keywords=\"pyramid module authentication accelerator\",\n python_requires='>=2.7',\n url='http://www.pingpongstars.it',\n install_requires=['pyramid_mako','pyramid_beaker' ],\n #packages=['src/test1'],\n packages=find_packages(),\n include_package_data=True,\n\n)\n\n\n","sub_path":"pypi_install_script/ppss_auth-0.7.4.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"54655462","text":"#import packages.\nfrom skimage.filters import threshold_local\nimport numpy as np \nimport argparse\nimport cv2\nimport imutils\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--image\", required = True, help = \"path of image\")\nargs = vars(ap.parse_args())\n\nprint(args)\n\n#load image\n\n\nimage = cv2.imread(args[\"image\"])\nratio = image.shape[0] / 500.0\norig = image.copy()\nimage = imutils.resize(image, height = 500)\n\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\ngray = cv2.GaussianBlur(gray, (5, 5), 0)\nedged = cv2.Canny(gray, 75, 200)\n\nprint(\"Edge Detection yas\")\ncv2.imshow(\"Image\", image)\ncv2.imshow(\"Edged\", edged)\ncv2.waitKey(0)\n","sub_path":"misc/timestabler-scan.py","file_name":"timestabler-scan.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"413890508","text":"# https://www.youtube.com/watch?v=JcI5Vnw0b2c&index=2&list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v\n# Regression Intro - Practical Machine Learning Tutorial with Python p.2\nimport pandas as pd\nimport quandl\n\nstyle.use('ggplot')\n\n# quandl.ApiConfig.api_key = '9tnd3zJgSopfWdp5g7eT'\n# df = quandl.get(\"WIKI/GOOGL\")\n# df.to_csv('data/shift_google.csv')\n\ndf = pd.read_csv('data/shift_google.csv')\ndf = df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']]\ndf['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close'] * 100.0\ndf['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100.0\n\ndf = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume']]\nprint(df.head())\n","sub_path":"sentdex/machine-learning/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"109575981","text":"import scrapy\n\nfrom scrapy.http import FormRequest\nfrom scrapy.spiders import Spider\nimport csv\nimport string\nimport re\nimport codecs\nimport json\nimport requests\n\n\n\n\n\n\nclass DmozSpider(Spider):\n\tname = \"delta\"\n\t\"allowed_domains = ['bancamarch.es']\"\n\t\"start_urls = ['https://telemarch.bancamarch.es/htmlVersion/index.jsp?idioma=es']\"\n\n\n\tdef start_requests(self):\n\t\t\"urls = ['file:///home/yago/tranz-scrapy/tutorial/tutorial/spiders/body.html']\"\n\t\turls = ['https://telemarch.bancamarch.es/htmlVersion/index.jsp?idioma=es']\n\t\tfor url in urls:\n\t\t\tyield scrapy.Request(url=url, callback=self.parse)\n\n\tdef parse(self, response):\n\t\tyield FormRequest.from_response(response,formname='basic',formdata={'usuario': '5078281','clave': '5709'},callback=self.parse1)\n\n\n\tdef parse1(self, response):\n\t\t\n\n\n\t\t\n\t\tnext_page = response.css('li.opid_163 a::attr(href)').extract_first()\n\t\t\n\t\tnext_page = response.urljoin(next_page)\n\t\t\n\n\t\t\n\t\tyield scrapy.Request(next_page, callback=self.parse2)\n\n\n\n\tdef parse2(self, response):\n\t\t\n\n\t\tyield FormRequest.from_response(response,formname='f3002',callback=self.parse3)\n\t\t\n\tdef parse3(self, response):\n\t\t\n\t\t\n\t\ttable1 = []\n\t\trow1 = []\n\t\trows = response.xpath('//table[@id=\"tablaMovimientos\"]/tbody/tr')\n\t\tfor row in rows:\n\t\t\t\n\t\t\t\n\t\t\ttd1 = row.xpath('td[1]/text()').extract()\n\t\t\t\n\t\t\ttd1 = ''.join(c for c in td1 if c not in '\\r\\t\\n')\n\t\t\t\n\t\t\ttd1 = re.sub('[\\t\\r\\n]','',td1)\n\t\t\t\n\t\t\trow1.append({'fecOp':td1})\n\t\t\ttd2 = row.xpath('td[2]/text()').extract()\n\t\t\ttd2 = ''.join(c for c in td2 if c not in '\\r\\t\\n')\n\t\t\ttd2 = re.sub('\\W+','', td2 )\n\n\n\t\t\trow1.append({'fecVal':td2})\n\t\t\ttd3 = row.xpath('td[3]/text()').extract()\n\t\t\ttd3 = ''.join(c for c in td3 if c not in '\\r\\t\\n')\n\t\t\t\"td3 = re.sub('\\W+','', td3 )\"\n\t\t\ttd3 = re.sub('[\\t\\r\\n]','',td3)\n\t\t\t\n\t\t\t\n\t\t\trow1.append({'oficina':td3})\n\t\t\ttd4 = row.xpath('td[4]/text()').extract()\n\t\t\ttd4 = ''.join(c for c in td4 if c not in '\\r\\t\\n')\n\t\t\ttd4 = re.sub('[\\t\\r\\n]','',td4)\n\t\t\trow1.append({'Concepto':td4})\n\t\t\ttd5 = row.xpath('td[5]/text()').extract()\n\t\t\ttd5 = ''.join(c for c in td5 if c not in '\\r\\t\\n')\n\t\t\ttd5 = re.sub('[\\t\\r\\n]','',td5)\n\t\t\t\n\t\t\ttd5 = td5.replace(u'\\u20ac','EUR')\n\t\t\trow1.append({'Importe':td5})\n\t\t\ttd6 = row.xpath('td[6]/text()').extract()\n\t\t\ttd6 = ''.join(c for c in td6 if c not in '\\r\\t\\n')\n\t\t\ttd6 = re.sub('[\\t\\r\\n]','',td6)\n\t\t\t\n\t\t\ttd6 = td6.replace(u'\\u20ac','EUR')\n\t\t\trow1.append({'Saldo':td6})\n\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\ttable1.append(row1)\n\t\t\trow1 = []\n\t\t\n\t\tpost_json(table1)\n\n\n\ndef post_json(tbl):\n\t\n\ttabla = json.dumps(tbl)\n\tr = requests.post('http://127.0.0.1:3000/bancamarch', data={'json': tabla})\n\t\n","sub_path":"tutorial/tutorial/spiders/delta.py","file_name":"delta.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"288290369","text":"# /tests/unit_test.py\n#\n# Unit tests for various utilities.\n#\n# Disable no-self-use in tests as all test methods must be\n# instance methods and we don't necessarily have to use a matcher\n# with them.\n# pylint: disable=no-self-use\n#\n# See LICENCE.md for Copyright information\n\"\"\"Unit tests for various utilities.\"\"\"\n\nimport os\n\nfrom psqtraviscontainer import architecture\nfrom psqtraviscontainer import directory\nfrom psqtraviscontainer import distro\n\nfrom testtools import ExpectedException\nfrom testtools import TestCase\n\nfrom testtools.matchers import AllMatch\nfrom testtools.matchers import DirExists\nfrom testtools.matchers import MatchesPredicate\n\n\nclass TestDirectoryNavigation(TestCase):\n\n \"\"\"Tests for directory.py.\"\"\"\n\n def test_enter_create_dir(self):\n \"\"\"Check that we create a dir when entering a non-existent one.\"\"\"\n does_not_exist = \"does_not_exist\"\n with directory.Navigation(os.path.join(os.getcwd(),\n does_not_exist)) as entered:\n self.assertThat(entered, DirExists())\n\n def test_enter_exist_dir(self):\n \"\"\"Check that we can enter an existing dir.\"\"\"\n existing_dir = os.path.join(os.getcwd(), \"existing\")\n os.makedirs(existing_dir)\n with directory.Navigation(existing_dir) as entered:\n self.assertThat(entered, DirExists())\n\n\nclass TestArchitecture(TestCase): # pylint:disable=R0903\n\n \"\"\"Tests for architecture.py.\"\"\"\n\n def test_unknown_architecture(self):\n \"\"\"Check that creating a non-special architecture returns metadata.\"\"\"\n check_methods = [\n architecture.Alias.universal,\n architecture.Alias.qemu,\n architecture.Alias.debian\n ]\n\n def function_returns_input(function):\n \"\"\"Return true if function returns input.\"\"\"\n return function(\"input\") == \"input\"\n\n self.assertThat(check_methods,\n AllMatch(MatchesPredicate(function_returns_input,\n \"% did not return same\")))\n\n\nclass TestDistroLookup(TestCase): # pylint:disable=R0903\n\n \"\"\"Tests for looking up the distro.\"\"\"\n\n def test_error_lookup_bad_distro(self):\n \"\"\"Check that looking up a non-existent distro throws.\"\"\"\n with ExpectedException(RuntimeError):\n distro.lookup(\"noexist\", \"noexist\", \"noexist\")\n","sub_path":"tests/unit_test.py","file_name":"unit_test.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"21960335","text":"import sys, collections, heapq\n\ninput = sys.stdin.readline\nN = int(input())\nM = int(input())\narr = collections.defaultdict(list)\nfor i in range(M):\n a, b, c = map(int, input().split())\n arr[a].append((b, c))\nstart, end = map(int, input().split())\ndiscoverd = [False] * (N + 1)\nqueue = [(0, start,[start])]\nwhile queue:\n dis, node, route= heapq.heappop(queue)\n if node == end:\n print(dis)\n print(len(route))\n print(' '.join(map(str,route)))\n break\n if not discoverd[node]:\n discoverd[node] = True\n for i, e in arr[node]:\n heapq.heappush(queue, (dis + e, i, route+[i]))\n","sub_path":"백준/다익스트라/최소비용구하기2.py","file_name":"최소비용구하기2.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"43428025","text":"from rest_framework import serializers\nfrom back.models import Task, Volonteer, Post\n\n\nclass TaskSerializer(serializers.Serializer):\n id = serializers.IntegerField(read_only=True)\n status = serializers.IntegerField(default=1)\n user_id = serializers.CharField(default=0)\n\n def create(self, validated_data):\n \"\"\"\n Create and return a new `Task` instance, given the validated data.\n \"\"\"\n return Task.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n \"\"\"\n Update and return an existing `Task` instance, given the validated data.\n \"\"\"\n instance.status = validated_data.get('status', instance.status)\n instance.user_id = str(instance.user_id) + ',' + str(validated_data.get('user_id', instance.user_id))\n instance.save()\n return instance\n\nclass PostSerializer(serializers.Serializer):\n id = serializers.IntegerField(read_only=True)\n description = serializers.CharField(default='Не задано')\n place = serializers.CharField(default='Не задано')\n custom = serializers.CharField(default='Не задано')\n lat = serializers.FloatField()\n lon = serializers.FloatField()\n\n def create(self, validated_data):\n \"\"\"\n Create and return a new `Task` instance, given the validated data.\n \"\"\"\n import vk_api\n login, password = 'dostoyewski@yandex.ru', 'seleNa'\n vk_session = vk_api.VkApi(login, password)\n try:\n vk_session.auth(token_only=True)\n except vk_api.AuthError as error_msg:\n print(error_msg)\n\n vk = vk_session.get_api()\n string = 'ALERT' + '\\n' + 'Описание проблемы: ' + validated_data.get('description') + '\\n' + 'Примерное местоположение: ' + validated_data.get('place') + '\\n' + 'Особые приметы: ' + validated_data.get('custom')\n vk.wall.post(message=string, owner_id=-180054668, from_group=1, lat=validated_data.get('lat'), long=validated_data.get('lon'))\n return Post.objects.create(**validated_data)\n\nclass VolonteerSerializer(serializers.Serializer):\n id = serializers.IntegerField(read_only=True)\n allergy = serializers.BooleanField(default=True)\n karma = serializers.IntegerField(default=0)\n\n def create(self, validated_data):\n \"\"\"\n Create and return a new `Volonteer` instance, given the validated data.\n \"\"\"\n return Volonteer.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n \"\"\"\n Update and return an existing `Volonteer` instance, given the validated data.\n \"\"\"\n instance.allergy = validated_data.get('allergy', instance.allergy)\n instance.karma = validated_data.get('karma', instance.karma)\n instance.save()\n return instance","sub_path":"back/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"109177614","text":"from django.urls import path\n\nfrom core.views import FetchExams, VerifyExamView, ExamListView, ExamDetailView, \\\n ExamListItemUpdateView\n\n\n\nurlpatterns = [\n path('', FetchExams.as_view({'post': 'post'}), name='fetch-exams'),\n path('exams/', ExamListView.as_view(), name='exams-list'),\n path('exams//', ExamDetailView.as_view(), name='exam-detail'),\n path('exam-list_item//', ExamListItemUpdateView.as_view(), name='exam-item-update'),\n path('/', VerifyExamView.as_view({'post': 'post'}), name='verify-exam'),\n\n]\n","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"352374455","text":"import time\n\n\nt1 = time.time()\n\n\nBianaNetworkFile = open('subnetwork.sif.5', 'r')\ngeneIdNetworkFile = open('PPI_Network.txt', 'w')\nnodeGeneIdsFile = open('Network_Gene_Ids.txt', 'w')\nscoresFile = open('guild_scores.txt', 'r')\ngeneScores = scoresFile.readlines();\nscoresFile.close()\ngeneIds = set()\n\n\nfor edge in BianaNetworkFile:\n node1 = 0\n node2 = 0\n found1 = False\n found2 = False\n splittedEdge = edge.split(' ')\n\n for geneInfo in geneScores:\n \n splittedGeneInfo = geneInfo.split('\\t')\n \n if splittedGeneInfo[0] == splittedEdge[0]:\n node1 = splittedGeneInfo[5]\n found1 = True\n \n elif splittedGeneInfo[0] == splittedEdge[2][:-1]:\n node2 = splittedGeneInfo[5]\n found2 = True\n \n if found1 and found2:\n break\n\n if node1.isdigit() and node2.isdigit():\n geneIdNetworkFile.write(str(node1) + ' interaction ' + str(node2) + '\\n')\n geneIds.add(node1)\n geneIds.add(node2)\n\t\t\nfor geneId in geneIds:\n nodeGeneIdsFile.write(geneId + '\\n')\n\t\t\n\nBianaNetworkFile.close()\ngeneIdNetworkFile.close()\nnodeGeneIdsFile.close()\nt2 = time.time()\nprint('Elapsed time = %f' %(t2-t1))\n","sub_path":"IdMapping.py","file_name":"IdMapping.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"419036719","text":"def NumberOfDigits(no):\r\n counter=0\r\n while no!=0:\r\n no=no//10\r\n print(no)\r\n counter=counter+1\r\n\r\n return counter\r\n\r\ndef main():\r\n num = int(input(\"Enter a number: \"))\r\n ans=NumberOfDigits(num)\r\n print(\"Number of Digits in {} are {}\".format(num,ans))\r\n\r\nif __name__==\"__main__\":\r\n main()\r\n \r\n \r\n","sub_path":"Assignment9_2.py","file_name":"Assignment9_2.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"50925197","text":"from django.shortcuts import render\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef scrap():\n url = 'https://www.gov.pl/web/koronawirus/wykaz-zarazen-koronawirusem-sars-cov-2'\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n table = soup.find(\"pre\").find(text=True)\n x = table.split(\";\")\n context = {'whole_amount': x[4], 'death_amount': x[5], 'dolnoslaskie': x[7], 'dolnoslaskie_d': x[8],\n 'kujawsko': x[10], 'kujawsko_d': x[11], 'lubelskie': x[13], 'lubelskie_d': x[14],\n 'lubuskie': x[16], 'lubuskie_d': x[17], 'lodzkie': x[19], 'lodzkie_d': x[20],\n 'malopolskie': x[22], 'malopolskie_d': x[23], 'mazowieckie': x[25], 'mazowieckie_d': x[26],\n 'opolskie': x[28], 'opolskie_d': x[29], 'podkarpackie': x[31], 'podkarpackie_d': x[32],\n 'podlaskie': x[34], 'podlaskie_d': x[35], 'pomorskie': x[37], 'pomorskie_d': x[38],\n 'slaskie': x[40], 'slaskie_d': x[41], 'swietokrzyskie': x[43], 'swietokrzyskie_d': x[44],\n 'warminsko_mazurskie': x[46], 'warminsko_mazurskie_d': x[47], 'wielkopolskie': x[49],\n 'wielkopolskie_d': x[50], 'zachodniopomorskie': x[52], 'zachodniopomorskie_d': x[53]\n }\n return context\n\n\ndef corona(request):\n return render(request, 'corona/index.html', scrap())\n\n\ndef details(request):\n return render(request, 'corona/detail.html', scrap())\n","sub_path":"corona/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"378971833","text":"from django.conf.urls import url\nfrom hotel.Notification import views\n\nurlpatterns = [\n url(r'^notifications/$', views.index, name='notification'),\n url(r'^getNotifications/$', views.getNotifications, name='getNotifications'),\n url(r'^save_update/$', views.save_update, name='save_update'),\n url(r'^save_update/(?P[0-9]+)/$', views.save_update, name='save_update_main'),\n url(r'^getNotificationsById/$', views.getNotificationsById, name='getNotificationsById'),\n url(r'^removeNotifications/$', views.removeNotifications, name='removeNotifications'),\n url(r'^updateStatus/$', views.updateStatus, name='updateStatus'),\n]","sub_path":"eCube_Hotel_2/eCube_UI_2/hotel/Notification/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"404199614","text":"'''\nfrom evelink import api\nfrom evelink import eve\nfrom evelink import char\n\ncharacter = 'Py Solette'\nkey = 4414604\nvcode = 'ThvGQXDMLClSSEyI6BfGZ431VetmE45oszUPQQNUQSW1ozUdu8WJQBwfyBjk4opo'\n\neve_wrap = eve.EVE()\nid_responce = eve_wrap.character_id_from_name(character)\nchar_id = id_responce.result\nchar_api = api.API(api_key=(key,vcode))\n\nchar = char.Char(char_id=char_id, api=char_api)\nkm = char.kills()\nprint(km)\n'''\n\nimport json\ndef log_to_json(data, file='log_to_json'):\n '''Takes python list/dict and makes json file'''\n with open(file + '.json', 'w') as outfile:\n json.dump(data, outfile)\n\n\ncharacter = 'Py Solette'\nkey = 4414604\nvcode = 'ThvGQXDMLClSSEyI6BfGZ431VetmE45oszUPQQNUQSW1ozUdu8WJQBwfyBjk4opo'\n\n\nimport evelink.api # Raw API access\nimport evelink.char # Wrapped API access for the /char/ API path\nimport evelink.eve # Wrapped API access for the /eve/ API path\n\neve_wrap = evelink.eve.EVE()\n\n\n# Using authenticated calls\napi = evelink.api.API(api_key=(key, vcode))\nid_response = eve_wrap.character_id_from_name(character)\nchar = evelink.char.Char(char_id=id_response.result, api=api)\nbalance_response = char.kills()\nlog_to_json(balance_response.result)\n\n","sub_path":"for_eve/fetch_kills.py","file_name":"fetch_kills.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"129397745","text":"import numpy as np\nimport argparse\nimport pulp as pl\nclass MDP:\n def __init__(self, states, actions):\n self.S = states\n self.A = actions\n self.STR = [[[] for a in range(actions)] for s in range(states)]\n self.TR = np.zeros((states, actions), dtype=float)\n self.isNonTerminal = np.ones((states, actions), dtype=bool)\n self.gamma = 1.0\n \n def computeTerminal(self):\n for s in range(self.S):\n for a in range(self.A):\n if len(self.STR[s][a]) == 0:\n self.isNonTerminal[s, a] = False\n continue\n if self.STR[s][a][0][0] == s and self.STR[s][a][0][1] == 1.0 and self.STR[s][a][0][2] == 0.0:\n self.isNonTerminal[s, a] = False\n\ndef constructMDP(path):\n f = open(path, 'r')\n S = int(f.readline().split()[1]) # number of states\n A = int(f.readline().split()[1]) # number of actions\n mdp = MDP(S, A)\n f.readline() # end\n\n line = f.readline().split()\n while line[0] == 'transition':\n a, b, c, d, e = int(line[1]), int(line[2]), int(line[3]), float(line[4]), float(line[5])\n mdp.STR[a][b].append((c, e, d))\n mdp.TR[a][b] += d * e\n line = f.readline().split()\n \n for s in range(S):\n for a in range(A):\n mdp.STR[s][a].sort()\n \n mdp.computeTerminal()\n \n mdp.gamma = float(f.readline().split()[1]) # value of gamma\n\n f.close()\n return mdp\n\ndef value_eval(mdp, P):\n P = P.astype(int)\n isNonTerminal = mdp.isNonTerminal[np.arange(mdp.S), P]\n k = np.sum(isNonTerminal)\n \n T1 = np.zeros((mdp.S,mdp.S))\n for i in range(mdp.S):\n if not isNonTerminal[i]:\n continue\n for t in mdp.STR[i][P[i]]:\n s2 = t[0]\n if not isNonTerminal[s2]:\n continue\n T1[i, s2] = t[1]\n T1 = T1[:, isNonTerminal]\n T1 = T1[isNonTerminal, :]\n\n U = mdp.TR[np.arange(mdp.S), P]\n U = U[isNonTerminal]\n\n A = np.eye(k) - mdp.gamma * T1\n\n V = np.zeros(mdp.S)\n V[isNonTerminal] = np.linalg.solve(A, U)\n\n return V\n\ndef calcQ(mdp, s, a, V):\n Q = 0\n for t in mdp.STR[s][a]:\n Q += t[1] * V[t[0]]\n Q = mdp.TR[s,a] + mdp.gamma * Q\n return Q\n\ndef optPolicy(mdp, V):\n P = np.zeros(mdp.S, dtype=int)\n for s in range(mdp.S):\n Qs = [calcQ(mdp, s, a, V) if len(mdp.STR[s][a]) > 0 else -np.inf for a in range(mdp.A)]\n P[s] = np.argmax(Qs)\n return P\n\ndef valueIter(mdp):\n V = np.zeros(mdp.S)\n V_old = np.zeros(mdp.S)\n while True:\n for s in range(mdp.S):\n Qs = [calcQ(mdp, s, a, V_old) for a in range(mdp.A) if len(mdp.STR[s][a]) > 0]\n V[s] = np.max(Qs) if len(Qs) > 0 else 0.0\n if np.allclose(V, V_old, rtol=0, atol=1e-9):\n break\n V_old = V.copy()\n return V, optPolicy(mdp, V)\n\ndef HowardPI(mdp):\n P = np.zeros(mdp.S, dtype=int)\n for s in range(mdp.S):\n for a in range(mdp.A):\n if len(mdp.STR[s][a]) == 0:\n continue\n P[s] = a\n break\n V = np.zeros(mdp.S)\n optFound = False\n\n while not optFound:\n optFound = True\n V = value_eval(mdp, P)\n\n for s in range(mdp.S):\n if not mdp.isNonTerminal[s, P[s]]:\n continue\n for a in range(mdp.A):\n if a == P[s]:\n continue\n\n if calcQ(mdp, s, a, V) > V[s]:\n P[s] = a\n optFound = False\n break\n return V, P\n\ndef linearProgramming(mdp):\n isNonTerminal = np.any(mdp.isNonTerminal, axis=1)\n\n Vs = [pl.LpVariable('V' + str(i)) for i in range(mdp.S)]\n prob = pl.LpProblem(\"MDPPlanning\", pl.LpMinimize)\n for s in range(mdp.S):\n for a in range(mdp.A):\n prob += Vs[s] >= pl.lpSum([t[1] * (t[2] + mdp.gamma*Vs[t[0]]) for t in mdp.STR[s][a]])\n if not isNonTerminal[s]:\n prob += Vs[s] == 0\n prob += pl.lpSum(Vs)\n\n prob.solve(pl.PULP_CBC_CMD(msg=0))\n return np.array([v.value() for v in Vs]), optPolicy(mdp, np.array([v.value() for v in Vs]))\n\ndef main_function(mdp_path, alg):\n mdp = constructMDP(mdp_path)\n\n V = P = np.zeros(mdp.S)\n\n if alg == 'vi':\n V, P = valueIter(mdp)\n elif alg == 'hpi':\n V, P = HowardPI(mdp)\n elif alg == 'lp':\n V, P = linearProgramming(mdp)\n \n return V, P\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--mdp', type=str, required=True)\n parser.add_argument('--algorithm', type=str, default='lp')\n\n args = parser.parse_args()\n \n V, P = main_function(args.mdp, args.algorithm)\n print('\\n'.join(['%.6f %s'%(V[i], P[i]) for i in range(len(V))]))\n","sub_path":"Assignments/Assn2/submission/planner.py","file_name":"planner.py","file_ext":"py","file_size_in_byte":4821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"460802934","text":"import sys\nimport os\nimport pickle\nimport importlib\nfrom typing import Union, List\n\nfrom markov_pilot.environment.environment import JsbSimEnv_multi, NoFGJsbSimEnv_multi\nfrom markov_pilot.agents.agent_container import AgentContainer\nfrom markov_pilot.helper.lab_journal import LabJournal\n\n#these imports are needed to restore all the classes from the saved pickle-files\nfrom markov_pilot.tasks.tasks import SingleChannel_FlightTask, SingleChannel_MinimumProps_Task\nfrom markov_pilot.wrappers.episodePlotterWrapper import EpisodePlotterWrapper_multi\n\n\n\ndef save_test_run(env: JsbSimEnv_multi, agent_container: AgentContainer, lab_journal: LabJournal, arglist):\n \"\"\"\n - creates a suitable directory for the test run\n - adds a sidecar file containing the meta information on the run (dict saved as pickle)\n - adds a text file containing the meta information on the run\n - add a line to the global csv-file for the test run\n \"\"\"\n # IMPORTANT to do this first, to make the lab_journal aware of the start time of the run\n lab_journal.set_run_start()\n\n task_names = '_'.join([t.name for t in env.task_list])\n date = lab_journal.run_start.strftime(\"%Y_%m_%d\")\n time = lab_journal.run_start.strftime(\"%H-%M\")\n\n #build the path name for the run protocol\n save_path = os.path.join(lab_journal.journal_save_dir, env.aircraft.name, arglist.exp_name, task_names, date+'-'+time)\n\n #create the base directory for this test_run\n os.makedirs(os.path.dirname(save_path), exist_ok=True)\n #create the directories for each agent_task\n for a in agent_container.agents_m:\n agent_path = os.path.join(save_path, a.name)\n os.makedirs(os.path.join(save_path, a.name), exist_ok=True)\n a.set_save_path(agent_path)\n\n env.save_env_data(arglist, save_path)\n agent_container.save_agent_container_data(save_path)\n #eventually append the run data to the csv-file. \n csv_line_nr = lab_journal.append_run_data(env, agent_container.agents_m, save_path)\n env.set_meta_information(csv_line_nr = csv_line_nr)\n\ndef restore_env_from_journal(lab_journal, line_numbers: Union[int, List[int]], target_environment = None) -> NoFGJsbSimEnv_multi:\n ENV_PICKLE = 'environment_init.pickle' #these are hard default names for the files\n TASKS_PICKLE ='task_agent.pickle' #these are hard default names for the files\n\n ln = line_numbers if isinstance(line_numbers, int) else line_numbers[0]\n\n #get run protocol\n try:\n model_file = lab_journal.get_model_filename(ln)\n run_protocol_path = lab_journal.find_associated_run_path(model_file)\n except TypeError:\n print(f\"there was no run protocol found that is associated with line_number {ln}\")\n exit()\n\n if run_protocol_path == None:\n print(f\"there was no run protocol found that is associated with line_number {ln}\")\n exit()\n\n #load the TASKS_PICKLE and restore the task_list\n with open(os.path.join(run_protocol_path, TASKS_PICKLE), 'rb') as infile:\n task_agent_data = pickle.load(infile)\n \n task_agents = []\n for idx in range(len(task_agent_data['task_list_class_names'])):\n task_list_init = task_agent_data['task_list_init'][idx]\n task_list_class_name = task_agent_data['task_list_class_names'][idx]\n make_base_reward_components_file = task_agent_data['make_base_reward_components_file'][idx]\n make_base_reward_components_fn = task_agent_data['make_base_reward_components_fn'][idx]\n\n #load the make_base_reward_components function from a python-file\n #load function from given filepath https://stackoverflow.com/a/67692/2682209\n spec = importlib.util.spec_from_file_location(\"make_base_rwd\", os.path.join(run_protocol_path, make_base_reward_components_file))\n func_module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(func_module)\n make_base_reward_components = getattr(func_module, make_base_reward_components_fn)\n\n #get the class for the task_agent https://stackoverflow.com/a/17960039/2682209\n class_ = getattr(sys.modules[__name__], task_list_class_name)\n #add the make_base_reward_components function to the parameter dict\n task_list_init.update({'make_base_reward_components': make_base_reward_components})\n #transform the setpoint_props and setpoint_values lists to setpoints dict\n task_list_init.update({'setpoints': dict(zip(task_list_init['setpoint_props'], task_list_init['setpoint_values']))})\n del task_list_init['setpoint_props']\n del task_list_init['setpoint_values']\n ta = class_(**task_list_init)\n task_agents.append(ta)\n\n #the task_agents are now ready, so now let's prepare the environment\n #load the ENV_PICKLE and restore the task_list\n with open(os.path.join(run_protocol_path, ENV_PICKLE), 'rb') as infile:\n env_data = pickle.load(infile)\n\n env_init_dicts = env_data['init_dicts']\n env_classes = env_data['env_classes']\n\n #create the innermost environment with the task_list added\n #load the env class\n env_class_ = getattr(sys.modules[__name__], env_classes[0])\n\n if target_environment and (env_class_ == JsbSimEnv_multi or env_class_ == NoFGJsbSimEnv_multi):\n #the user wants us to exchange the innermost environment\n if target_environment == 'NoFG':\n env_class_ = NoFGJsbSimEnv_multi\n elif target_environment == 'FG':\n env_class_ = JsbSimEnv_multi\n else:\n raise ValueError(\"parameter target_:environment must be either 'NoFG' or 'FG' or entirely omitted. Other values not allowed.\")\n\n env_init = env_init_dicts[0]\n env_init.update({'task_list':task_agents})\n\n env = env_class_(**env_init)\n \n #apply wrappers if available\n #TODO: what about other wrappers than EpisodePlotterWrapper? We don't save the VarySetpointWrapper to the wrappers list.\n for idx in range(1, len(env_init_dicts)):\n wrapper_class_ = getattr(sys.modules[__name__], env_classes[idx])\n wrap_init = env_init_dicts[idx]\n wrap_init.update({'env': env})\n env = wrapper_class_(**wrap_init)\n \n env.set_meta_information(csv_line_nr = ln) #set the line number, the environment was loaded from\n return env\n\ndef restore_agent_container_from_journal(lab_journal, line_numbers: Union[int, List[int]], task_list_n = None, mapping_dict = None) -> 'AgentContainer':\n CONTAINER_PICKLE = 'agent_container.pickle'\n\n ln = [line_numbers] if isinstance(line_numbers, int) else line_numbers\n\n #get run protocol\n\n agent_pickle_files_m = [lab_journal.get_model_filename(line) for line in ln]\n try:\n model_file = lab_journal.get_model_filename(ln[0])\n run_protocol_path = lab_journal.find_associated_run_path(model_file)\n except TypeError:\n print(f\"there was no run protocol found that is associated with line_number {ln}\")\n exit()\n\n agent_container = AgentContainer.init_from_save(os.path.join(run_protocol_path, CONTAINER_PICKLE), agent_pickle_files_m, task_list_n, mapping_dict)\n\n return agent_container\n","sub_path":"markov_pilot/helper/load_store.py","file_name":"load_store.py","file_ext":"py","file_size_in_byte":7115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"395575760","text":"class Solution:\n def reverseWords(self, s: str) -> str:\n if len(s)<=0:\n return s\n items = s.split(\" \")\n print(items)\n res_items = []\n for item in items:\n print(type(item))\n item = item[::-1]\n res_items.append(item)\n res = \"\"\n for i,each in enumerate(res_items):\n res +=each\n if i!=len(res_items)-1:\n res +=\" \"\n return res\n","sub_path":"src/字符串操作/q557_反转字符串中的单词III/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"163508850","text":"import botbook_mcp3002 as mcp # for botbook_mcp3002 module import\n\t\t\t\t\t\t\t # read gas sence\nimport time\t# for using time.sleep()\n\nimport RPi.GPIO as GPIO # for using GPIO port\nfrom sys import exit \t# for exception processing\nimport pygame.mixer # for warning sound\n\nGPIO.setmode(GPIO.BCM) # set GPIO port as GPIO.BCM\nGPIO.setup(17,GPIO.OUT) # moving motor\nGPIO.setup(21,GPIO.IN) # button input\n\n# motor initialize\nmotor = GPIO.PWM(17,50) \nmotor.start(7.5) \n\n# sound initialize\npygame.mixer.init(48000,-16,1,1024) \nwarningSound = pygame.mixer.Sound(\"/home/pi/warning.wav\") \nsoundChannelA = pygame.mixer.Channel(1) \n\ntickSound = pygame.mixer.Sound(\"/home/pi/tick.wav\")\nsoundChannelB = pygame.mixer.Channel(2)\n\n# read Gas Function\ndef readPotent():\n\n\tglobal gasValue \n\tgasValue = mcp.readAnalog() # read gas information from mcp-3002 \n\n#m main Function\ndef main(): \n\n\tisGas = 0\n\tcount = 0\n\tflag = 0\n\ttickCount = 0\n\n\tprint(\" start program \")\n\n\ttry:\n\t\twhile True: # while Loop\n\t\t\treadPotent() # read Gas Funtion Call\n\t\t\tisButton = GPIO.input(21) # read button\n\t\t\t\n\t\t\t# burning the gas\n\t\t\t# for 10, call tickSound\n\t\t\tif (tickCount < 10): \n\t\t\t\ttickCount = tickCount + 1\n\t\t\t\tsoundChannelB.play(tickSound)\n\n\t\t\tif (gasValue > 600):\t# gas on\n\t\t\t\tisGas = 1\n\t\t\t\tprint(\" Gas !!! \")\n\t\t\t\tprint(\"The current potentiometer value is %i \" % gasValue) # \n\t\t\t\n\t\t\tif (isGas == 1): # gas count time per 0.5 sec\n\t\t\t\tcount = count + 1\n\t\t\t\tsoundChannelA.play(warningSound) # warning sound call\n\t\t\t\n\t\t\ttime.sleep(0.5) # program timer per 0.5 sec\n\t\t\n\t\t\tif( count == 10 ): # time 0.5 * 10 = 5sec , motor on.\n\t\t\t\tmotor.ChangeDutyCycle(12.5) \n\n\t\t\tif( isButton == 1 ): # button on\n\t\t\t\tisGas = 0\n\t\t\t\tcount = 0\n\t\t\t\ttickCount = 0\n\t\t\t\tmotor.ChangeDutyCycle(7.5) # motor off.\n\n\texcept KeyboardInterrupt:\n\t\tGPIO.cleanup()\nif (__name__ == \"__main__\"): #main Function Start\n\tmain()\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"178278399","text":"from math import *\r\n\r\npeople = int(input(\"How many people are sharing the bill?\\n\"))\r\nbill = float(input(\"How much is the bill?\\n\"))\r\nprint(\"Kevin paid the bill first. But Kevin only has 100 dollar notes\")\r\nprint(\"So Kevin is going to paid $%d.00.\" %(100*ceil(bill/100.0))) \r\nprint(\"The cafe is giving %.2f to Kevin.\" %(100-(bill%100))) \r\nprint(\"Each one should give %.2f to Kevin.\" %(bill/people))\r\n\r\nnumber = int(1)\r\nwhile (number <= 100):\r\n if (number%7==0 or number%10==7):\r\n print('X', end= ' ')\r\n else:\r\n print(number, end= ' ') \r\n number = number + 1\r\nprint(\"\\nGame Over.\")\r\n\r\n\r\nfrom random import randint\r\n\r\nnumber = randint(1,6)\r\nprint(\"I got a %d\" % number)\r\ncount = 1\r\nwhile number != 6 : \r\n number=randint(1,6)\r\n print(\"I got a %d\" % number)\r\n count = count + 1\r\n\r\nprint(\"Oh, it takes me %d times to get a 6!!!\" % count)\r\n\r\ncount=0\r\nfor time in range(0,100):\r\n number = randint(1,6)\r\n count = count+1\r\n while number != 6 : \r\n number=randint(1,6)\r\n count = count + 1\r\nprint('Average time taken is %.2f times.'%(count/100.0))\r\n\r\ninput()\r\n","sub_path":"L3/LawCheukHim_L3Q1.py","file_name":"LawCheukHim_L3Q1.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"492071247","text":"# Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nfrom ..objects.exceptions import ValidationError\nfrom ..core import fileoperations\n\n\ndef get_dockerrun(dockerrun_path):\n \"\"\"\n Return dict representation of Dockerrun.aws.json in dockerrun_path\n Return None if Dockerrun doesn't exist at that path.\n :param dockerrun_path: str: full path to Dockerrun.aws.json\n :return: dict\n \"\"\"\n\n try:\n return fileoperations.get_json_dict(dockerrun_path)\n except ValueError:\n err_msg = 'You provided an invalid Dockerrun.aws.json file. ' \\\n 'Reason was: {}'\n raise ValidationError(err_msg.format('Invalid JSON format.'))\n except IOError: # Dockerrun.aws.json doesn't exist\n return None\n","sub_path":"lib/python2.7/site-packages/ebcli/docker/dockerrun.py","file_name":"dockerrun.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"252718944","text":"import re\nres = {}\ni =0\nwith open(\"..\\exam-schedule.csv\") as file:\n for line in file:\n if i==0:\n i=1\n continue\n lArr = line.split(\",\")\n cThing = lArr[len(lArr)-2] + \" | \" + lArr[3] + \" | \" + lArr[5]\n if cThing in res:\n res[cThing] +=1\n # print(cThing)\n else:\n res[cThing] =1\n\n\n\nfor student in dict(sorted(res.items(),key=lambda item: item[1],reverse=True)):\n if res[student] == 1:\n continue\n line = student.split(\"|\")\n print(f\"{line[0]}has {res[student]} exams on{line[1]}({line[2]})\")\n ","sub_path":"05-modules/data-formats/exam-schedule/overlapping-exams/overlap.py","file_name":"overlap.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"381789295","text":"from tkinter.scrolledtext import ScrolledText\nfrom threading import Thread\nimport tkinter as tk\nfrom src.constant import *\nfrom src.solution.sentiment import SentimentAnalysisTool, SentimentAnalysis\nfrom src.utils.browser import WebBrowser\n\n\nclass Page2(tk.Frame):\n isInitialized = False\n\n def __init__(self, parent, customers, couriers, controller, name):\n tk.Frame.__init__(self, parent, bg=lightBlue)\n print(f\"{name} Frame initialized\")\n\n self.webBrowser = WebBrowser\n self.customers = customers\n self.couriers = couriers\n self.controller = controller\n self.name = name\n\n self.wordFreqDisplay = ScrolledText\n self.status = tk.Label\n self.sentimentDescription = tk.Label\n self.hasAnalyzed = False\n self.scrapingText = tk.StringVar(self, \" Random Scraping\")\n\n self.tool = SentimentAnalysisTool(self.couriers)\n\n self.currentResult = SentimentAnalysis()\n self.T1 = Thread\n self.T2 = Thread\n\n self.showArticle()\n self.showStatistic()\n\n def showArticle(self):\n browserFrame = tk.Frame(self, bg='blue', width=810, height=500)\n browserFrame.grid(row=0, column=0)\n\n initialUrl = \"https://www.google.com/\"\n browserSetting = {}\n self.webBrowser = WebBrowser(browserFrame, browserSetting, initialUrl, \"Search For Article\")\n self.webBrowser.start()\n\n mining = getIconImage(\"mining\")\n scraping = tk.Button(browserFrame, textvariable=self.scrapingText, image=mining, compound=\"left\",\n width=190, command=self.__randomScraping, **buttonConfig2)\n scraping.image = mining\n scraping.place(x=3, y=5)\n\n frame = tk.Frame(self, bg=lightPurple, width=800, height=200)\n frame.grid(row=1, column=0, sticky=\"w\")\n\n linkSelected = tk.StringVar(frame, \"https://www.google.com/\")\n dropDownMenu = tk.OptionMenu(frame, linkSelected, *(self.__getSampleLinks()))\n dropDownMenu.config(width=80, anchor=\"w\", **dropDownConfig)\n dropDownMenu.grid(row=0, column=0, sticky=\"w\")\n linkSelected.trace(mode=\"w\", callback=lambda *args: self.__search(linkSelected.get()))\n\n tk.Button(frame, text=\"Analyze Page\", command=self.__startSentiment, **buttonConfig3).grid(row=0, column=1)\n tk.Label(frame, text=\" STATUS \", background=lightPurple, font=buttonFontN).grid(row=0, column=2, sticky='ns')\n\n self.status = tk.Label(frame, text=\"Not yet analyze\", width=15, background=\"#BFC7E4\", font=buttonFontN)\n self.status.grid(row=0, column=3, sticky='ns')\n\n def showStatistic(self):\n frame = tk.Frame(self, bg=lightBlue)\n frame.grid(row=2, column=0, sticky=\"w\")\n\n self.wordFreqDisplay = ScrolledText(frame, width=30, height=5, wrap=tk.WORD, bg=lightBlue)\n self.wordFreqDisplay.grid(row=0, column=0, pady=7, padx=10, rowspan=2)\n self.wordFreqDisplay.insert(tk.INSERT, \"No Word Frequency Found\")\n\n wordFreqButton = tk.Button(frame, text=\"Word Frequency\", command=lambda: self.__showGraph(0))\n wordFreqButton.config(width=17, height=2)\n wordFreqButton.grid(row=0, column=1, padx=1, pady=7)\n\n positveButton = tk.Button(frame, text=\"Positive Sentiment\", command=lambda: self.__showGraph(1))\n positveButton.config(width=17, height=2)\n positveButton.grid(row=0, column=2, padx=1, pady=7)\n\n negativeButton = tk.Button(frame, text=\"Negative Sentiment\", command=lambda: self.__showGraph(2))\n negativeButton.config(width=17, height=2)\n negativeButton.grid(row=0, column=3, padx=1, pady=7)\n\n neutralButton = tk.Button(frame, text=\"Neutral Sentiment\", command=lambda: self.__showGraph(3))\n neutralButton.config(width=17, height=2)\n neutralButton.grid(row=0, column=4, padx=1, pady=7)\n\n self.sentimentDescription = tk.Label(frame, text=\"No sentiment analysis yet\", borderwidth=3, relief=\"groove\")\n self.sentimentDescription.config(anchor=\"w\", padx=10, foreground=\"green\", font=subFontN)\n self.sentimentDescription.grid(row=1, column=1, sticky=\"swe\", columnspan=4, padx=1, pady=7)\n\n def __randomScraping(self):\n if self.scrapingText.get().strip() == \"Analyzing\":\n return\n\n thread = Thread(target=self.__randomAnalysis)\n thread.isDaemon = True\n thread.start()\n\n def __randomAnalysis(self):\n self.scrapingText.set(\"{:^25}\".format(\"Analyzing\"))\n\n queries = [\n (\"city-link\", \"city-link express news\"),\n (\"pos laju\", \"pos laju news\"),\n (\"gdex\", \"gdex express news\"),\n (\"j&t\", \"j&t express news\"),\n (\"dhl\", \"dhl express news\"),\n ]\n\n for q in queries:\n self.tool.randomSentiment(q, n=10)\n\n print(\"DONE\")\n self.scrapingText.set(\" Random Scraping\")\n\n def __startSentiment(self):\n status = self.status['text']\n if status == \"Showing Graph\" or status == \"Analyzing Page\":\n return\n elif status == \"Has been analyzed\":\n self.currentResult = self.tool.history[self.webBrowser.getUrl()]\n self.__update()\n else:\n self.T1 = Thread(target=self.__getStatus)\n self.T2 = Thread(target=self.__getSentiment)\n\n self.T1.start()\n self.T2.start()\n\n def __getStatus(self):\n self.status.config(text=\"Analyzing Page\")\n self.T2.join()\n self.status.config(text=\"Finished Analyzed\")\n self.__update()\n\n def __update(self):\n self.wordFreqDisplay.delete(\"1.0\", \"end\")\n self.wordFreqDisplay.insert(tk.INSERT, self.__printFreq())\n self.sentimentDescription['text'] = self.currentResult.sentimentDescription\n\n def __getSentiment(self):\n url = self.webBrowser.getUrl()\n self.currentResult = self.tool.getSentiment(url)\n\n def __getSampleLinks(self):\n with open(f\"{sentiment}/link.txt\", mode=\"r\") as file:\n links = [link.strip() for link in file.readlines()]\n return links\n\n def __search(self, url):\n if url in self.tool.getUrls():\n self.status.config(text=\"Has been analyzed\")\n elif url[:4] == \"file\":\n self.status.config(text=\"Showing Graph\")\n else:\n self.status.config(text=\"Not yet analyze\")\n self.webBrowser.loadUrl(url)\n\n def __printFreq(self):\n result = self.currentResult.sortedDict\n output = \"\"\n if result:\n for word, freq in result.items():\n output += f\"{word}, {freq}\\n\"\n else:\n output = \"No Word Frequency Found\"\n return output\n\n def __showGraph(self, mode=0):\n if self.sentimentDescription['text'] == \"Current Page could not be analyzed\":\n return None\n\n # 0 = wordFreq, 1 = positive, 2 = negative, 3 = neutral\n if mode == 0:\n fname = \"wordFreq\"\n self.currentResult.plotWordFrequency()\n elif mode == 1:\n fname = \"positive\"\n self.currentResult.plotSentimentGraph(model=\"positive\")\n elif mode == 2:\n fname = \"negative\"\n self.currentResult.plotSentimentGraph(model=\"negative\")\n elif mode == 3:\n fname = \"neutral\"\n self.currentResult.plotSentimentGraph(model=\"neutral\")\n else:\n print(\"Invalid mode\")\n return None\n\n self.__search(url=f\"file:///{sentiment}/figures/{fname}_graph.html\")\n","sub_path":"src/ui_pages/page_2.py","file_name":"page_2.py","file_ext":"py","file_size_in_byte":7517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"56989129","text":"\nimport time\nimport sys\nimport pytz\nimport logging\nimport datetime\nimport itertools\nfrom urllib.parse import urlparse\nimport matplotlib.pyplot as plt\n\nfrom opcua import ua, Client\n\n\nclass OpcUaClient(object):\n CONNECT_TIMEOUT = 15 # [sec]\n RETRY_DELAY = 10 # [sec]\n MAX_RETRIES = 3 # [-]\n\n class Decorators(object):\n @staticmethod\n def autoConnectingClient(wrappedMethod):\n def wrapper(obj, *args, **kwargs):\n for retry in range(OpcUaClient.MAX_RETRIES):\n try:\n return wrappedMethod(obj, *args, **kwargs)\n except ua.uaerrors.BadNoMatch:\n raise\n except Exception:\n pass\n try:\n obj._logger.warn('(Re)connecting to OPC-UA service.')\n obj.reconnect()\n except ConnectionRefusedError:\n obj._logger.warn(\n 'Connection refused. Retry in 10s.'.format(\n OpcUaClient.RETRY_DELAY\n )\n )\n time.sleep(OpcUaClient.RETRY_DELAY)\n else: # So the exception is exposed.\n obj.reconnect()\n return wrappedMethod(obj, *args, **kwargs)\n return wrapper\n\n def __init__(self, serverUrl):\n self._logger = logging.getLogger(self.__class__.__name__)\n self._client = Client(\n serverUrl.geturl(),\n timeout=self.CONNECT_TIMEOUT\n )\n\n def __enter__(self):\n self.connect()\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.disconnect()\n self._client = None\n\n @property\n @Decorators.autoConnectingClient\n def sensorList(self):\n return self.objectsNode.get_children()\n\n @property\n @Decorators.autoConnectingClient\n def objectsNode(self):\n path = [ua.QualifiedName(name='Objects', namespaceidx=0)]\n return self._client.get_root_node().get_child(path)\n\n def connect(self):\n self._client.connect()\n self._client.load_type_definitions()\n\n def disconnect(self):\n try:\n self._client.disconnect()\n except Exception:\n pass\n\n def reconnect(self):\n self.disconnect()\n self.connect()\n\n @Decorators.autoConnectingClient\n def get_browse_name(self, uaNode):\n return uaNode.get_browse_name()\n\n @Decorators.autoConnectingClient\n def get_node_class(self, uaNode):\n return uaNode.get_node_class()\n\n @Decorators.autoConnectingClient\n def get_namespace_index(self, uri):\n return self._client.get_namespace_index(uri)\n\n @Decorators.autoConnectingClient\n def get_child(self, uaNode, path):\n return uaNode.get_child(path)\n\n @Decorators.autoConnectingClient\n def read_raw_history(self,\n uaNode,\n starttime=None,\n endtime=None,\n numvalues=0,\n cont=None):\n details = ua.ReadRawModifiedDetails()\n details.IsReadModified = False\n details.StartTime = starttime or ua.get_win_epoch()\n details.EndTime = endtime or ua.get_win_epoch()\n details.NumValuesPerNode = numvalues\n details.ReturnBounds = True\n result = OpcUaClient._history_read(uaNode, details, cont)\n assert(result.StatusCode.is_good())\n return result.HistoryData.DataValues, result.ContinuationPoint\n\n @staticmethod\n def _history_read(uaNode, details, cont):\n valueid = ua.HistoryReadValueId()\n valueid.NodeId = uaNode.nodeid\n valueid.IndexRange = ''\n valueid.ContinuationPoint = cont\n\n params = ua.HistoryReadParameters()\n params.HistoryReadDetails = details\n params.TimestampsToReturn = ua.TimestampsToReturn.Both\n params.ReleaseContinuationPoints = False\n params.NodesToRead.append(valueid)\n result = uaNode.server.history_read(params)[0]\n return result\n\n\nclass DataAcquisition(object):\n LOGGER = logging.getLogger('DataAcquisition')\n AXES = ('x', 'y', 'z')\n ORDINATES = ('accel', 'veloc')\n DOMAINS = ('time', 'freq')\n MAX_VALUES_PER_ENDNODE = 100 # Num values per endnode\n MAX_VALUES_PER_REQUEST = 2 # Num values per history request\n\n @staticmethod\n def selected_to_workbook(serverUrl,\n macIdsToCollect,\n starttime,\n endtime):\n with OpcUaClient(serverUrl) as client:\n for sensorNode in client.sensorList:\n assert(client._client.uaclient._uasocket.timeout == 15)\n macId = client.get_browse_name(sensorNode).Name\n if macId not in macIdsToCollect:\n DataAcquisition.LOGGER.info(\n 'Skipping sensor {:s}'.format(macId)\n )\n continue\n tagPath = ua.QualifiedName(\n 'deviceTag',\n sensorNode.nodeid.NamespaceIndex\n )\n DataAcquisition.LOGGER.info(\n 'Processing sensor {:s} ({:s})'.format(\n macId,\n client.get_child(sensorNode, tagPath).get_value()\n )\n )\n DataAcquisition.get_sensor_data(\n client,\n sensorNode,\n starttime,\n endtime\n )\n\n @staticmethod\n def get_sensor_data(serverUrl, macId, browseName, starttime, endtime):\n allValues = []\n allDates = []\n with OpcUaClient(serverUrl) as client:\n assert(client._client.uaclient._uasocket.timeout == 15)\n sensorNode = DataAcquisition.get_sensor_node(\n client,\n macId,\n browseName\n )\n for path in DataAcquisition.endnodes_path_generator(sensorNode):\n DataAcquisition.LOGGER.info(\n 'Browsing {:s} -> {:s}'.format(\n macId,\n sensorNode.get_browse_name().Name\n )\n )\n endNode = client.get_child(sensorNode, path)\n (values, dates) = DataAcquisition.get_endnode_data(\n client,\n endNode,\n starttime,\n endtime\n )\n allValues.extend(values)\n allDates.extend(dates)\n return (allValues, allDates)\n\n @staticmethod\n def endnodes_path_generator(sensorNode):\n for (axis, ordinate, domain) in \\\n itertools.product(DataAcquisition.AXES,\n DataAcquisition.ORDINATES,\n DataAcquisition.DOMAINS):\n # browseName: e.g. xAccelTime\n browseName = ''.join([\n axis, ordinate.capitalize(), domain.capitalize()\n ])\n nsIdx = sensorNode.nodeid.NamespaceIndex # iQunet namespace index\n path = [\n ua.QualifiedName(axis, nsIdx), # e.g. 'x'\n ua.QualifiedName(ordinate, nsIdx), # e.g. 'accel'\n ua.QualifiedName(browseName, nsIdx), # e.g. 'xAccelTime'\n ]\n yield path\n\n @staticmethod\n def get_sensor_node(client, macId, browseName):\n nsIdx = client.get_namespace_index(\n 'http://www.iqunet.com'\n ) # iQunet namespace index\n bpath = [\n ua.QualifiedName(name=macId, namespaceidx=nsIdx),\n ua.QualifiedName(name=browseName, namespaceidx=nsIdx)\n ]\n sensorNode = client.objectsNode.get_child(bpath)\n return sensorNode\n\n @staticmethod\n def get_endnode_data(client, endNode, starttime, endtime):\n dvList = DataAcquisition.download_endnode(\n client,\n endNode,\n starttime,\n endtime\n )\n dates, values = ([], [])\n for dv in dvList:\n dates.append(dv.SourceTimestamp.strftime('%Y-%m-%d %H:%M:%S'))\n values.append(dv.Value.Value.y_ordinate)\n\n # If no starttime is given, results of read_raw_history are reversed.\n if starttime is None:\n values.reverse()\n dates.reverse()\n return (values, dates)\n\n @staticmethod\n def download_endnode(client, endNode, starttime, endtime):\n endNodeName = client.get_browse_name(endNode).Name\n DataAcquisition.LOGGER.info(\n 'Downloading endnode {:s}'.format(\n endNodeName\n )\n )\n dvList, contId = [], None\n while True:\n remaining = DataAcquisition.MAX_VALUES_PER_ENDNODE - len(dvList)\n assert(remaining >= 0)\n numvalues = min(DataAcquisition.MAX_VALUES_PER_REQUEST, remaining)\n partial, contId = client.read_raw_history(\n uaNode=endNode,\n starttime=starttime,\n endtime=endtime,\n numvalues=numvalues,\n cont=contId\n )\n if not len(partial):\n DataAcquisition.LOGGER.warn(\n 'No data was returned for {:s}'.format(endNodeName)\n )\n break\n dvList.extend(partial)\n sys.stdout.write('\\r Loaded {:d} values, {:s} -> {:s}'.format(\n len(dvList),\n str(dvList[0].ServerTimestamp.strftime(\"%Y-%m-%d %H:%M:%S\")),\n str(dvList[-1].ServerTimestamp.strftime(\"%Y-%m-%d %H:%M:%S\"))\n ))\n sys.stdout.flush()\n if contId is None:\n break # No more data.\n if len(dvList) >= DataAcquisition.MAX_VALUES_PER_ENDNODE:\n break # Too much data.\n sys.stdout.write('...OK.\\n')\n return dvList\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n logging.getLogger(\"opcua\").setLevel(logging.WARNING)\n\n # replace xx.xx.xx.xx with the IP address of your server\n serverIP = \"xx.xx.xx.xx\"\n serverUrl = urlparse('opc.tcp://{:s}:4840'.format(serverIP))\n\n # replace xx:xx:xx:xx with your sensors macId\n macId = 'xx:xx:xx:xx'\n\n starttime = pytz.utc.localize(\n datetime.datetime.strptime(\"2020-02-01 00:00:00\", '%Y-%m-%d %H:%M:%S')\n )\n endtime = pytz.utc.localize(\n datetime.datetime.strptime(\"2020-02-24 00:00:00\", '%Y-%m-%d %H:%M:%S')\n )\n\n # acquire history data\n (values, dates) = DataAcquisition.get_sensor_data(\n serverUrl=serverUrl,\n macId=macId,\n browseName=\"vibration\",\n starttime=starttime,\n endtime=endtime\n )\n\n # plot data\n for i in range(len(dates)):\n plt.figure()\n plt.plot(values[i])\n plt.title(str(dates[i]))\n","sub_path":"examples/OPCuaGetVibrationDataStruct.py","file_name":"OPCuaGetVibrationDataStruct.py","file_ext":"py","file_size_in_byte":11201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"300875946","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\nclass Solution(object):\n def trailingZeroes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n\n result = 0\n\n while n:\n m = n / 5\n result += m\n n = m\n\n return result\n","sub_path":"leetcode/172.py","file_name":"172.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"410781344","text":"#!/usr/bin/env python\n\"\"\"\nGiven a graph representing a schema and nodes to hit, this class does a poor\nman's travelling salesman solution.\n\"\"\"\n__author__ = \"Andrew J. Dolgert \"\n__revision__ = \"$Revision: 1.1 $\"\n\n# system modules\nfrom logging import getLogger\n\n# local modules\nfrom pyquerybuilder.qb.DotGraph import DotGraph\nfrom pyquerybuilder.qb.Graph import Graph\n\n_LOGGER = getLogger(\"ConstructQuery\")\n\n\nclass ConstructQuery(object):\n \"\"\"Given a graph representing a schema and nodes to hit, this class does \n a poor man's travelling salesman solution.\"\"\"\n def __init__(self, connectivity):\n \"\"\"Connectivity describes which tables have foreign keys\n into which other tables.\"\"\"\n graph = Graph(connectivity)\n undirected_graph = graph.get_undirected()\n self._spanning = []\n # traversing graph\n # get spanning path of BFS from this node\n # self._spannning stores those path\n for node_index in range(0, len(undirected_graph)):\n span = undirected_graph.breadth_first_search(node_index)\n self._spanning.append(span)\n\n def print_spans(self):\n \"\"\"print every spans in this spanning collection\"\"\"\n span_index = 0\n for span in self._spanning:\n dot = DotGraph(file(\"span%d.dot\" % (span_index),\"w\"))\n span.write_graph(dot)\n span_index = span_index+1\n\n def get_smallest_subtree(self, query_elements):\n '''Find the subtree containing the query elements.'''\n query_set = set(query_elements)\n min_len = len(self._spanning) + 1\n smallest_span = None\n span_index = 0\n for span in self._spanning:\n sub_span = span.subtree_including(query_set)\n if sub_span is not None:\n if sub_span.get_edges_number() < min_len:\n min_len = sub_span.get_edges_number()\n smallest_span = sub_span\n span_index = span_index + 1\n\n return smallest_span\n\n def get_statement_joins(self, query_elements):\n '''The argument is a list of which tables contain the desired\n elements. The return value is a list of joins between those tables.'''\n query_set = set(query_elements)\n\n edge_sets = []\n min_len = len(self._spanning)\n min_index = -1\n for node_index in range(0, len(self._spanning)): \n subs = self._spanning[node_index].get_edges_including(query_set)\n if len(subs) < min_len:\n min_len = len(subs)\n min_index = node_index\n edge_sets.append(subs)\n return (min_index, edge_sets[min_index])\n\n","sub_path":"pyquerybuilder/qb/ConstructQuery.py","file_name":"ConstructQuery.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"125059507","text":"# Default Imports\nfrom greyatomlib.pandas_project.q01_read_csv_data_to_df.build import read_csv_data_to_df\n\n# You have been give the dataset already in 'ipl_df'.\nipl_df = read_csv_data_to_df(\"./data/ipl_dataset.csv\")\n\n# Solution\nimport pandas as pd\n# Solution\ndef get_runs_counts_by_match():\n new_df = pd.DataFrame(columns=['match_code','0','1','2','3','4','5','6'])\n new_df['match_code']=ipl_df['match_code']\n new_df['0']=ipl_df['runs']==0\n new_df['1']=ipl_df['runs']==1\n new_df['2']=ipl_df['runs']==2\n new_df['3']=ipl_df['runs']==3\n new_df['4']=ipl_df['runs']==4\n new_df['5']=ipl_df['runs']==5\n new_df['6']=ipl_df['runs']==6\n pivot_df=new_df.pivot_table(['0','1','2','3','4','5','6'],index=['match_code'],aggfunc='sum')\n return pivot_df\n","sub_path":"q07_get_run_counts_by_match/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"133888595","text":"import numpy as np\nimport tensorflow as tf\n\n\ndef placeholder(dim=None):\n return tf.placeholder(dtype=tf.float32, shape=(None,dim) if dim else (None,))\n\ndef placeholders(*args):\n return [placeholder(dim) for dim in args]\n\ndef mlp(x, hidden_sizes=(32,), activation=tf.tanh, output_activation=None):\n for h in hidden_sizes[:-1]:\n x = tf.layers.dense(x, units=h, activation=activation)\n return tf.layers.dense(x, units=hidden_sizes[-1], activation=output_activation)\n\ndef q_mlp(x, hidden_sizes=(32,), activation=tf.tanh, output_activation=None):\n for h in hidden_sizes[:-1]:\n x = tf.layers.dense(x, units=h, activation=activation)\n q_mu = tf.layers.dense(x, units=hidden_sizes[-1], activation=output_activation)\n q_sigma = tf.layers.dense(x, units=hidden_sizes[-1], activation=tf.nn.relu)\n q_mu = tf.squeeze(q_mu, axis=1)\n q_sigma = tf.squeeze(q_sigma, axis=1)\n q_dist = tf.distributions.Normal(loc=q_mu, scale=q_sigma)\n q = q_dist.sample([1])\n import pdb;\n pdb.set_trace()\n return q\n\ndef a_mlp(x, hidden_sizes=(32,), activation=tf.nn.relu, output_activation=tf.tanh):\n for h in hidden_sizes[:-1]:\n x = tf.layers.dense(x, units=h, activation=activation)\n act_dim = hidden_sizes[-1]\n a_mu = tf.layers.dense(x, units=act_dim, activation=output_activation)\n a_sigma = tf.layers.dense(x, units=act_dim, activation=tf.sigmoid)\n conc_factor = 1\n a_dist = tf.distributions.Normal(a_mu, conc_factor*a_sigma)\n a = a_dist.sample([1])[0]\n a = tf.tanh(a)\n return a,a_mu,a_sigma\n\ndef sample_action(a_mu, a_alpha, a_beta, concen_factor=1):\n act_dim = len(a_mu)\n # Shift a_alpha to range [-10,0] so that exp(a_alpha) in [4e-5,1]\n a_alpha = (a_alpha-1)*5\n a_cov = np.zeros((act_dim, act_dim))\n beta_ind = 0\n for i in range(act_dim):\n a_cov[i,i] = np.exp(a_alpha[i])\n if i+1 < act_dim:\n for j in range(i+1, act_dim):\n tmp = np.exp((a_alpha[i]+a_alpha[j])/2) * a_beta[beta_ind]\n a_cov[i,j] = tmp\n a_cov[j,i] = tmp\n a_cov = concen_factor * a_cov\n return np.random.multivariate_normal(a_mu, a_cov, 1)[0], a_cov\n\ndef sample_action_op(a_mu, a_para, act_dim):\n # alpha and beta for information matrix: (act_dim * (act_dim+1)) / 2\n # a_alpha[0:act_dim] = alpha\n # a_alpha[act_dim:(act_dim * (act_dim+1)) / 2] = beta\n a_alpha = a_para[:, :act_dim]\n a_beta = a_para[:, act_dim:]\n a_info_matrix = np.zeros((a_para.shape[0], act_dim, act_dim))\n beta_ind = 0\n for i in range(act_dim):\n a_info_matrix[:, i, i] = tf.exp(a_alpha[:,i])\n if i+1 < act_dim:\n for j in range(i+1, act_dim):\n a_info_matrix[:, i, j] = tf.exp((a_alpha[:,i]+a_alpha[:,j])/2) * tf.tanh(a_beta[:, beta_ind])\n a_info_matrix[:, j, i] = tf.exp((a_alpha[:,i] + a_alpha[:,j]) / 2) * tf.tanh(a_beta[:, beta_ind])\n beta_ind += 1\n a_dist = tf.contrib.distributions.MultivariateNormalFullCovariance(a_mu, tf.linalg.inv(a_info_matrix))\n a = a_dist.sample([1])\n return a, a_info_matrix\n\ndef get_vars(scope):\n return [x for x in tf.global_variables() if scope in x.name]\n\ndef count_vars(scope):\n v = get_vars(scope)\n return sum([np.prod(var.shape.as_list()) for var in v])\n\n\"\"\"\nActor-Critics\n\"\"\"\ndef mlp_actor_critic(x, a_ph, hidden_sizes=(400,300), activation=tf.nn.relu,\n output_activation=tf.tanh, action_space=None):\n act_dim = a_ph.shape.as_list()[-1]\n act_limit = action_space.high[0]\n with tf.variable_scope('pi'):\n # pi = act_limit * mlp(x, list(hidden_sizes)+[act_dim], activation, output_activation)\n # import pdb; pdb.set_trace()\n pi, pi_mu, pi_sigma = a_mlp(x, list(hidden_sizes) + [act_dim], activation, output_activation)\n pi = act_limit * pi\n pi_mu = act_limit * pi_mu\n with tf.variable_scope('q'):\n q = tf.squeeze(mlp(tf.concat([x, a_ph], axis=-1), list(hidden_sizes)+[1], activation, None), axis=1)\n # q = q_mlp(tf.concat([x, a], axis=-1), list(hidden_sizes)+[1], activation, None)\n with tf.variable_scope('q', reuse=True):\n q_pi = tf.squeeze(mlp(tf.concat([x, pi], axis=-1), list(hidden_sizes)+[1], activation, None), axis=1)\n with tf.variable_scope('q', reuse=True):\n q_pi_mu = tf.squeeze(mlp(tf.concat([x, pi_mu], axis=-1), list(hidden_sizes)+[1], activation, None), axis=1)\n # q_pi = q_mlp(tf.concat([x,pi], axis=-1), list(hidden_sizes)+[1], activation, None)\n return pi, pi_mu, pi_sigma, q, q_pi, q_pi_mu\n","sub_path":"spinup/algos/sddpg_simple2/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"504154293","text":"class Solution(object):\n def isAnagram(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n dict1 = self.strToDict(s)\n dict2 = self.strToDict(t)\n if dict1 == dict2:\n return True\n else:\n return False\n \n def strToDict(self, s):\n dict = {}\n for c in s:\n if dict.has_key(c):\n dict[c] = dict.get(c) + 1\n else:\n dict.setdefault(c, 1)\n return dict\n\nclass Solution_With_Python_API(object):\n def isAnagram(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n d1 = collections.defaultdict(int)\n d2 = collections.defaultdict(int)\n for c in s:\n d1[c] += 1\n for c in t:\n d2[c] += 1\n if d1 == d2:\n return True\n else: \n return False\n\nclass Solution_With_Less_Space(object):\n def isAnagram(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n temp = [0 for i in range(26)]\n for c in s:\n temp[ord(c) - ord('a')] += 1\n for c in t:\n temp[ord(c) - ord('a')] -= 1\n for n in temp:\n if n != 0:\n return False\n return True","sub_path":"valid_anagram.py","file_name":"valid_anagram.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"425527093","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nimport re\nimport time\nimport pickle\nimport os, subprocess, operator, argparse\nfrom sys import argv\n#import delims\nimport sys\nfrom Chinese_handler import *\nfrom Preprocessing import *\nimport gc\n\ndef countNgram(n,fp1,fp2):\n fin = open(fp1, 'r')\n fout = open(fp2, 'a+')\n lines = fin.readlines()\n #lines = [line.decode('utf-8') for line in fin.readlines()]\n stop_words = load_stop_words(\"../data/fixed/stopWord.txt\")\n for oline in lines:\n line = oline.strip().split('\\t',2)\n #print(line[0]) line[0] is the label!\n #fout.write(line[0].encode('utf-8') + ' ')\n uString = preProcessing(line[2])[0].decode('utf-8').split() # the uString is the preprocessed line in lines\n for word in uString:\n if word in stop_words:\n continue\n L = len(word)\n if L == 1:\n fout.write(word.encode('utf-8', 'ignore') + ' ')\n continue\n for i in range(0, L - n + 1):\n cur = word[i:i + n]\n fout.write(cur.encode('utf-8', 'ignore') + ' ')\n # cur = word[L-1:L]\n # fout.write(cur.encode('utf-8', 'ignore') + ' ')\n fout.write('\\n')\n del lines\n del stop_words\n gc.collect()\n fin.close()\n fout.close()\n\n'''\n下面对ngram分词后得到的grams进行筛选\n'''\n'''\ndef load_dictionary():\n bigTable = {}\n fin = open('../data/derived/train_ngram_100w.txt', 'r')\n lines = [line.decode('utf-8') for line in fin.readlines()]\n for single_line in lines:\n words = single_line.split()\n length = len(words)\n print words[0] # the class label\n for i in range(1,length):\n if words[i] in bigTable:\n bigTable[words[i]] += 1\n else:\n bigTable.update({words[i]: 1})\n return bigTable\n\n\ndef neighborFilter():\n fin = open('../data/derived/train_ngram_100w.txt','r')\n fout = open('../data/derived/train_ngram_100w_new.txt','a+')\n lines = [line.decode('utf-8') for line in fin.readlines()]\n dict = load_dictionary()\n for line in lines:\n new_line = line\n words = line.split()\n length = len(words)\n for i in range(1,length-1):\n word1 = words[i]\n word2 = words[i+1]\n if word1 in dict and word2 in dict:\n freq1 = dict[word1]\n freq2 = dict[word2]\n if freq1 < 1.2 * freq2 and freq2 < 1.2 * freq1:\n dict.update({word1: 0})\n dict.update({word2: 0})\n new_line = new_line.replace(word1+\" \",\"\").replace(word2+\" \",\"\")\n elif freq1 < 0.1 * freq2:\n dict.update({word1: 0})\n new_line = new_line.replace(word1 + \" \",\"\")\n elif freq2 < 0.1 * freq1:\n dict.update({word2: 1})\n new_line = new_line.replace(word2 + \" \",\"\")\n fout.write(new_line.encode('utf-8'))\n'''\n","sub_path":"SVM_new/src/Ngram.py","file_name":"Ngram.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"353418201","text":"from typing import List, Dict\nimport sqlite3\nimport random\nfrom collections import defaultdict, OrderedDict, Counter\n\nfrom unidecode import unidecode\nfrom functional import seq\n\nfrom qanta.util.constants import MIN_APPEARANCES, PUNCTUATION\n\n\nclass Question:\n def __init__(self, qnum, answer, category, naqt,\n tournaments, page, ans_type, fold, gender):\n self.qnum = qnum\n self.answer = answer\n self.category = category\n self.naqt = naqt\n self.tournaments = tournaments\n self.page = page\n self.ans_type = ans_type\n self.fold = fold\n self.gender = gender\n self.text = {}\n self._last_query = None\n\n def raw_words(self):\n \"\"\"\n Return a list of all words, removing all punctuation and normalizing\n words\n \"\"\"\n for ii in sorted(self.text):\n for jj in self.split_and_remove_punc(self.text[ii]):\n yield jj\n\n @staticmethod\n def split_and_remove_punc(text):\n for ii in text.split():\n word = \"\".join(x for x in unidecode(ii.lower()) if x not in PUNCTUATION)\n if word:\n yield word\n\n def partials(self, word_skip=-1):\n assert(isinstance(word_skip, int)), \"Needs an integer %i\" % word_skip\n for i in sorted(self.text):\n previous = [self.text[x] for x in sorted(self.text) if x < i]\n\n # TODO(jbg): Test to make sure this gives individual words\n # correctly if word_skip > 0\n if word_skip > 0:\n words = self.text[i].split()\n for j in range(word_skip, len(words), word_skip):\n yield i, j, previous + [\" \".join(words[:j])]\n\n yield i + 1, 0, [self.text[x] for x in sorted(self.text) if x <= i]\n\n def text_lines(self):\n d = {}\n d[\"id\"] = self.qnum\n d[\"answer\"] = unidecode(self.page)\n for ii in sorted(self.text):\n d[\"sent\"] = ii\n d[\"text\"] = unidecode(self.text[ii])\n yield d\n\n def get_text(self, sentence, token):\n if self._last_query != (sentence, token):\n self._last_query = (sentence, token)\n previous = \"\"\n for ii in range(sentence):\n previous += self.text.get(ii, \"\")\n if token > 0:\n previous += \" \".join(self.text[sentence].split()[:token])\n self._cached_query = previous\n return self._cached_query\n\n def add_text(self, sent, text):\n self.text[sent] = text\n\n def flatten_text(self):\n return unidecode(\" \".join(self.text[x] for x in sorted(self.text)))\n\n\nclass QuestionDatabase:\n def __init__(self, location):\n self._conn = sqlite3.connect(location)\n\n def query(self, command, arguments, text=True):\n questions = {}\n c = self._conn.cursor()\n command = 'select id, page, category, answer, ' + \\\n 'tournament, type, naqt, fold, gender ' + command\n c.execute(command, arguments)\n\n for qq, pp, cc, aa, tt, kk, nn, ff, gg in c:\n questions[qq] = Question(qq, aa, cc, nn, tt, pp, kk, ff, gg)\n\n if text:\n for ii in questions:\n command = 'select sent, raw from text where question=? order by sent asc'\n c.execute(command, (ii, ))\n for ss, rr in c:\n questions[ii].add_text(ss, rr)\n\n return questions\n\n def all_questions(self):\n return self.query('FROM questions where page != \"\"', ())\n\n def guess_questions(self, appearance_filter=lambda pq: len(pq[1]) >= MIN_APPEARANCES):\n question_pages = self.questions_with_pages()\n\n dev_questions = seq(question_pages.values()) \\\n .flatten() \\\n .filter(lambda q: q.fold == 'train' or q.fold == 'dev') \\\n .group_by(lambda q: q.page) \\\n .filter(appearance_filter) \\\n .flat_map(lambda pq: pq[1]) \\\n .filter(lambda q: q.fold != 'train')\n\n test_questions = seq(question_pages.values()) \\\n .flatten() \\\n .filter(lambda q: q.fold == 'test' or q.fold == 'devtest') \\\n .filter(lambda q: q.page != '')\n\n return (dev_questions + test_questions).list()\n\n def answer_map(self, normalization=lambda x: x):\n c = self._conn.cursor()\n command = 'select answer, page from questions ' + \\\n 'where page != \"\"'\n c.execute(command)\n\n d = defaultdict(Counter)\n for aa, pp in c:\n d[normalization(aa)][pp] += 1\n\n return d\n\n def questions_with_pages(self) -> Dict[str, List[Question]]:\n page_map = OrderedDict()\n\n questions = self.query('from questions where page != \"\"', ()).values()\n\n for row in sorted(questions, key=lambda x: x.answer):\n if row.page not in page_map:\n page_map[row.page] = []\n page_map[row.page].append(row)\n return page_map\n\n def prune_text(self):\n \"\"\"\n Remove sentences that do not have an entry in the database\n \"\"\"\n\n c = self._conn.cursor()\n command = 'select id from questions group by id'\n c.execute(command)\n questions = set(x for x in c)\n\n c = self._conn.cursor()\n command = 'select question from text group by question'\n c.execute(command)\n text = set(x for x in c)\n\n orphans = text - questions\n\n c = self._conn.cursor()\n for ii in orphans:\n command = 'delete from text where question=%i' % ii\n c.execute(command)\n print(\"Keeping %i Pruning %i\" % (len(questions - orphans),\n len(orphans)))\n self._conn.commit()\n\n def page_by_count(self, min_count=1, exclude_test=False):\n \"\"\"\n Return all answers that appear at least the specified number\n of times in a category.\n \"\"\"\n c = self._conn.cursor()\n if exclude_test:\n command = 'select page, count(*) as num from questions where ' + \\\n 'page != \"\" and fold != \"test\" and fold != \"devtest\"' + \\\n 'group by page order by num desc'\n else:\n command = 'select page, count(*) as num from questions where ' + \\\n 'page != \"\" ' + \\\n 'group by page order by num desc'\n c.execute(command)\n\n for aa, nn in c:\n if nn < min_count:\n continue\n else:\n yield aa\n\n def get_all_pages(self, exclude_test=False):\n c = self._conn.cursor()\n if exclude_test:\n c.execute('select distinct page from questions where page != \"\" and fold != \"devtest\" and fold != \"test\"')\n else:\n c.execute('select distinct page from questions where page != \"\"')\n for result_tuple in c:\n yield result_tuple[0]\n\n def all_answers(self):\n \"\"\"\n Return a lookup from IDs to pages\n \"\"\"\n answers = {}\n c = self._conn.cursor()\n command = \"select id, page from questions where page != ''\"\n c.execute(command)\n\n for qid, page in c:\n answers[int(qid)] = page\n return answers\n","sub_path":"qanta/util/qdb.py","file_name":"qdb.py","file_ext":"py","file_size_in_byte":7273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"513864612","text":"import pandas as pd\nimport MeCab\nfrom pymongo import MongoClient\nimport re\nfrom statistics import mean\nimport time\nfrom timeMeasurement import time_measurement\n\nclient = MongoClient('localhost', 27017)\n\n# データベース指定\ndb = client.mydb\n\n# コレクション指定\ncount = db.kousienPN.find().limit(1000)\nsave = db.testMain\n\n# related_words読み込み\n# names=(関連語、関連値)\nrelated_df = pd.read_csv(\"related_words.txt\",\n sep=':',\n encoding='utf-8',\n names=('Word', 'Related')\n )\nword_list = list(related_df['Word'])\nrelated_list = list(related_df['Related']) # 中身の型はnumpy.float64\nrelated_dict = dict(zip(word_list, related_list))\n\n# 各ツイートを形態素解析して、一単語ずつrelated_wordsと照合する\ndef related_tweets():\n for record in count:\n m = MeCab.Tagger('')\n mecabPrint = m.parse(record['text'])\n lines = mecabPrint.split('\\n') # 解析結果を1行(1語)ごとに分けてリストにする\n lines = lines[0:-2] # 後ろ2行は不要なので削除\n # 形態素解析されたツイートを入れる配列\n diclist = []\n for word in lines:\n l = re.split('\\t|,',word) # 各行はタブとカンマで区切られてるので\n d = {'Surface':l[0], 'POS1':l[1], 'POS2':l[2], 'BaseForm':l[7]}\n diclist.append(d)\n\n # diclistの中身をpnTableと照合した結果を入れる配列\n diclist_new = []\n for word in diclist:\n base = word['BaseForm'] # 個々の辞書から基本形を取得\n if base in related_dict:\n related = float(related_dict[base]) # 中身の型があれなので\n word['Related'] = related\n diclist_new.append(word)\n else:\n related = 'notfound' # その語がrelationwordsになかった場合\n word['Related'] = related\n diclist_new.append(word)\n\n\n related_list = []\n # 各ツイートの類似度を算出\n for word in diclist_new:\n related = word['Related']\n if related != 'notfound':\n related_list.append(related) # notfoundだった場合は追加もしない\n if len(related_list) > 0: # 「全部notfound」じゃなければ\n relatedMean = mean(related_list)\n else:\n relatedMean = 0 # 全部notfoundならゼロにする\n\n # 確認用\n print('\\n' + str(diclist_new))\n print(relatedMean)\n\n # mongoDBに登録\n tweetPN = {}\n '''\n id : ツイートID\n text : テキスト本文\n created_at : ツイート日時\n user : ユーザ名\n PN : PN平均値\n related : 関連度\n '''\n tweetPN['id'] = record['id']\n tweetPN['text'] = record['text']\n tweetPN['created_at'] = record['created_at']\n tweetPN['user'] = {'screen_name': record['user']['screen_name']}\n tweetPN['PN'] = record['PN']\n tweetPN['related'] = relatedMean\n\n # コレクションに追加(コレクションもここで作成)\n save.insert(tweetPN)\n\nstart = time.time()\nrelated_tweets()\nelapsed_time = time.time() - start\nprint(time_measurement(elapsed_time))\n","sub_path":"recommendation/related_tweets.py","file_name":"related_tweets.py","file_ext":"py","file_size_in_byte":3385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"30527926","text":"#-------------------------------------------------------------------------------\n# Name: module1\n# Purpose:\n#\n# Author: Wornes\n#\n# Created: 15/02/2014\n# Copyright: (c) Wornes 2014\n# Licence: \n#-------------------------------------------------------------------------------\n#Necesario para iniciar pygame:\nimport sys, pygame, pygame.mixer\nfrom pygame.draw import *\nfrom pygame.surface import Surface\nfrom pygame.locals import *\n#from Game import Board,Player\nfrom Engine.Buttons.Button import *\npygame.init()\n\nexit = False\nstartGame = False\n\n#Crea una variable con dos atributos int\nsize = width, height = 1024, 768\nbuttonWidth = width/5\nbuttonHeight = height/10\n#color (rgb) negro usado para limpiar la pantalla\nblack = 0,0,0\npurple = 130,0,200\n#Crea un reloj. El reloj permite controlar los frames a los que se mueve el\n#programa, ya que si no se mueve a la velocidad que te permita el procesador.\nclock = pygame.time.Clock()\n#Una variable ventana\nscreen = pygame.display.set_mode(size)\nbackground =pygame.display.set_mode(size)\n#Buttons:\nstartGameButton = Button(width/2-width/10,height/4,buttonWidth,buttonHeight)\nexitButton = Button(width/2-width/10,height/2,buttonWidth,buttonHeight)\n#Text for the buttons\nmyfont = pygame.font.SysFont(\"monospace\", 15)\nlabelStartGame = myfont.render(\"Start Game\", 1, (255,255,0))\nlabelExit = myfont.render(\"Exit to desktop\", 1, (255,255,0))\n#Run\nwhile not exit:\n ''' Leer boton pulsado'''\n 'Dos botones: Start Game y Exit.'\n 'Dos cuadros de texto: Jugador1 y Jugador2 para incluir el nombre'\n for event in pygame.event.get():\n if event.type == MOUSEBUTTONDOWN:\n exit= exitButton.getRect().collidepoint(pygame.mouse.get_pos())\n if startGameButton.getRect().collidepoint(pygame.mouse.get_pos()):\n labelStartGame = myfont.render(\"GAME STARTED\", 1, (255,255,0))\n\n #\"limpia\" la ventana, poniendola a negro para evitar distorsiones\n # al moverse las imagenes\n #screen.fill(black)\n## screen.blit(background,(0,0))\n #Draw Buttons\n pygame.draw.rect(background,purple,startGameButton.getRect(),1)\n pygame.draw.rect(background,purple,exitButton.getRect(),1)\n #Draw text\n screen.blit(labelStartGame, startGameButton.getRect().midleft)\n screen.blit(labelExit, exitButton.getRect().midleft)\n #Hacemos que funcione cada 60 frames o algo asi, para ralentizarlo\n clock.tick(60)\n #flip refresca la pantalla, si no se pone no se muestran los cambios\n pygame.display.flip()\npygame.quit()\nsys.exit()","sub_path":"JuegoCartas/MainModule.py","file_name":"MainModule.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"593642845","text":"\"\"\"Simple least squares classifier for face emotion recognition.\n\nAdditionally uses random Gaussian matrix as featurization\n\"\"\"\n\nimport numpy as np\n\n\ndef evaluate(A, Y, w):\n Yhat = np.argmax(A.dot(w), axis=1)\n return float(np.sum(Yhat == Y)) / Y.shape[0]\n\n\ndef main():\n # load data\n with np.load('data/fer2013_train.npz') as data:\n X_train, X_test = data['X'], data['Y']\n\n with np.load('data/fer2013_test.npz') as data:\n Y_train, Y_test = data['X'], data['Y']\n\n # one-hot labels\n I = np.eye(3)\n Y_oh_train, Y_oh_test = I[Y_train], I[Y_test]\n\n # generate random Gaussian and featurize X\n d = 100\n W = np.random.normal(size=(X_train.shape[1], d))\n A_train, A_test = X_train.dot(W), X_test.dot(W)\n\n # train model\n w = np.linalg.inv(A_train.T.dot(A_train)).dot(A_train.T).dot(Y_oh_train)\n\n # evaluate model\n ols_train_accuracy = evaluate(A_train, Y_train, w)\n print('(ols) Train Accuracy:', ols_train_accuracy)\n ols_test_accuracy = evaluate(A_test, Y_test, w)\n print('(ols) Test Accuracy:', ols_test_accuracy)\n","sub_path":"src/step_6_ls_simple.py","file_name":"step_6_ls_simple.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"453986739","text":"__author__ = 'Chaddle'\n\nclass Armor(object):\n import re\n from bs4 import BeautifulSoup\n import urllib.request\n\n path = \"file:///.../equipment/armor.htm\"\n\n page = urllib.request.urlopen(path)\n soup = BeautifulSoup(page.read())\n col_heads = ['Cost', 'Armor/Shield Bonus', 'Maximum Dex Bonus', 'Armor Check Penalty',\n 'Arcane Spell Failure Chance', 'Speed30', 'Speed20', 'Weight']\n\n def __init__(self, name):\n self.name = str(name).strip()\n self.armor_dict = {}\n\n def get_stats(self):\n equip_table = []\n for line in self.soup.table.tbody.find_all('td'):\n equip_table.append(str(line.text).strip())\n\n armors_list = []\n for i in range(len(equip_table)):\n try:\n if i % 9 == 0 and self.name == equip_table[i]:\n armors_list.append(equip_table[i])\n except Exception as e:\n print(e)\n\n armor_dict = {}\n for a in armors_list:\n armor_dict[a] = {}\n index = equip_table.index(a)\n for h in self.col_heads:\n armor_dict[a][h] = equip_table[index+1]\n index += 1\n self.armor_dict = armor_dict[self.name]\n\nbreastplate = Armor(\"Breastplate\")\nbreastplate.get_stats()\nprint(breastplate.armor_dict[\"Cost\"])\n","sub_path":"equipment.py","file_name":"equipment.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"497544148","text":"from utils.control_bit import get_control_bit\nfrom utils.crc import get_crc_from_file\nfrom utils.modulo_sum import get_modulo_sum_from_file\nfrom utils.noise import set_noise_in_file\n\nif __name__ == '__main__':\n file_path = \"files/files_to_test/test.jpg\"\n crc_div = 78\n mod_div = 102\n\n file = open(file_path, \"rb\").read()\n\n ctrl_bit = get_control_bit(file)\n sum_mod = get_modulo_sum_from_file(file, mod_div)\n crc = get_crc_from_file(file, crc_div)\n\n print(\"Control bit: \", ctrl_bit)\n print(\"Modulo sum: \", sum_mod)\n print(\"CRC: \", crc)\n\n print(\"\\nAdding noises...\")\n file = set_noise_in_file(file, 0.0001)\n print(\"Added noises...\\n\")\n\n new_ctrl_bit = get_control_bit(file)\n new_sum_mod = get_modulo_sum_from_file(file, mod_div)\n new_crc = get_crc_from_file(file, crc_div)\n\n print(\"New control bit: \", new_ctrl_bit, \", old:\", ctrl_bit)\n print(\"New modulo sum: \", new_sum_mod, \", old: \", sum_mod)\n print(\"New CRC: \", new_crc, \", old: \", crc, \". Checked with prev CRC: \", get_crc_from_file(file, crc_div, crc))\n\n\n\n","sub_path":"lab1/new_main.py","file_name":"new_main.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"406982854","text":"import primerSetFinder\n\n\n\ndef largeFileReader():\n largeFile = 'nonRedundant.fasta'\n lineCount = 0\n coliPoint = 0\n coliSeq = ''\n file = open(largeFile,'r')\n for line in file:\n if '>' in line:\n if coliPoint == 1:\n primerSetFinder.fwdPrimerFinder(coliSeq,0,0)\n file.close()\n break\n if 'Escherichia coli' in line:\n coliPoint = 1\n elif coliPoint == 1:\n coliSeq = coliSeq + line\n lineCount += 1 ","sub_path":"largeFileReader.py","file_name":"largeFileReader.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"249880007","text":"import os\nimport argparse\nimport collections\nfrom numpy.core.fromnumeric import argsort\nimport torch\nimport numpy as np\nimport data_loader.data_loaders as module_data\nimport model.loss as module_loss\nimport model.metric as module_metric\nimport model.model as module_arch\nfrom parse_config import ConfigParser\nfrom trainer import ConstraintTrainer, LossReweightConstraintTrainer\nfrom utils import prepare_device, deep_copy\nfrom data_loader.random_noise import label_noise, noisy_labeler\nimport time\n\ndef main(config, args):\n logger = config.get_logger('train')\n\n # setup data_loader instances\n if config[\"data_loader\"][\"type\"] == \"CaltechDataLoader\":\n train_data_loader = config.init_obj('data_loader', module_data, idx_start = 0, img_num = 30, phase = \"train\")\n valid_data_loader = config.init_obj('data_loader', module_data, idx_start = 30, img_num = 20, phase = \"val\")\n test_data_loader = config.init_obj('data_loader', module_data, idx_start = 50, img_num = 20, phase = \"test\")\n elif config[\"data_loader\"][\"type\"] == \"AircraftsDataLoader\":\n train_data_loader = config.init_obj('data_loader', module_data, phase = \"train\")\n valid_data_loader = config.init_obj('data_loader', module_data, phase = \"val\")\n test_data_loader = config.init_obj('data_loader', module_data, phase = \"test\")\n elif config[\"data_loader\"][\"type\"] == \"BirdsDataLoader\" or \\\n config[\"data_loader\"][\"type\"] == \"CarsDataLoader\" or \\\n config[\"data_loader\"][\"type\"] == \"DogsDataLoader\" or \\\n config[\"data_loader\"][\"type\"] == \"IndoorDataLoader\" or \\\n config[\"data_loader\"][\"type\"] == \"Cifar10DataLoader\":\n train_data_loader = config.init_obj('data_loader', module_data, valid_split = 0.1, phase = \"train\")\n valid_data_loader = train_data_loader.split_validation()\n test_data_loader = config.init_obj('data_loader', module_data, phase = \"test\")\n elif config[\"data_loader\"][\"type\"] == \"FlowerDataLoader\":\n train_data_loader = config.init_obj('data_loader', module_data)\n valid_data_loader = train_data_loader.split_validation()\n test_data_loader = train_data_loader.split_test()\n\n device, device_ids = prepare_device(config['n_gpu'])\n if args.noisy_labeler:\n aux_model = module_arch.ResNet18(\n n_classes=config[\"arch\"][\"args\"][\"n_classes\"]-1 if args.train_dac else config[\"arch\"][\"args\"][\"n_classes\"]\n )\n aux_model.load_state_dict(torch.load(args.noisy_labeler_dir)[\"state_dict\"])\n wrong_indices, train_labels_old = noisy_labeler(\n train_data_loader,\n train_data_loader.dataset, \n train_data_loader.sampler.indices,\n aux_model,\n device = device\n )\n del aux_model\n logger.info(\"Randomizing {} number of labels\".format(wrong_indices.shape[0]))\n elif args.noise_rate!=0:\n wrong_indices, train_labels_old = label_noise(\n train_data_loader.dataset, train_data_loader.sampler.indices, args.noise_rate, symmetric=not args.noise_nonuniform\n )\n logger.info(\"Randomizing {} number of labels\".format(wrong_indices.shape[0]))\n\n # If small data, shrink training data size\n logger.info(\"Train Size: {} Valid Size: {} Test Size: {}\".format(\n len(train_data_loader.sampler), \n len(valid_data_loader.sampler), \n len(test_data_loader.sampler)))\n\n # build model architecture, then print to console\n model = config.init_obj('arch', module_arch)\n logger.info(model)\n\n # prepare for (multi-device) GPU training\n model = model.to(device)\n source_state_dict = deep_copy(model.state_dict())\n if len(device_ids) > 1:\n model = torch.nn.DataParallel(model, device_ids=device_ids)\n\n # get function handles of loss and metrics\n criterion = getattr(module_loss, config['loss'])\n metrics = [getattr(module_metric, met) for met in config['metrics']]\n\n accuracies = []\n torch.manual_seed(int(time.time()))\n for run in range(args.runs):\n model.reset_parameters(source_state_dict)\n # build optimizer, learning rate scheduler. delete every lines containing lr_scheduler for disabling scheduler\n trainable_params = filter(lambda p: p.requires_grad, model.parameters())\n optimizer = config.init_obj('optimizer', torch.optim, trainable_params)\n lr_scheduler = config.init_obj('lr_scheduler', torch.optim.lr_scheduler, optimizer)\n\n if args.train_correct_label:\n checkpoint_dir = os.path.join(\n \"./saved_label_noise\", \n \"{}_{}_noise_rate_{}_correct_label\".format(config[\"arch\"][\"type\"], config[\"data_loader\"][\"type\"], args.noise_rate))\n trainer = LossReweightConstraintTrainer(model, criterion, metrics, optimizer,\n config=config,\n device=device,\n train_data_loader=train_data_loader,\n valid_data_loader=valid_data_loader,\n test_data_loader=test_data_loader,\n lr_scheduler=lr_scheduler,\n checkpoint_dir=checkpoint_dir,\n adaptive_epoch=args.reweight_epoch,\n temp=args.reweight_temp,\n correct_epoch=args.correct_epoch,\n correct_thres=args.correct_thres,\n train_labels_old=train_labels_old)\n lambda_extractor = config[\"reg_extractor\"]\n lambda_pred_head = config[\"reg_predictor\"]\n scale_factor = config[\"scale_factor\"]\n if config[\"reg_method\"] == \"constraint\":\n trainer.add_constraint(\n norm = config[\"reg_norm\"], lambda_extractor = lambda_extractor, lambda_pred_head=lambda_pred_head, \n state_dict = source_state_dict, scale_factor=scale_factor\n )\n if config[\"reg_method\"] == \"penalty\":\n trainer.add_penalty(\n norm = config[\"reg_norm\"], lambda_extractor = lambda_extractor, lambda_pred_head=lambda_pred_head, \n state_dict = source_state_dict, scale_factor=scale_factor\n )\n else:\n checkpoint_dir = os.path.join(\n \"./saved_label_noise\", \n \"{}_{}_{}_{}_{:.4f}_{:.4f}_noise_rate_{}\".format(config[\"arch\"][\"type\"], config[\"data_loader\"][\"type\"], \n config[\"reg_method\"], config[\"reg_norm\"],\n config[\"reg_extractor\"], config[\"reg_predictor\"], args.noise_rate))\n trainer = ConstraintTrainer(model, criterion, metrics, optimizer,\n config=config,\n device=device,\n train_data_loader=train_data_loader,\n valid_data_loader=valid_data_loader,\n test_data_loader=test_data_loader,\n lr_scheduler=lr_scheduler,\n checkpoint_dir = checkpoint_dir)\n \n lambda_extractor = config[\"reg_extractor\"]\n lambda_pred_head = config[\"reg_predictor\"]\n scale_factor = config[\"scale_factor\"]\n if config[\"reg_method\"] == \"constraint\":\n trainer.add_constraint(\n norm = config[\"reg_norm\"], lambda_extractor = lambda_extractor, lambda_pred_head=lambda_pred_head, \n state_dict = source_state_dict, scale_factor=scale_factor\n )\n if config[\"reg_method\"] == \"penalty\":\n trainer.add_penalty(\n norm = config[\"reg_norm\"], lambda_extractor = lambda_extractor, lambda_pred_head=lambda_pred_head, \n state_dict = source_state_dict, scale_factor=scale_factor\n )\n\n trainer.train()\n accuracies.append(trainer.test())\n logger.info(\"Test Accuracy {:1.4f} +/- {:1.4f}\".format(np.mean(accuracies), np.std(accuracies)))\n\n\nif __name__ == '__main__':\n args = argparse.ArgumentParser()\n args.add_argument('-c', '--config', default=None, type=str,\n help='config file path (default: None)')\n args.add_argument('-r', '--resume', default=None, type=str,\n help='path to latest checkpoint (default: None)')\n args.add_argument('-d', '--device', default=None, type=str,\n help='indices of GPUs to enable (default: all)')\n args.add_argument('--runs', type=int, default=3)\n args.add_argument('--noise_rate', type=float, default=0)\n args.add_argument('--noise_nonuniform', action=\"store_true\")\n args.add_argument('--noisy_labeler', action=\"store_true\")\n args.add_argument('--noisy_labeler_dir', type=str, \\\n default=\"./saved_finetune_models/ResNet18_IndoorDataLoader_none_none_1.0000_1.0000/model_epoch_8.pth\")\n\n args.add_argument('--train_correct_label', action=\"store_true\")\n args.add_argument('--reweight_epoch', type=int, default=5)\n args.add_argument('--reweight_temp', type=float, default=1)\n args.add_argument('--correct_epoch', type=int, default=10)\n args.add_argument('--correct_thres', type=float, default=0.9)\n\n # custom cli options to modify configuration from default values given in json file.\n CustomArgs = collections.namedtuple('CustomArgs', 'flags type target')\n options = [\n CustomArgs(['--lr', '--learning_rate'], type=float, target='optimizer;args;lr'),\n CustomArgs(['--bs', '--batch_size'], type=int, target='data_loader;args;batch_size'),\n CustomArgs(['--model'], type=str, target=\"arch;type\"),\n CustomArgs(['--weight_decay'], type=float, target=\"optimizer;args;weight_decay\"),\n CustomArgs(['--reg_method'], type=str, target='reg_method'),\n CustomArgs(['--reg_norm'], type=str, target='reg_norm'),\n CustomArgs(['--reg_extractor'], type=float, target='reg_extractor'),\n CustomArgs(['--reg_predictor'], type=float, target='reg_predictor'),\n CustomArgs(['--scale_factor'], type=int, target=\"scale_factor\")\n ]\n config, args = ConfigParser.from_args(args, options)\n print(config)\n main(config, args)\n","sub_path":"train_label_noise.py","file_name":"train_label_noise.py","file_ext":"py","file_size_in_byte":10213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"325812768","text":"import requests \n\nclass BotHandler:\n\n def __init__(self, token):\n self.token = token\n self.api_url = \"https://api.telegram.org/bot{}/\".format(token)\n self.offset = None\n self.timeout = 0\n\n def get_updates(self):\n method = 'getUpdates'\n params = {'timeout': self.timeout, 'offset': self.offset}\n resp = requests.get(self.api_url + method, params)\n result_json = resp.json()['result']\n if len(result_json) > 0:\n self.offset = result_json[0]['update_id'] + 1\n else:\n self.offset = None\n return result_json\n\n def send_message(self, chat_id, text):\n params = {'chat_id': chat_id, 'text': text}\n method = 'sendMessage'\n resp = requests.post(self.api_url + method, params)\n return resp\n\n def reply_to_message(self, chat_id, text, reply_to_message_id):\n params = {'chat_id': chat_id, 'text': text, 'reply_to_message_id': reply_to_message_id}\n method = 'sendMessage'\n resp = requests.post(self.api_url + method, params)\n return resp\n\nmybot = BotHandler('649982709:AAEH6u7pmW6deVuJWfYDNOj5I5u-dXaN2rI');\n\nclass TranslaThor:\n\n def __init__(self, api_key):\n self.api_key = api_key\n self.api_url = 'https://translate.yandex.net/api/v1.5/tr.json/'\n\n def detect(self, text_for_detection):\n method = 'detect'\n params = {'key': self.api_key, 'text': text_for_detection}\n resp = requests.get(self.api_url + method, params) #prox\n detected = resp.json()\n return detected\n\n def translate(self, text_for_translation, lang = 'en'):\n method = 'translate'\n params = {'key': self.api_key, 'text': text_for_translation, 'lang': lang}\n resp = requests.get(self.api_url + method, params) #prox\n translated = resp.json()['text']\n return translated\n \ntranslator = TranslaThor('trnsl.1.1.20181209T145918Z.7dd52327550b6c7e.ed590e7965dad56809bb01fe77f376e97aa7619b')\n\ndef main():\n update = mybot.get_updates()\n if len(update) == 0:\n mybot.timeout = 100\n else:\n mybot.timeout = 100\n mybot.offset = update[-1]['update_id'] + 1\n while 1:\n update = mybot.get_updates()\n if len(update) > 0:\n mybot.send_message(666892256, str(update[0]))\n if('message' in update[0]):\n if ('text' in update[0]['message']):\n text_for_translation = update[0]['message']['text']\n chat_id = update[0]['message']['chat']['id']\n reply_to_message_id = update[0]['message']['message_id']\n lang = translator.detect(text_for_translation)['lang']\n if (lang != 'en' and lang != ''):\n translated_text = translator.translate(text_for_translation)\n mybot.reply_to_message(chat_id, translated_text, reply_to_message_id)\n\nif __name__ == '__main__': \n try:\n main()\n except KeyboardInterrupt:\n exit()\n","sub_path":"tran.py","file_name":"tran.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"557399433","text":"import json\nfrom pprint import pprint\nimport PythonParse\nimport random\nimport sys\n\nbaseName = sys.argv[1]\noriginal = PythonParse.ParsePlayerLogs(baseName+\"orig\")\nplayerLogs = PythonParse.ParsePlayerLogs(baseName)\nngramPlayerLogs = PythonParse.ParsePlayerLogs(baseName+\"ngram\")\nghostPlayerLogs = PythonParse.ParsePlayerLogs(baseName+\"ghost\")\nAIPlayerLogs = PythonParse.ParsePlayerLogs(baseName+\"AI\")\n\n\ndef getSimilarity(h1_hist, h2_hist):\n similarity = 1\n difference = 0\n\n keys = set(h1_hist.keys()).union(set(h2_hist.keys()))\n normalize = 1.0/len(keys)\n\n for key in keys:\n h1_count = h1_hist[key] if key in h1_hist else 0\n h2_count = h2_hist[key] if key in h2_hist else 0\n difference += float(abs(h1_count - h2_count)) / float((h1_count + h2_count))\n\n similarity -= normalize * difference\n print(similarity)\n\n return similarity\n\ndef evaluate(original, retry, ngram, Ghost, AI):\n original_hist = dict()\n retry_hist = dict()\n ngram_hist = dict()\n Ghost_hist = dict()\n AI_hist = dict()\n Other_hist = dict()\n\n #Comparator is a compilation of 1 to 3 grams\n for i in range(3):\n n = i+1\n for round in original:\n history = []\n for entry in round:\n if(entry['initiatedPlayer'] == 0):\n history.append(entry['p1Action'])\n if(len(history) > n):\n history.pop(0)\n if(len(history) == n):\n if(str(history) not in original_hist):\n original_hist[str(history)] = 0\n original_hist[str(history)] += 1\n\n for round in retry:\n history = []\n for entry in round:\n if(entry['initiatedPlayer'] == 0):\n history.append(entry['p1Action'])\n if(len(history) > n):\n history.pop(0)\n if(len(history) == n):\n if(str(history) not in retry_hist):\n retry_hist[str(history)] = 0\n retry_hist[str(history)] += 1\n for round in ngram:\n history = []\n for entry in round:\n if(entry['initiatedPlayer'] == 0):\n history.append(entry['p1Action'])\n if(len(history) > n):\n history.pop(0)\n if(len(history) == n):\n if(str(history) not in ngram_hist):\n ngram_hist[str(history)] = 0\n ngram_hist[str(history)] += 1\n for round in Ghost:\n history = []\n for entry in round:\n if(entry['initiatedPlayer'] == 0):\n history.append(entry['p1Action'])\n if(len(history) > n):\n history.pop(0)\n if(len(history) == n):\n if(str(history) not in Ghost_hist):\n Ghost_hist[str(history)] = 0\n Ghost_hist[str(history)] += 1\n for round in AI:\n history = []\n for entry in round:\n if(entry['initiatedPlayer'] == 0):\n history.append(entry['p1Action'])\n if(len(history) > n):\n history.pop(0)\n if(len(history) == n):\n if(str(history) not in AI_hist):\n AI_hist[str(history)] = 0\n AI_hist[str(history)] += 1\n #print(original_hist)\n #print(retry_hist)\n #print(ngram_hist)\n #print(Ghost_hist)\n #print(AI_hist)\n #print(Other_hist)\n\n print(\"~~~~~~~~~~~~~~~~~~~~~\")\n print(\"retry\")\n retry_sim = getSimilarity(retry_hist, original_hist)\n print(\"ngram\")\n ngram_sim = getSimilarity(retry_hist, ngram_hist)\n print(\"Ghost\")\n ghost_sim = getSimilarity(retry_hist, Ghost_hist)\n print(\"AI\")\n AI_sim = getSimilarity(retry_hist, AI_hist)\n print(\"~~~~~~~~~~~~~~~~~~~~~\")\n\n hists = [retry_sim, ngram_sim, ghost_sim, AI_sim]\n \n return hists\n\nretry_avg = []\nngram_avg = []\nghost_avg = []\nAI_avg = []\nother_avg = []\n\nfor i in range(5):\n if(i == int(sys.argv[3])):\n print(\"skip\")\n pass\n else:\n m_retry = playerLogs[i:i+1]\n m_ngram = ngramPlayerLogs[i:i+1]\n m_Ghost = ghostPlayerLogs[i:i+1] \n m_AI = AIPlayerLogs[i:i+1] \n res = evaluate(original, m_retry, m_ngram, m_Ghost, m_AI)\n if(res[0] != 1.0):\n retry_avg.append(res[0])\n ngram_avg.append(res[1])\n ghost_avg.append(res[2])\n AI_avg.append(res[3])\n\nimport numpy as np\nprint(\"Mean\")\nprint(np.mean(retry_avg))\nprint(np.mean(ngram_avg))\nprint(np.mean(ghost_avg))\nprint(np.mean(AI_avg))\nprint(\"Standard Deviation\")\nprint(np.std(retry_avg))\nprint(np.std(ngram_avg))\nprint(np.std(ghost_avg))\nprint(np.std(AI_avg))","sub_path":"AnalysisScripts-Train vs Test/SequenceSimilarityAnalysis.py","file_name":"SequenceSimilarityAnalysis.py","file_ext":"py","file_size_in_byte":4964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"495334903","text":"import sys\n\nis_frozen = getattr(sys, 'frozen', False)\nfrozen_temp_path = getattr(sys, '_MEIPASS', '')\n\nimport os\n\n# This is needed to find resources when using pyinstaller\nif is_frozen:\n basedir = frozen_temp_path\nelse:\n basedir = os.path.dirname(os.path.abspath(__file__))\nresource_dir = os.path.join(basedir, 'resources')\n\n\n\n\nimport gi\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import Gtk, Gdk\n\nfrom matplotlib import pyplot\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas\n# from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo as FigureCanvas\nfrom matplotlib.backends.backend_gtk3 import NavigationToolbar2GTK3 as NavigationToolbar\n\nfrom PlotWindow import PlotBox\nfrom About import AboutWindow\nfrom ErrorMessage import ErrorMessage\n\nclass ZoomWindow():\n def __init__(self, parent, simulation, colormap, zoom_value=0):\n self.zoom = 100.0\n\n self.parent = parent\n self.simulation = simulation\n self.colormap = colormap\n self.zoom_value = zoom_value\n\n \n self.builder = Gtk.Builder()\n \n self.builder.add_from_file(resource_dir + \"/zoom.glade\")\n self.window = self.builder.get_object(\"wndZoom\")\n self.statBar = self.builder.get_object(\"statBar\")\n self.btnApplyZoom = self.builder.get_object(\"btnApplyZoom\")\n self.txtZoomValue = self.builder.get_object(\"txtZoomValue\")\n self.boxPlot = self.builder.get_object(\"boxPlot\")\n self.menuColorMap = self.builder.get_object(\"menuColorMap\")\n self.btnQuit = self.builder.get_object(\"btnQuit\")\n self.btnAbout = self.builder.get_object(\"btnAbout\")\n\n self.window.set_transient_for(self.parent.window)\n\n self.btnApplyZoom.connect(\"clicked\", self.on_apply_zoom)\n self.btnQuit.connect(\"activate\", lambda _: self.window.close())\n\n self.txtZoomValue.connect(\"key-press-event\", self.on_key_press_event)\n\n self.plot = PlotBox(self, self.simulation, self.colormap, self.statBar)\n self.boxPlot.pack_start(self.plot.boxPlot, True, True, 0)\n\n self.btnAbout.connect(\"activate\", lambda _: AboutWindow(self.window))\n\n # Get a list of the colormaps in matplotlib. Ignore the ones that end with\n # '_r' because these are simply reversed versions of ones that don't end\n # with '_r'\n maps = sorted(m for m in pyplot.cm.datad if not m.endswith(\"_r\"))\n\n firstitem = Gtk.RadioMenuItem(self.colormap)\n firstitem.set_active(True)\n firstitem.connect('activate', self.on_color_bar_menu, self.colormap)\n self.menuColorMap.append(firstitem)\n for name in maps:\n if name != self.colormap:\n item = Gtk.RadioMenuItem.new_with_label([firstitem], name)\n item.set_active(False)\n item.connect('activate', self.on_color_bar_menu, name)\n self.menuColorMap.append(item)\n\n\n self.window.show_all()\n\n self.btnApplyZoom.emit(\"clicked\")\n\n def on_key_press_event(self, widget, event):\n\n # print(\"Key press on widget: \", widget)\n # print(\" Modifiers: \", event.state)\n # print(\" Key val, name: \", event.keyval, Gdk.keyval_name(event.keyval))\n\n # check the event modifiers (can also use SHIFTMASK, etc)\n ctrl = (event.state & Gdk.ModifierType.CONTROL_MASK)\n\n # see if we recognise a keypress\n if Gdk.keyval_name(event.keyval) == 'Return':\n # print(\"Enter\")\n self.on_apply_zoom(None)\n\n\n def isNumeric(self, val, func=float):\n try:\n func(val)\n return True\n except Exception as e:\n return False\n\n def on_apply_zoom(self, widget):\n value = self.txtZoomValue.get_text().replace(\"%\", \"\")\n self.zoom = float(value) if self.isNumeric(value) else False\n\n if not (self.zoom and self.zoom > 0):\n ErrorMessage(self.window, \"Invalid input parameters\", \"Zoom value must be a positive real.\")\n return\n\n zmin, zmax, ymin, ymax = self.plot.compute_zoom(self.zoom)\n \n self.parent.plot.draw_rectangle(zmin, zmax, ymin, ymax)\n self.txtZoomValue.set_text(\"{}%\".format(self.zoom))\n\n\n\n def on_color_bar_menu(self, widget, name):\n self.colormap = name\n self.plot.update_plot(name)","sub_path":"src/ZoomWindow.py","file_name":"ZoomWindow.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"309717197","text":"import matplotlib.pyplot as plt\r\n\r\ndata = open(\"populacao_brasileira.csv\").readlines()\r\n\r\nx = [] #Anos\r\ny = [] #População\r\n\r\nfor i in range(len(data)):\r\n\tif i != 0:\r\n\t\tlign = data[i].split(\";\")\r\n\t\tx.append(int(lign[0]))\r\n\t\ty.append(int(lign[1]))\r\n\r\nplt.plot(x, y, color=\"k\")\r\nplt.bar(x, y, color=\"#a9a9a9\")\r\nplt.title(\"Crescimento da população brasileira 1980-2016\")\r\nplt.xlabel(\"Ano\")\r\nplt.ylabel(\"População x 100.000.000\")\r\n#plt.show()\r\nplt.savefig(\"populacao_brasileira.png\", dpi=300)","sub_path":"populacao_brasileira.py","file_name":"populacao_brasileira.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"268891053","text":"# #!venv/bin/python\nimport logging\nimport os\n\nfrom aiogram import Bot, Dispatcher, executor, types\nfrom aiogram.dispatcher import FSMContext\nfrom aiogram.contrib.fsm_storage.memory import MemoryStorage\nfrom aiogram.dispatcher.filters import Text\n\nfrom profile import profile_start, register_profile_handlers\nfrom girths import girth_start, register_girth_handlers, show_girths\n# from entries import entries_start, register_entries_handlers\n\nfrom models.database import DB_NAME\nimport db\nfrom config import menu, text_welcome\nfrom dotenv import load_dotenv\n\nlogging.basicConfig(level=logging.INFO)\n\nload_dotenv()\ntoken = os.getenv(\"TELEGRAM_TOKEN\")\n\nbot = Bot(token)\ndp = Dispatcher(bot, storage=MemoryStorage())\n\n\n@dp.message_handler(commands=['start'], state=\"*\")\nasync def start_handler(message: types.Message, state: FSMContext):\n \"\"\"Обработка команды start. Вывод текста и меню\n Поиск пользователя в базе. Если не найден - предложить заполнить анкету.\n Если найден - показываем меню\"\"\"\n await state.finish()\n\n await message.answer(text_welcome)\n result = db.get_user(message.from_user.id)\n if not bool(result):\n await state.update_data(telegram_id=message.from_user.id)\n await profile_start(message)\n else:\n await message.answer(menu)\n\n\n@dp.message_handler(commands=['add_girths'], state=\"*\")\nasync def start_girths(message: types.Message, state: FSMContext):\n await state.finish()\n\n result = db.get_user(message.from_user.id)\n if bool(result):\n await state.update_data(user_id=result[0].id)\n await girth_start(message)\n else:\n await message.answer(\"Что-то пошло не так.\")\n\n\n@dp.message_handler(commands=['add_entries'], state=\"*\")\nasync def start_girths(message: types.Message, state: FSMContext):\n await state.finish()\n\n result = db.get_user(message.from_user.id)\n if bool(result):\n await state.update_data(user_id=result[0].id)\n # await entries_start(message)\n else:\n await message.answer(\"Что-то пошло не так.\")\n\n\n@dp.message_handler(commands=['get_girths'])\nasync def start_girths(message: types.Message):\n await show_girths(message)\n\n\nregister_profile_handlers(dp)\n# register_entries_handlers(dp)\nregister_girth_handlers(dp)\n\n# @dp.message_handler(commands=['help'])\n# async def help_handler(message: types.Message):\n# '''Обработка команды help. Вывод текста и меню'''\n\n# await message.answer(f'Привет, {message.from_user.first_name}!') \n\n\n# @dp.message_handler(lambda c: c.data == 'main_window')\n# async def show_main_window(calback_query: types.CallbackQuery):\n# '''Главный экран'''\n\n\n# @dp.message_handler()\n# async def unknown_message(message: types.Message):\n# \"\"\"Ответ на любое неожидаемое сообщение\"\"\"\n\n@dp.message_handler(commands=\"cancel\", state=\"*\")\n@dp.message_handler(Text(equals=\"отмена\", ignore_case=True), state=\"*\")\nasync def cancel(message: types.Message, state: FSMContext):\n await state.finish()\n await message.answer(\"Действие отменено\")\n\nif __name__ == '__main__':\n if not os.path.exists(DB_NAME):\n db.create()\n\n executor.start_polling(dp, skip_updates=True)\n\n\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"22127458","text":"import sys\nimport requests\nimport csv\n\ndef fetchArtistId(name):\n \"\"\"Using the Spotify API search method, take a string that is the artist's name, \n and return a Spotify artist ID.\n \"\"\"\n namespace = name.replace(\" \",\"%20\")\n url = 'https://api.spotify.com/v1/search?q=' + namespace + '&type=artist'\n req = requests.get(url)\n artistInfo = req.json()\n artists = artistInfo['artists']['items']\n \n if not artists: #If the artistInfo['artists']['items'] is empty, then it returns the error code\n \tsearchresultid = \"Search does not match an artist name\"\n else:\n \tsearchresultid = artists[0]['id']\n\n return searchresultid\n\n\ndef fetchArtistInfo(artist_id):\n \"\"\"Using the Spotify API, takes a string representing the id and\n returns a dictionary including the keys 'followers', 'genres', \n 'id', 'name', and 'popularity'.\n \"\"\"\n url = 'https://api.spotify.com/v1/artists/' + artist_id\n req = requests.get(url)\n artistInfo = req.json()\n\n artist_dict = {}\n\n artist_dict['followers'] = artistInfo['followers']['total']\n artist_dict['genres'] = artistInfo['genres']\n artist_dict['id'] = artistInfo['id']\n artist_dict['name'] = artistInfo['name']\n artist_dict['popularity'] = artistInfo['popularity']\n\n return artist_dict\n\n\n\n\n\n","sub_path":"Assignment7/fetchArtist.py","file_name":"fetchArtist.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"55918676","text":"import cv2\nimport numpy as np \n\nfrom matplotlib import pyplot as plt\nimport matplotlib.image as mpimg\n\n# abrindo imagem de nome \"imgteste\"\n\nimg = cv2.imread('imgteste.jpg', 0)\ncv2.imshow('Imagem', img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\nimg = cv2.imread(\"imgteste.jpg\", 0)\nplt.hist(img.ravel(), 256, [0, 256])\ncv2.imshow(\"Histograma\", img)\nplt.show()\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n# examinando os parâmetros do histograma\n#cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])\n#hist = cv2.calcHist([gray_img],[0],None,[256],[0,256])\n#\n#segmentando a imagem\n#img = cv2.imread('imgteste.jpg',0)\n#ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)\n#ret,thresh2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)\n#ret,thresh3 = cv2.threshold(img,127,255,cv2.THRESH_TRUNC)\n#ret,thresh4 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO)\n#ret,thresh5 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO_INV)\n#titles = ['Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']\n#images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]\n#for i in xrange(6):\n# plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')\n# plt.title(titles[i])\n# plt.xticks([]),plt.yticks([])\n#plt.show()\n#\n#cv2.waitKey(0)\n#cv2.destroyAllWindows()\n\nimg = cv2.imread('imgteste.jpg', 0)\ncv2.imshow('Imagem', img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\nhist = cv2.calcHist([img],[0],None,[256],[0,256])\nhist,bins = np.histogram(img,256,[0,256])\n\nplt.hist(img.ravel(),256,[0,256])\nplt.title('Histograma')\nplt.show()\n\nwhile True:\n k = cv2.waitKey(0) & 0xFF \n if k == 27: break # ESC key to exit\ncv2.destroyAllWindows()","sub_path":"cg.py","file_name":"cg.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"429948235","text":"x = 5\n\nprint(x)\nprint(x)\n# print(Have a nice day!)\nprint(\"Have a nice day!\")\n\ntemperature_in_celsius = 5\ncar_speed = 55\ntemperatureInCelsius = 55\n# 4runner = 5\nrunner4 = 5\n\nPI = 3.14159\nSCREEN_WIDTH = 800\nm = 294 / 10.5\nprint(m)\n\nm = 294\ng = 10.5\nm2 = m / g\nprint(m2)\n\n#Shift + F6 to change variable names\n\nx = 5 + 10\nprint(x)\n\nimport arcade\n\nSCREEN_WIDTH = 800\n\n# arcade.draw_circle_filled(400, 50, 10, arcade.color.RED)\n","sub_path":"Lab 02 - Draw a Picture/Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"560333287","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/12/29 13:44\n# @Author : StephenZ\n# @Site : \n# @File : Case27.py\n# @Purpose :\n# @Software : PyCharm\n# @Copyright: (c) StephenZ 2019\n# @Licence : <@2019>\nfrom typing import List\n\n\nclass Solution:\n def removeElement(self, nums: List[int], val: int) -> int:\n count = nums.count(val)\n for i in range(count):\n nums.remove(val)\n return len(nums)\n\n\n\n\ndef test_sulotion():\n nums = [0, 1, 2, 2, 3, 0, 4, 2]\n val = 2\n\n s = Solution()\n s.removeElement(nums, val)\n\n\nif __name__ == '__main__':\n test_sulotion()\n","sub_path":"Case/Case27.py","file_name":"Case27.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"351135059","text":"import discord\nfrom discord.ext import commands, menus\n\n\nclass HelpSource(menus.ListPageSource):\n \"\"\"\n This class is used to manage pagination of the help command.\n \"\"\"\n def __init__(self, ctx, fields, per_page=3):\n self.ctx = ctx\n self.num_fields = int(len(fields) / per_page)\n if len(fields) % per_page:\n self.num_fields += 1\n super().__init__(fields, per_page=per_page)\n\n async def format_page(self, menu, entries):\n offset = menu.current_page * self.per_page\n\n embed = discord.Embed(\n title=f\"\\N{NEWSPAPER} Help Menu [{menu.current_page + 1}/{self.num_fields}]\",\n description=f\"A listing of all available commands sorted by grouping.\\n\"\n f\"To learn more about specific commands, use `{self.ctx.bot.config['prefix']}help `\"\n )\n for field in [field for i, field in enumerate(entries, start=offset)]:\n embed.add_field(\n name=field['name'],\n value=field['value'],\n inline=field['inline']\n )\n embed.set_footer(\n text=self.ctx.bot.config['footer']['text'],\n icon_url=self.ctx.bot.config['footer']['icon_url']\n )\n return embed\n\n\nclass HelpCommand(commands.MinimalHelpCommand):\n \"\"\"\n Contains all of the features for a custom help message depending on certain\n values set when defining a command in the first place.\n\n NOTE: Users who use the help command can only see commands that they are actually allowed to use in permissions.\n Similarly, any commands that have `hidden=True` in their decorator are hidden.\n \"\"\"\n async def send_bot_help(self, mapping):\n \"\"\"\n Send a help list for all of the bot commands.\n \"\"\"\n fields = []\n # Parsing through all cogs and all commands contained within each command.\n for cog in mapping.keys():\n if cog:\n command_list = await self.filter_commands(mapping[cog], sort=True)\n if len(command_list) > 0:\n # If a cog contains visible commands, add the to an embed field.\n fields.append({\n \"name\": cog.qualified_name,\n \"value\": f\"{cog.description}\\nCommands:\\n\" +\n \", \".join(f\"`{command}`\" for command in command_list),\n \"inline\": False\n })\n\n # Create the paginated help menu\n pages = menus.MenuPages(source=HelpSource(self.context, fields), delete_message_after=True)\n await pages.start(self.context)\n\n async def send_cog_help(self, cog):\n \"\"\"\n Sends help for all commands contained within a cog, by cog name.\n \"\"\"\n embed = discord.Embed(\n title=f\"{cog.qualified_name} Help\",\n description=f\"{cog.description}\\nTo learn more about specific commands, \"\n f\"use `{self.clean_prefix}help `\"\n )\n embed.set_author(\n name=self.context.message.author,\n icon_url=self.context.message.author.avatar_url\n )\n embed.add_field(\n name=\"Commands\",\n value=\"\\n\".join(\n \"`{1.qualified_name}`\".format(self, command)\n for command in cog.walk_commands()\n if not command.hidden\n )\n )\n embed.set_footer(\n text=self.context.bot.config['footer']['text'],\n icon_url=self.context.bot.config['footer']['icon_url']\n )\n await self.get_destination().send(embed=embed)\n\n async def send_group_help(self, group):\n \"\"\"\n Sends help message for all commands grouped in a parent command.\n \"\"\"\n command_list = group.walk_commands()\n command_activation = []\n command_example = []\n for command in command_list:\n if f'`{command.qualified_name} {command.signature}` - {command.help}' not in command_activation:\n if not command.hidden:\n command_activation.append(f'`{command.qualified_name} {command.signature}` - {command.help}')\n if command.brief not in [None, \"\"]:\n command_example.append(f'`{self.clean_prefix}{command.qualified_name} {command.brief}`')\n else:\n command_example.append(f'`{self.clean_prefix}{command.qualified_name}`')\n\n fields = []\n if group.aliases:\n fields.append({\n \"name\": \"Aliases\",\n \"value\": \", \".join('`{}`'.format(alias) for alias in group.aliases),\n \"inline\": False\n })\n fields.append({\n \"name\": \"Commands\",\n \"value\": \"\\n\".join(command_activation),\n \"inline\": False\n })\n fields.append({\n \"name\": \"Examples\",\n \"value\": \"\\n\".join(command_example),\n \"inline\": False\n })\n\n embed = discord.Embed(\n title=f\"'{group.qualified_name.capitalize()}' Help\",\n description=f\"{group.help}\\n\\n\"\n f\"For more information on each command, use `{self.clean_prefix}help [command]`.\"\n )\n for field in fields:\n embed.add_field(\n name=field['name'],\n value=field['value'],\n inline=field['inline']\n )\n embed.set_author(\n name=self.context.message.author,\n icon_url=self.context.message.author.avatar_url\n )\n embed.set_footer(\n text=self.context.bot.config['footer']['text'],\n icon_url=self.context.bot.config['footer']['icon_url']\n )\n await self.get_destination().send(embed=embed)\n\n async def send_command_help(self, command):\n \"\"\"\n Send help for a specific given single command.\n \"\"\"\n fields = []\n if command.aliases:\n fields.append({\n \"name\": \"Aliases\",\n \"value\": \", \".join('`{}`'.format(alias) for alias in command.aliases),\n \"inline\": False\n })\n fields.append({\n \"name\": \"Usage\",\n \"value\": f\"`{self.clean_prefix}{command.qualified_name}\"\n f\"{' ' + command.signature if command.signature else ''}`\",\n \"inline\": False\n })\n fields.append({\n \"name\": \"Example\",\n \"value\": f\"`{self.clean_prefix}{command.qualified_name}\"\n f\"{' ' + command.brief if command.brief else ''}`\",\n \"inline\": False\n })\n\n embed = discord.Embed(\n title=f\"'{command.name.capitalize()}' Help\",\n description=f\"{command.help}\"\n )\n for field in fields:\n embed.add_field(\n name=field['name'],\n value=field['value'],\n inline=field['inline']\n )\n embed.set_author(\n name=self.context.message.author,\n icon_url=self.context.message.author.avatar_url\n )\n embed.set_footer(\n text=self.context.bot.config['footer']['text'],\n icon_url=self.context.bot.config['footer']['icon_url']\n )\n await self.get_destination().send(embed=embed)\n\n\nclass LoadHelp(commands.Cog, name=\"Help\"):\n \"\"\"\n The actual discord cog that is loaded when this file is added, simply wrapping the help command.\n \"\"\"\n def __init__(self, bot):\n self._original_help_command = bot.help_command\n self.bot = bot\n bot.help_command = HelpCommand()\n bot.help_command.cog = self\n print(f\"Loaded Help Cog.\")\n\n \"\"\"\n Called when the cog is unloaded from the system.\n \"\"\"\n def cog_unload(self):\n print(f\"Unloaded Help Cog.\")\n\n\ndef setup(bot):\n \"\"\"\n The function called by Discord.py when adding a file extension in a multi-file project.\n \"\"\"\n bot.add_cog(LoadHelp(bot))\n","sub_path":"cogs/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":8035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"215529153","text":"# Databricks notebook source\n# MAGIC %sh\n# MAGIC curl -O https://projecttextsummarization.s3.amazonaws.com/Apple.txt\n\n# COMMAND ----------\n\n# MAGIC %sh\n# MAGIC curl -O https://projecttextsummarization.s3.amazonaws.com/cosine_similarity_input_final_excel.txt\n\n# COMMAND ----------\n\ndir = '/tmp'\n\n# COMMAND ----------\n\ndbutils.fs.cp('file:/databricks/driver/Apple.txt', dir, recurse=True)\ndbutils.fs.cp('file:/databricks/driver/cosine_similarity_input_final_excel.txt', dir, recurse=True)\n\n# COMMAND ----------\n\n# apple store\n# /FileStore/tables/Apple.txt\n# terry collins\n# /FileStore/tables/OneArticle.txt\n\n# COMMAND ----------\n\nimport sys\nimport numpy\n\nnumpy.set_printoptions(threshold=sys.maxsize)\n\n# COMMAND ----------\n\nimport nltk\nfrom nltk import tokenize\nfrom nltk.cluster.util import cosine_distance\nimport numpy\nimport operator\n\n# COMMAND ----------\n\nnltk.download('all')\n\n# COMMAND ----------\n\nfile = open('/dbfs/tmp/Apple.txt')\narticle = file.read()\nprint(article)\narticle_sentences = tokenize.sent_tokenize(article)\n\n# COMMAND ----------\n\n# stop words in english - /FileStore/tables/english_stopwords.txt\nfrom nltk.corpus import stopwords\n\nstop_words = set(stopwords.words('english'))\n\n\n# COMMAND ----------\n\n# method to check if the word is a stop word\ndef is_stop_word(word):\n # print(\"found\")\n if word in stop_words:\n return True\n\n\n# COMMAND ----------\n\ndef normalize(matrix):\n for idx in range(len(matrix)):\n matrix[idx] /= matrix[idx].sum()\n\n return matrix\n\n\n# COMMAND ----------\n\ndef cosine_similarity_matrix(sentences):\n sentences_count = len(article_sentences)\n print(\"Sentence count\", sentences_count)\n # Create an empty similarity matrix\n cosine_similarity_matrix = numpy.zeros((sentences_count, sentences_count))\n\n for i in range(sentences_count):\n for j in range(sentences_count):\n if i == j:\n continue\n\n sentence_one = [word.lower() for word in article_sentences[i]]\n sentence_two = [word.lower() for word in article_sentences[j]]\n\n all_words = list(set(sentence_one + sentence_two))\n count_of_words = len(all_words)\n\n vector_for_sent1 = [0] * count_of_words\n vector_for_sent2 = [0] * count_of_words\n\n # build the vector for the first sentence\n for word in sentence_one:\n if (is_stop_word(word)): continue\n vector_for_sent1[all_words.index(word)] = vector_for_sent1[all_words.index(word)] + 1\n\n # build the vector for the second sentence\n for word in sentence_two:\n if (is_stop_word(word)): continue\n vector_for_sent2[all_words.index(word)] = vector_for_sent1[all_words.index(word)] + 1\n\n cosine_similarity_matrix[i][j] = 1 - cosine_distance(vector_for_sent1, vector_for_sent2)\n\n # print the similarity matrix\n # print(cosine_similarity_matrix)\n\n # return the cosine similarity matrix\n return normalize(cosine_similarity_matrix)\n\n\n# COMMAND ----------\n\ndef page_rank(cosine_similarity_matrix):\n jump_factor = 0.85\n error = 0.0001\n initial_page_rank = numpy.ones(len(cosine_similarity_matrix)) / len(cosine_similarity_matrix)\n\n while True:\n length_cosine_similarity = len(cosine_similarity_matrix)\n dot_product = cosine_similarity_matrix.T.dot(initial_page_rank)\n page_rank = numpy.ones(length_cosine_similarity) * (1 - jump_factor) / len(\n cosine_similarity_matrix) + jump_factor * dot_product\n\n if (abs(page_rank - initial_page_rank).sum()) <= error:\n return page_rank\n initial_page_rank = page_rank\n\n\n# COMMAND ----------\n\ndef get_summary(sentences, top_n=5):\n sentence_ranks = page_rank(cosine_similarity_matrix(sentences))\n\n # printing page rank\n # print(sentence_ranks)\n\n # Sort the sentence ranks\n ranked_sentence_indexes = [item[0] for item in sorted(enumerate(sentence_ranks), key=lambda item: -item[1])]\n top_n_sentences = ranked_sentence_indexes[:top_n]\n summary = operator.itemgetter(*sorted(top_n_sentences))(sentences)\n return summary\n\n\n# COMMAND ----------\n\n# DECISION TREE\n\n# COMMAND ----------\n\nimport numpy as np\nfrom math import log\nimport random\n\n\n# COMMAND ----------\n\n# Partition the output label based on the value\ndef partition(x):\n partition_split = {}\n counter = 0\n\n for i in x:\n if i in partition_split:\n partition_split[i].append(counter)\n else:\n partition_split[i] = [counter]\n counter += 1\n\n return partition_split\n\n\n# COMMAND ----------\n\ndef predict(x, tree):\n for split_criterion in tree:\n sub_tree = tree[split_criterion]\n attribute_index = split_criterion[0]\n attribute_value = split_criterion[1]\n split_decision = split_criterion[2]\n\n if split_decision == (x[attribute_index] == attribute_value):\n if type(sub_tree) is dict:\n prediction = predict(x, sub_tree)\n else:\n prediction = sub_tree\n\n return prediction\n\n\n# COMMAND ----------\n\n# Calculates the entropy value of the output label\ndef entropy(y, w=None):\n if w is None:\n w = np.ones((len(y), 1), dtype=int)\n\n total_weight = np.sum(w)\n partition_dict = partition(y)\n curr_entropy = 0.\n\n for key in partition_dict.keys():\n split_w = []\n for indices in partition_dict[key]:\n split_w.append(w[indices])\n y_val = np.sum(split_w) / total_weight\n curr_entropy -= y_val * log(y_val, 2)\n\n return curr_entropy\n\n\n# COMMAND ----------\n\n# Calculates the mutual information factor for the given input and the respective output label\ndef mutual_information(x, y, w=None):\n if w is None:\n w = np.ones((len(y), 1), dtype=int)\n\n y_entropy = entropy(y, w)\n\n conditional_entropy = 0\n total_weight = np.sum(w)\n partition_split = partition(x)\n\n for j in partition_split.keys():\n split_y = []\n split_w = []\n for x in partition_split[j]:\n split_y.append(y[x])\n split_w.append(w[x])\n conditional_entropy += np.sum(split_w) * entropy(split_y, split_w)\n curr_info_gain = y_entropy - (conditional_entropy / total_weight)\n\n return curr_info_gain\n\n\n# COMMAND ----------\n\n# Decision tree implementation\ndef id3(x, y, attribute_value_pairs=None, depth=0, max_depth=5, w=None):\n local_attribute_val_pairs = []\n if depth == 0:\n column_counter = 0\n for column in x.T:\n unique_values = np.unique(column)\n for i in unique_values:\n local_attribute_val_pairs.append(tuple((column_counter, i)))\n column_counter += 1\n else:\n local_attribute_val_pairs = attribute_value_pairs\n\n values, counts = np.unique(y, return_counts=True)\n\n if (depth == max_depth) or (len(values) == 1) or (len(local_attribute_val_pairs) == 0):\n return values[counts.argmax()]\n\n best_attribute = 0\n best_value = 0\n prev_best_info_gain = 0\n\n for attribute, value in local_attribute_val_pairs:\n x_part = (np.array(x)[:, attribute] == value).astype(int)\n curr_best_info_gain = mutual_information(x_part, y)\n if curr_best_info_gain > prev_best_info_gain:\n prev_best_info_gain = curr_best_info_gain\n best_attribute = attribute\n best_value = value\n\n partition_split = partition((np.array(x)[:, best_attribute] == best_value).astype(int))\n build_tree = {}\n\n for value, indices in partition_split.items():\n decision = bool(value)\n\n build_tree[(best_attribute, best_value, decision)] = id3(x.take(indices, axis=0)\n , y.take(indices, axis=0)\n , attribute_value_pairs=local_attribute_val_pairs\n , depth=depth + 1\n , max_depth=max_depth\n , w=w)\n return build_tree\n\n\n# COMMAND ----------\n\n# Calculates the error percentage for the predicted output label\ndef compute_error(y_true, y_pred, w=None):\n if w is None:\n w = np.ones((len(y_true), 1), dtype=int)\n error = []\n for i in range(len(y_true)):\n error.append(w[i] * (y_true[i] != y_pred[i]))\n\n return np.sum(error) / np.sum(w)\n\n\n# COMMAND ----------\n\n# Decision tree - Bagging implementation\ndef bagging(x, y, max_depth, num_trees):\n indices = []\n h_i = {}\n alpha_i = 1\n for t in range(num_trees):\n for k in range(len(y)):\n indices.append(random.randrange(len(y)))\n decision_tree = id3(x[indices], y[indices], max_depth=max_depth)\n h_i[t] = (alpha_i, decision_tree)\n\n return h_i\n\n\n# COMMAND ----------\n\n# Predicts the output label for the given X feature vector and the ensemble\ndef predict_example(x, h_ens):\n y_pred = []\n for row in x:\n pred = []\n n = 0\n for bag in h_ens.keys():\n alpha, tree = h_ens[bag]\n pred.append(alpha * predict(row, tree))\n n += alpha\n\n avg_value = np.sum(pred) / n\n if avg_value >= 0.5:\n y_pred.append(1)\n else:\n y_pred.append(0)\n\n return y_pred\n\n\n# COMMAND ----------\n\n# Applies the decision tree bagging implementation on the cosine similarity matrix of the input text\nM = np.genfromtxt('/dbfs/tmp/cosine_similarity_input_final_excel.txt', missing_values=0, skip_header=0,\n delimiter='\t', dtype=float)\nytrn = M[:, 0]\nXtrn = M[:, 1:]\n\n# Load the test data\nM = np.genfromtxt('/dbfs/tmp/cosine_similarity_input_final_excel.txt', missing_values=0, skip_header=0,\n delimiter='\t', dtype=float)\nytst = M[:, 0]\nXtst = M[:, 1:]\n\nprint('Bagging parameters and test data error')\n\nfor num_trees in (5, 10):\n for max_depth in (15, 17):\n h_ens = bagging(Xtrn, ytrn, max_depth, num_trees)\n y_pred = predict_example(Xtst, h_ens)\n test_error = compute_error(ytst, y_pred)\n print('Number of trees: ', num_trees)\n print('Maximum depth of the tree: ', max_depth)\n print('Test Error = {0:4.2f}%'.format(test_error * 100))\n print('----------')\n\n# COMMAND ----------\n\n# display the result\nfor idx, summary in enumerate(get_summary(article_sentences)):\n print(summary)\n\n# COMMAND ----------\n\n\n","sub_path":"Document Summarization.py","file_name":"Document Summarization.py","file_ext":"py","file_size_in_byte":10512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"225436624","text":"from argparse import ArgumentParser\nfrom dataclasses import dataclass\nfrom datetime import datetime\nfrom typing import List\n\nfrom rota.adapters.driven.formatter import MonthTableFormatter\nfrom rota.adapters.driven.generator import MonthGenerator\nfrom rota.adapters.driven.storage import Spreadsheet\nfrom rota.domain.rota import Rota\n\n\n@dataclass(frozen=True)\nclass AppConfig:\n file_name: str\n year: int\n month_name: str\n day_names: List[str]\n\n @classmethod\n def read_environment(cls):\n parser = ArgumentParser()\n\n parser.add_argument('-f', '--file_name', help=\"file name to store rota output\",\n default='rota.xlsx')\n parser.add_argument('-y', '--year', help=\"Desired year for rota\", type=int,\n default=datetime.now().year)\n parser.add_argument('-m', '--month_name', help=\"Name of the month desired for rota\",\n required=True)\n parser.add_argument('-d', '--day_names', help=\"Names of days desired for rota\",\n required=True, nargs='+')\n\n args = parser.parse_args()\n\n return cls(\n file_name=args.file_name,\n year=args.year,\n month_name=args.month_name,\n day_names=args.day_names,\n )\n\n\nif __name__ == '__main__':\n config = AppConfig.read_environment()\n\n Rota(\n date_generator=MonthGenerator(),\n formatter=MonthTableFormatter(),\n storage=Spreadsheet()\n ).generate(file_name=config.file_name, year=config.year, month_name=config.month_name,\n day_names=config.day_names)\n","sub_path":"rota/adapters/driver/cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"624350978","text":"STOP = 0\nFORWARD = 1\nRIGHT = 2\nBACKWARD = 3\nLEFT = 4\n\nANGULAR_SPEED = 1.0\nLINEAR_SPEED = 0.3\n\nFRAMING_ANGULAR_SPEED = 0.1\nFRAMING_LINEAR_SPEED = 0.3\n\nANGULAR_VELOCITY = 1\nLINEAR_VELOCITY = 1\n\nDIRECTION_SOURCE_FRAMING = 2\nDIRECTION_SOURCE_OBSTACLE_AVOIDANCE = 1\nDIRECTION_SOURCE_NONE = 0\n\n\nOBSTACLE_NONE = 0\nOBSTACLE_AT_LEFT = 1\nOBSTACLE_AT_RIGHT = 2\nOBSTACLE_AT_LEFT_RIGHT = 3\nOBSTACLE_AT_RIGHT_LEFT = 4\nOBSTACLE_STUCK = 5\n\nFRAMING_NONE = 0\nFRAMING_LEFT = 1\nFRAMING_RIGHT = 2\nFRAMING_KEEP_FRAME = 3\nFRAMING_KEEP_FRAME_BUT_FAR = 4\n","sub_path":"ROS/constants/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"277753404","text":"import re\nimport sys\n\n\ndef solve(data):\n m = re.sub(r'!.', '', data)\n depth = 0\n total = 0\n garbage = False\n for c in m:\n if garbage and c != '>':\n pass\n elif c == '>':\n garbage = False\n elif c == '<':\n garbage = True\n elif c == '{':\n depth += 1\n elif c == '}':\n total += depth\n depth = depth - 1 if depth > 0 else 0\n return total\n\n\nprint(solve(input()))\n","sub_path":"advent/2017/day09/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"345972666","text":"#!usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport getopt\nfrom urllib import request\nfrom bs4 import BeautifulSoup\n\n#html下载器\nclass HtmlDownloader(object):\n\tdef download(self,url):\n\t\treq=request.Request(url)\n\t\treq.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) \\\n\t\t\tAppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')\n\t\tresponse = request.urlopen(req)\n\t\tif response.getcode() != 200:\n\t\t\treturn None\n\t\treturn response.read()\n\n#html解析器\nclass HtmlParser(object):\n\tdef _get_new_urls(self,soup):\n\t\tnew_urls=set() #用来存放url\n\t\tlinks=soup.find_all('a')\n\t\tfor link in links:\n\t\t\tnew_url=link['href']\n\t\t\tnew_urls.add(new_url)\n\t\treturn new_urls\n\tdef parse(self,url,html_cont):\n\t\tsoup=BeautifulSoup(html_cont,'html.parser',from_encoding='utf-8') #解析数据\n\t\tnew_urls=self._get_new_urls(soup) #获取新的url\n\t\treturn new_urls\n\n#主函数\ndef mainfunc(urls,deep):\n\twhile deep > 0: #判断深度\n\t\tfor url in urls: #遍历每层深度的url\n\t\t\tnew_all_urls=set() #设置一个set()放置下一层的url\n\t\t\thtml_cont = HtmlDownloader().download(url) #下载页面\n\t\t\tnew_urls=HtmlParser().parse(url,html_cont) #解析url\n\t\t\tfor new_url in new_urls:\n\t\t\t\tnew_all_urls.add(new_url)\n\t\tdeep = deep - 1 \n\t\turls = new_all_urls #取得下一层深度的所有url\n\t\tprint(urls)\n\n#使用提示和帮助\ndef usage():\n\tprint('''\n\t\t用法:python spider.py -u url -d deep -f logfile -l loglevel(1-5) --help --thread threadnum --dbfile filepath --key keyword\n\t\t-u 指定爬虫开始地址\n\t\t-d 指定爬虫深度,默认为1\n\t\t-f 日志记录文件,默认spider.log\n\t\t-l 日志记录文件记录详细程度,数字越大记录越详细,可选参数,1-5取值,默认为1\n\t\t--help 输出帮助\n\t\t--thread 指定线程池大小,多线程爬取页面,可选参数,默认10\n\t\t--dafile 存放结果数据到指定的数据库(sqlite)文件中,默认为spide.db\n\t\t--key 页面内的关键词,获取满足该关键词的网页,可选参数,默认为所有页面\n\t\t''')\nif __name__ == \"__main__\":\n\turl = None\n\tdeep = 1\n\tlogfile = 'spider.log'\n\tloglevel = 5\n\tthreadnum = 1\n\tfilepath = 'spider.db'\n\tkeyword = None\n\ttry:\n\t\topts,args = getopt.getopt(sys.argv[1:],\"u:d:f:l:\",[\"help\",\"thread=\",\"dbfile=\",\"key=\"])\n\t\tfor name, value in opts:\n\t\t\tif name == '-u':\n\t\t\t\turl = value\n\t\t\telif name == '-d':\n\t\t\t\tdeep = value\n\t\t\telif name == '-f':\n\t\t\t\tlogfile = value\n\t\t\telif name == '-l':\n\t\t\t\tloglevel=value\n\t\t\telif name == '--thread':\n\t\t\t\tthreadnum = value\n\t\t\telif name == '--dafile':\n\t\t\t\tfilepath = value\n\t\t\telif name == '--key':\n\t\t\t\tkeyword = value\n\t\t\telif name == '--help':\n\t\t\t\tusage()\n\texcept:\n\t\tusage()\n\tdeep = int(deep)\n\tloglevel = int(loglevel)\n\tthreadnum = int(threadnum)\n\turls = set() #防止抓取重复URL\n\turls.add(url) #加入初始url\n\tif deep < 1 or loglevel < 1 or loglevel >5 or threadnum < 1 or not url:\n\t\tusage()\n\t\texit()\n\tmainfunc(urls,deep)\n\n","sub_path":"spider-u-d.py","file_name":"spider-u-d.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"137922495","text":"from sequana.iotools import YamlDocParser\nfrom sequana import sequana_data\nfrom sequana import snaketools\n\n\ndef test_yamlreader():\n filename = sequana_data(\"test_gui_generic_config.yaml\")\n r = YamlDocParser(filename)\n assert r.sections['N'] == '# example of docstring\\n'\n\n # check docstring is parsed with #### removed\n r = YamlDocParser(snaketools.Module('quality_control').config)\n docstring = r._block2docstring(\"fastqc\")\n assert docstring.startswith(\"FastQC\")\n\n assert r._block2docstring(\"dummy\") is None\n\n # check that pipelines can be parsed\n for pipeline in snaketools.pipeline_names:\n filename = snaketools.Module(pipeline).config\n r = YamlDocParser(filename)\n","sub_path":"test/test_iotools.py","file_name":"test_iotools.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"535001151","text":"import re\n\n\ndef match(t1, t2):\n result = False\n try:\n if re.match(t1 + '$', t2):\n result = True\n except:\n pass\n if t1 == t2:\n result = True\n return result\n\n\nclass Config:\n\n def __init__(self):\n self.name = \"\"\n self.set_map = {}\n self.unset_list = []\n self.sub_config_list = []\n self.edit_list = []\n\n def set_name(self, name):\n self.name = name\n\n def get_name(self):\n return self.name\n\n def set_set_map(self, set_map):\n self.set_map = set_map\n\n def get_set_map(self):\n return self.set_map\n\n def set_unset_list(self, unset_list):\n self.unset_list = unset_list\n\n def get_unset_list(self):\n return self.unset_list\n\n def set_sub_config_list(self, sub_config_list):\n self.sub_config_list = sub_config_list\n\n def get_sub_config_list(self):\n return self.sub_config_list\n\n def set_edit_list(self, edit_list):\n self.edit_list = edit_list\n\n def get_edit_list(self):\n return self.edit_list\n\n def is_same(self, config):\n if not isinstance(config, Config):\n return False\n if self.name == config.name:\n return True\n else:\n return False\n\n def is_empty(self):\n ret = False\n if self.name == \"\" and len(self.set_map.keys()) == 0 and len(self.unset_list) == 0 \\\n and len(self.sub_config_list) == 0 and len(self.edit_list) == 0:\n ret = True\n return ret\n\n def get_sub_config_name_list(self):\n ret = []\n for config in self.sub_config_list:\n ret.append(config.get_name())\n return ret\n\n def get_sub_config_by_name(self, name):\n ret = None\n for config in self.sub_config_list:\n if name == config.get_name():\n ret = config\n return ret\n\n def get_edit_name_list(self):\n ret = []\n for edit in self.edit_list:\n ret.append(edit.get_name())\n return ret\n\n def get_edit_by_name(self, name):\n ret = None\n for edit in self.edit_list:\n if name == edit.get_name():\n ret = edit\n return ret\n\n def compare(self, config):\n if not self.is_same(config):\n return self, config\n\n more = Config()\n less = Config()\n\n # compare set\n self_set_keys = self.set_map.keys()\n other_set_keys = config.get_set_map().keys()\n for key in [i for i in self_set_keys if i not in other_set_keys]:\n more.get_set_map()[key] = self.set_map[key]\n\n for key in [i for i in other_set_keys if i not in self_set_keys]:\n less.get_set_map()[key] = config.get_set_map()[key]\n\n for key in [i for i in self_set_keys if i in other_set_keys]:\n if not match(self.set_map[key], config.get_set_map()[key]):\n more.get_set_map()[key] = self.set_map[key]\n less.get_set_map()[key] = config.get_set_map()[key]\n\n # compare unset\n other_unset_list = config.get_unset_list()\n for key in [i for i in self.unset_list if i not in other_unset_list]:\n more.get_unset_list().append(key)\n\n for key in [i for i in other_unset_list if i not in self.unset_list]:\n less.get_unset_list().append(key)\n\n # compare sub config\n self_sub_conf_name_list = self.get_sub_config_name_list()\n other_sub_conf_name_list = config.get_sub_config_name_list()\n for name in [i for i in self_sub_conf_name_list if i not in other_sub_conf_name_list]:\n more.get_sub_config_list().append(self.get_sub_config_by_name(name))\n\n for name in [i for i in other_sub_conf_name_list if i not in self_sub_conf_name_list]:\n less.get_sub_config_list().append(config.get_sub_config_by_name(name))\n\n for name in [i for i in self_sub_conf_name_list if i in other_sub_conf_name_list]:\n sub_config_more, sub_config_less = \\\n self.get_sub_config_by_name(name).compare(config.get_sub_config_by_name(name))\n if not sub_config_more.is_empty():\n more.get_sub_config_list().append(sub_config_more)\n if not sub_config_less.is_empty():\n less.get_sub_config_list().append(sub_config_less)\n\n # compare edit\n self_edit_name_list = self.get_edit_name_list()\n other_edit_name_list = config.get_edit_name_list()\n for name in [i for i in self_edit_name_list if i not in other_edit_name_list]:\n more.get_edit_list().append(self.get_edit_by_name(name))\n\n for name in [i for i in other_edit_name_list if i not in self_edit_name_list]:\n less.get_edit_list().append(config.get_edit_by_name(name))\n\n for name in [i for i in self_edit_name_list if i in other_edit_name_list]:\n edit_more, edit_less = self.get_edit_by_name(name).compare(config.get_edit_by_name(name))\n if not edit_more.is_empty():\n more.get_edit_list().append(edit_more)\n if not edit_less.is_empty():\n less.get_edit_list().append(edit_less)\n\n #set name\n if not more.is_empty():\n more.set_name(self.name)\n if not less.is_empty():\n less.set_name(self.name)\n\n return more, less\n\n def equals(self, config):\n ret = False\n if self.is_same(config):\n more, less = self.compare(config)\n if more.is_empty() and less.is_empty():\n ret = True\n return ret\n\n def to_string(self, blank=\"\"):\n ret = \"\"\n indentation = \" \"\n # name\n ret = blank + \"config \" + self.name\n # set\n for key, value in self.set_map.items():\n ret += \"\\n\" + blank + indentation + \"set \" + key + \" \" + value\n # unset\n for key in self.unset_list:\n ret += \"\\n\" + blank + indentation + \"unset \" + key\n # sub config\n for config in self.sub_config_list:\n ret += \"\\n\" + config.to_string(blank + indentation)\n # edit\n for edit in self.edit_list:\n ret += \"\\n\" + edit.to_string(blank + indentation)\n #end\n ret += \"\\n\" + blank + \"end\"\n\n return ret\n\n def to_diff_string(self, config, blank=\"\"):\n ret = \"\"\n indentation = \" \"\n\n if self.name != config.name:\n ret += self.diff_str(blank, \"-\")\n ret += \"\\n\" + config.diff_str(blank, \"+\")\n return\n\n diff = False\n self_set_keys = self.set_map.keys()\n other_set_keys = config.get_set_map().keys()\n del_set_list = []\n add_set_list = []\n for key in [i for i in self_set_keys if i not in other_set_keys]:\n del_set_list.append([key, self.set_map[key]])\n diff = True\n\n for key in [i for i in other_set_keys if i not in self_set_keys]:\n add_set_list.append([key, config.set_map[key]])\n diff = True\n\n for key in [i for i in self_set_keys if i in other_set_keys]:\n if self.set_map[key] != config.get_set_map()[key]:\n del_set_list.append([key, self.set_map[key]])\n add_set_list.append([key, config.set_map[key]])\n diff = True\n\n other_unset_list = config.get_unset_list()\n del_unset_list = []\n add_unset_list = []\n for key in [i for i in self.unset_list if i not in other_unset_list]:\n del_unset_list.append(key)\n diff = True\n\n for key in [i for i in other_unset_list if i not in self.unset_list]:\n add_unset_list.append(key)\n diff = True\n\n # compare sub config\n self_sub_conf_name_list = self.get_sub_config_name_list()\n other_sub_conf_name_list = config.get_sub_config_name_list()\n del_subconfig_list = []\n add_subconfig_list = []\n upd_subconfig_list = []\n for name in [i for i in self_sub_conf_name_list if i not in other_sub_conf_name_list]:\n del_subconfig_list.append(self.get_sub_config_by_name(name))\n diff = True\n\n for name in [i for i in other_sub_conf_name_list if i not in self_sub_conf_name_list]:\n add_subconfig_list.append(config.get_sub_config_by_name(name))\n diff = True\n\n for name in [i for i in self_sub_conf_name_list if i in other_sub_conf_name_list]:\n sub_config_more, sub_config_less = \\\n self.get_sub_config_by_name(name).compare(config.get_sub_config_by_name(name))\n if not sub_config_more.is_empty() or not sub_config_less.is_empty():\n upd_subconfig_list.append([self.get_sub_config_by_name(name), config.get_sub_config_by_name(name)])\n diff = True\n\n # compare edit\n self_edit_name_list = self.get_edit_name_list()\n other_edit_name_list = config.get_edit_name_list()\n del_edit_list = []\n add_edit_list = []\n upd_edit_list = []\n for name in [i for i in self_edit_name_list if i not in other_edit_name_list]:\n del_edit_list.append(self.get_edit_by_name(name))\n diff = True\n\n for name in [i for i in other_edit_name_list if i not in self_edit_name_list]:\n add_edit_list.append(config.get_edit_by_name(name))\n diff = True\n\n for name in [i for i in self_edit_name_list if i in other_edit_name_list]:\n edit_more, edit_less = self.get_edit_by_name(name).compare(config.get_edit_by_name(name))\n if not edit_more.is_empty() or not edit_less.is_empty():\n upd_edit_list.append([self.get_edit_by_name(name), config.get_edit_by_name(name)])\n diff = True\n\n if diff:\n ret += \" \" + blank + \"config \" + self.name\n\n for set in del_set_list:\n ret += \"\\n\" + \"-\" + blank + indentation + \"set \" + set[0] + \" \" + set[1]\n for key in del_unset_list:\n ret += \"\\n\" + \"-\" + blank + indentation + \"unset \" + key\n for sub_config in del_subconfig_list:\n ret += \"\\n\" + sub_config.diff_str(blank + indentation, \"-\")\n for edit in del_edit_list:\n ret += \"\\n\" + edit.diff_str(blank + indentation, \"-\")\n\n for set in add_set_list:\n ret += \"\\n\" + \"+\" + blank + indentation + \"set \" + set[0] + \" \" + set[1]\n for key in add_unset_list:\n ret += \"\\n\" + \"+\" + blank + indentation + \"unset \" + key\n for sub_config in add_subconfig_list:\n ret += \"\\n\" + sub_config.diff_str(blank + indentation, \"+\")\n for edit in add_edit_list:\n ret += \"\\n\" + edit.diff_str(blank + indentation, \"+\")\n\n for cofig_pair in upd_subconfig_list:\n ret += \"\\n\" + cofig_pair[0].to_diff_string(cofig_pair[1], blank + indentation)\n for edit_pair in upd_edit_list:\n ret += \"\\n\" + edit_pair[0].to_diff_string(edit_pair[1], blank + indentation)\n ret += \"\\n\" + \" \" + blank + \"end\"\n\n return ret\n\n def diff_str(self, blank, prefix):\n ret = \"\"\n indentation = \" \"\n # name\n ret = prefix + blank + \"config \" + self.name\n # set\n for key, value in self.set_map.items():\n ret += \"\\n\" + prefix + blank + indentation + \"set \" + key + \" \" + value\n # unset\n for key in self.unset_list:\n ret += \"\\n\" + prefix + blank + indentation + \"unset \" + key\n # sub config\n for config in self.sub_config_list:\n ret += \"\\n\" + config.diff_str(blank + indentation, prefix)\n # edit\n for edit in self.edit_list:\n ret += \"\\n\" + edit.diff_str(blank + indentation, prefix)\n # end\n ret += \"\\n\" + prefix + blank + \"end\"\n\n return ret\n","sub_path":"lib/fg_config_compare/lib/unit/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":11884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"521672480","text":"####################\n###### CLASS #######\n####################\nclass Machine:\n def __init__(self, nom, ip,cpu,ram,hdd,os):\n self.nom= nom\n self.ip = ip\n self.cpu= cpu\n self.ram= ram\n self.hdd= hdd\n self.os = os\n\n####################################################\n######### CRUD ###########################\n####################################################\n \ndef readAll():\n with open('machines.txt') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n for row in csv_reader:\n if line_count == 0:\n print(f'Column names are {\", \".join(row)}')\n line_count += 1\n else:\n print(f'\\t hostname={row[0]}, ip={row[1]}, nombre CPU={row[2]}, RAM={row[3]}, HardDisk={row[4]}, OS={row[5]} ')\n line_count += 1\n print(f'Processed {line_count} lines.')\n return line_count\n\n\ndef readAllv2():\n \n with open('machines.txt') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n str_machine =\"\"\n for row in csv_reader:\n #if line_count != 0:\n m1 = Machine(row[0],row[1],row[2],row[3],row[4],row[5])\n str_machine = str_machine + json.dumps(m1.__dict__)\n line_count += 1\n return str_machine\n\ndef readByName(hostname):\n with open('machines.txt') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n strReturn=\"\"\n for row in csv_reader:\n if row[0] == hostname:\n print(f'\\t hostname={row[0]}, ip={row[1]}, nombre CPU={row[2]}, RAM={row[3]}, HardDisk={row[4]}, OS={row[5]} ')\n m1 = Machine(row[0],row[1],row[2],row[3],row[4],row[5])\n print('the row found is '+strReturn)\n line_count += 1\n if line_count == 0:\n print (\"Hostname NOT FOUND\") \n return m1\n\n\ndef create(machine):\n with open('machines.txt', mode='a',newline='') as employee_file:\n employee_writer = csv.writer(employee_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n employee_writer.writerow([machine.nom, machine.ip, machine.cpu,machine.ram,machine.hdd,machine.os])\n return ''\n \n\ndef createOrUpdate(machine):\n\n if find(machine.nom) >= 0:\n delete(machine.nom)\n\n create(machine)\n return ''\n\n\ndef find(host):\n with open('machines.txt', 'rt') as f:\n reader = csv.reader(f, delimiter=',')\n line_count = -1\n line_found = -1\n for row in reader:\n line_count +=1\n if host == row[0]: # if the username shall be on column 3 (-> index 2)\n print ('existe dans la colon N°'+str(line_count))\n line_found = line_count\n print ('ligne trouver :'+str(line_found))\n return line_found\n\n\n\n\ndef delete(host):\n a_file = open(\"machines.txt\", \"r\")\n lines = a_file.readlines()\n a_file.close()\n #supprimer ligne\n del lines[find(host)]\n #réecrir fichier apres suppression ligne\n new_file = open(\"machines.txt\", \"w+\")\n for line in lines:\n new_file.write(line)\n new_file.close()\n return ''\n\n\"\"\"\n\n#################################\n######## test unitair ###########\n#################################\nclass TestStringMethods(unittest.TestCase):\n\n def test_readAll(self):\n\n file = open(\"machines.txt\",\"r\")\n Counter = 0\n # Reading from file\n Content = file.read()\n CoList = Content.split(\"\\n\")\n \n for i in CoList:\n if i:\n Counter += 1\n file.close()\n self.assertEqual(readAll(), Counter)\n \n\nif __name__ == '__main__':\n unittest.main()\n \n\"\"\"\n\n\n#############################\n########### API #############\n#############################\napp = Flask(__name__)\n\n@app.route(\"/machine\",methods=[\"GET\"])\ndef getAllAPI():\n return readAllv2()\n\n@app.route(\"/machine/\", methods=[\"GET\"])\ndef getByIdAPI(hostname):\n print('hostname ======' +hostname)\n m1 =readByName(hostname)\n return json.dumps(m1.__dict__)\n\n@app.route('/machine/addorupdate', methods=['POST'])\ndef createAPI():\n data = request.get_json()\n nom= data.get('nom', '')\n ip= data.get('ip', '')\n cpu= data.get('cpu', '')\n ram= data.get('ram', '')\n hdd= data.get('hdd', '')\n os= data.get('os', '')\n m1 = Machine(nom,ip,cpu,ram,hdd,os)\n createOrUpdate(m1)\n return \"Creation de l'hote \"+nom+\" est enregistrer avec succée !!\"\n\n@app.route('/machine/del/', methods=['DELETE'])\ndef deleteApi(host):\n delete(host)\n return \"le host \"+host+\" est supprimer avec succée !!\"\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')\n\n\n\"\"\"\n#########################\n#### INTERACTIVE ########\n#########################\n\nprint (\"Ce program permet de gérer les hosts\")\nprint (\"FORMAT : nom, ip, cpu, ram, hdd, os\")\nprint (\"Tapez votre choix\")\nprint (\"1:afficher , 2:ajouter , 3:supprimer, 4:modifier\")\naction = input(\"\")\n\nif action == \"1\":\n hostname = input(\"Merci de saisir le hostname a afficher:\")\n readByName(hostname)\nelif action==\"2\":\n print(\"Saisir les information de la machine a ajouter\")\n hostname = input(\"Saisir nom du hote:\")\n ip = input(\"Saisir l'adresse IP du hote:\")\n cpu = input(\"Saisir le nombre de CPU du hote:\")\n ram = input(\"Saisir la taille RAM du hote:\")\n hdd = input(\"Saisir la taille disque dur du hote:\")\n os = input(\"Saisir l'OS du hote:\")\n machine = Machine(hostname, cpu,ip,ram,hdd,os)\n createOrUpdate(machine)\n\n \nelif action==\"3\":\n hostname = input(\"Merci de saisir le hostname a supprimer:\")\n delete(hostname)\nelse:\n print(\"Saisir les information de la machine a modifier, s'il n'existe pas il va êtres créer\")\n hostname = input(\"Saisir nom du hote:\")\n readByName(hostname)\n print(\"****\")\n ip = input(\"Saisir l'adresse IP du hote:\")\n cpu = input(\"Saisir le nombre de CPU du hote:\")\n ram = input(\"Saisir la taille RAM du hote:\")\n hdd = input(\"Saisir la taille disque dur du hote:\")\n os = input(\"Saisir l'OS du hote:\")\n machine = Machine(hostname, cpu,ip,ram,hdd,os)\n createOrUpdate(machine)\n\"\"\"\n####### tester CRUD #######\n#m1 = Machine(\"host1\", \"ababababa\",\"8\",\"256\",\"500\",\"Ubuntu\")\n#createOrUpdate(m1)\n#create(m1)\n#delete(\"host2\")\n#find(\"host2\")\n\n\n","sub_path":"Data/host.py","file_name":"host.py","file_ext":"py","file_size_in_byte":6376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"568572146","text":"import json\n\nimport requests\nimport typing\nfrom flask import current_app, url_for, request, redirect\nfrom rauth import OAuth2Service\n\nfrom anyway.dataclasses.user_data import UserData\n\n\nclass OAuthSignIn(object):\n providers = {}\n\n def __init__(self, provider_name):\n self.provider_name = provider_name\n credentials = current_app.config[\"OAUTH_CREDENTIALS\"][provider_name]\n self.consumer_id = credentials[\"id\"]\n self.consumer_secret = credentials[\"secret\"]\n\n def authorize(self):\n pass\n\n def callback(self) -> typing.Optional[UserData]:\n pass\n\n def get_callback_url(self):\n return url_for(\"oauth_callback\", provider=self.provider_name, _external=True)\n\n @classmethod\n def get_provider(self, provider_name):\n # This is quick fix for the DEMO - to make sure that anyway.co.il is fully compatible with https://anyway-infographics-staging.web.app/\n if provider_name != \"google\":\n return None\n\n if not self.providers:\n self.providers = {}\n for provider_class in self.__subclasses__():\n provider = provider_class()\n self.providers[provider.provider_name] = provider\n return self.providers[provider_name]\n\n\nclass FacebookSignIn(OAuthSignIn):\n def __init__(self):\n super(FacebookSignIn, self).__init__(\"facebook\")\n self.service = OAuth2Service(\n name=\"facebook\",\n client_id=self.consumer_id,\n client_secret=self.consumer_secret,\n authorize_url=\"https://graph.facebook.com/oauth/authorize\",\n access_token_url=\"https://graph.facebook.com/oauth/access_token\",\n base_url=\"https://graph.facebook.com/\",\n )\n\n def authorize(self):\n return redirect(\n self.service.get_authorize_url(\n scope=\"email\", response_type=\"code\", redirect_uri=self.get_callback_url()\n )\n )\n\n def callback(self) -> typing.Optional[UserData]:\n if \"code\" not in request.args:\n return None\n oauth_session = self.service.get_auth_session(\n data={\n \"code\": request.args[\"code\"],\n \"grant_type\": \"authorization_code\",\n \"redirect_uri\": self.get_callback_url(),\n },\n decoder=json.loads,\n )\n # TODO: enrich facebook data collection\n me = oauth_session.get(\"me?fields=id,email\").json()\n name = me.get(\"email\").split(\"@\")[0], # Facebook does not provide username, so the email's user is used instead\n data_of_user = UserData(name=name, email=me.get(\"email\"), service_user_id=\"facebook$\" + me[\"id\"])\n\n\n return data_of_user\n\n\nclass GoogleSignIn(OAuthSignIn):\n def __init__(self):\n super(GoogleSignIn, self).__init__(\"google\")\n googleinfo = requests.get(\"https://accounts.google.com/.well-known/openid-configuration\")\n googleinfo.raise_for_status()\n google_params = googleinfo.json()\n self.service = OAuth2Service(\n name=\"google\",\n client_id=self.consumer_id,\n client_secret=self.consumer_secret,\n authorize_url=google_params.get(\"authorization_endpoint\"),\n base_url=google_params.get(\"userinfo_endpoint\"),\n access_token_url=google_params.get(\"token_endpoint\"),\n )\n\n def authorize(self):\n return redirect(\n self.service.get_authorize_url(\n scope=\"email\", response_type=\"code\", redirect_uri=self.get_callback_url()\n )\n )\n\n def callback(self) -> typing.Optional[UserData]:\n if \"code\" not in request.args:\n return None\n oauth_session = self.service.get_auth_session(\n data={\n \"code\": request.args[\"code\"],\n \"grant_type\": \"authorization_code\",\n \"redirect_uri\": self.get_callback_url(),\n },\n decoder=json.loads,\n )\n me = oauth_session.get(\"\").json()\n # The data in me dict includes information about the user, as described in\n # OpenID Connect Standard Claims(https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims) and the\n # claims_supported metadata value of the Discovery document(https://accounts.google.com/.well-known/openid-configuration)\n # So in the best case we have \"aud\", \"email\", \"email_verified\", \"exp\", \"family_name\", \"given_name\", \"iat\",\n # \"iss\", \"locale\", \"name\", \"picture\", \"sub\"\n # and in the worst case we only have \"sub\".\n # Note - in some places in the docs there is an indication that more fields exists.\n name = me.get(\"name\")\n if not name:\n if me.get(\"given_name\"):\n name = me.get(\"given_name\")\n if me.get(\"family_name\"):\n name = f\"{name} {me.get('family_name')}\" if name else me.get(\"family_name\")\n\n data_of_user = UserData(name=name, email=me.get(\"email\"), service_user_id=me[\"sub\"],\n service_user_domain=me.get(\"hd\"), service_user_locale=me.get(\"locale\"),\n picture_url=me.get(\"picture\"), user_profile_url=me.get(\"profile\"))\n\n return data_of_user\n\n","sub_path":"anyway/oauth.py","file_name":"oauth.py","file_ext":"py","file_size_in_byte":5257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"134432929","text":"#!/usr/bin/python3\n\n# A script to replicate the function of DNA polymerase,\n# that is to reads a straind of DNA or RNA and return its complementary\n# strand.\n\ndef readfile(file_location):\n file_string=''\n with open(file_location,'r') as file_object:\n file_string += file_object.readline().strip().upper()\n \n return file_string\n\n# This function translates the nucleic acid into its complementary strand.\n# In the function, the argument nucleic_acid specifies what you're translating. 'dna' or 'rna'.\n\ndef polymerase(na_string, nucleic_acid='dna'):\n dna_translation_table=str.maketrans('ACGT','TGCA')\n rna_translation_table=str.maketrans('ACGU','UGCA')\n \n if nucleic_acid == 'dna':\n reversed_complementary_strand=na_string.translate(dna_translation_table)\n elif nucleic_acid == 'rna':\n reversed_complementary_strand=na_string.translate(rna_translation_table)\n \n complementary_strand=reversed_complementary_strand[::-1] # Extended slice operator to reverse the string\n return complementary_strand\n \nif __name__=='__main__':\n from sys import argv\n print (polymerase(readfile(argv[-1]),argv[-2])) \n","sub_path":"Rosalind/polymerase.py","file_name":"polymerase.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"319526105","text":"\"\"\"changing case riders to JSON settings column\n\nRevision ID: 2eef59adf24d\nRevises: 11f6fc11b5eb\nCreate Date: 2015-12-10 21:32:36.167955\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '2eef59adf24d'\ndown_revision = '11f6fc11b5eb'\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('cases', sa.Column('case_rider_settings', postgresql.JSON(), nullable=True))\n op.drop_column('cases', 'case_riders')\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('cases', sa.Column('case_riders', sa.VARCHAR(length=64), autoincrement=False, nullable=True))\n op.drop_column('cases', 'case_rider_settings')\n ### end Alembic commands ###\n","sub_path":"alembic/versions/2eef59adf24d_changing_case_riders_to_json_settings_.py","file_name":"2eef59adf24d_changing_case_riders_to_json_settings_.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"48162391","text":"'''\nFind the sum of all left leaves in a given binary tree.\n\nExample:\n\n 3\n / \\\n 9 20\n / \\\n 15 7\n\nThere are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.\n'''\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def sumOfLeftLeaves(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if not root:\n return 0\n sum = 0\n stack = [root]\n cur = root\n while cur.left:\n stack.append(cur.left)\n cur = cur.left\n if cur != root and not cur.right:\n sum += cur.val\n while stack:\n node = stack.pop()\n if node.right:\n stack.append(node.right)\n cur = node.right\n while cur.left:\n stack.append(cur.left)\n cur = cur.left\n if cur != node.right and not cur.right:\n sum += cur.val\n return sum\n\n# easy solution as we don't care the order of the leaves\nclass Solution(object):\n def sumOfLeftLeaves(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if not root:\n return 0\n sum = 0\n stack = [root]\n while len(stack):\n cur = stack.pop()\n if cur.left != None:\n if cur.left.left == None and cur.left.right == None:\n sum += cur.left.val\n else:\n stack.append(cur.left)\n if cur.right != None:\n if cur.right.left != None or cur.right.right != None:\n stack.append(cur.right)\n return sum\n","sub_path":"tree/sum_0f_left_leaves.py","file_name":"sum_0f_left_leaves.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"228856251","text":"from sklearn.neighbors import NearestNeighbors\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nX = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])\r\nnbrs = NearestNeighbors(n_neighbors=2, algorithm='ball_tree').fit(X)\r\ndistances, indices = nbrs.kneighbors(X)\r\nplt.scatter(X[:,0],X[:,1])\r\nplt.show()\r\nprint(indices)\r\nprint(distances)\r\n","sub_path":"sample2.py","file_name":"sample2.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"540495912","text":"from django.urls import path\nfrom events import views\n#from django.conf import settings\n#from django.conf.url import static\nfrom .views import Login, Logout, Signup, home\n\nurlpatterns = [\n\tpath('', home, name='home'),\n path('event/', views.event, name='event'),\n path('add/', views.add_event, name='add_event'),\n path('dashboard/', views.dashboard, name='dashboard'),\n path('booked/', views.booked, name='booked'),\n path('/booking/', views.booking, name='booking'),\n path('/', views.event_detail, name='event-detail'),\n path('/delete/', views.delete_event, name='delete_event'),\n path('/update/', views.update_event, name='update_event'),\n path('signup/', Signup.as_view(), name='signup'),\n path('login/', Login.as_view(), name='login'),\n path('logout/', Logout.as_view(), name='logout'),\n #path('events_search/', views.events_search, name='events_search'),\n]\n\n\n\n#if settings.DEBUG:\n #urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n #urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"events/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":"15"} +{"seq_id":"273831504","text":"import json\nfrom .dynamics import Dynamics\nfrom .bbug import Bbug\nfrom boto3.dynamodb.conditions import Key, Attr\nfrom decimal import *\n\nclass Accounts(Dynamics):\n\n def __init__(self,settings):\n Dynamics.__init__(self,settings)\n self.table=self.dynamodb.Table('dynamics_accounts')\n\n def base_uri(self):\n return '/accounts'\n\n def save(self,account):\n self.table.put_item(Item=account)\n self.messages.append(\"Account \" + account['name'] +\n \" was saved in dynamodb.\")\n\n def get_from_dynamics(self, param_modifiedon=''):\n \"\"\"Get all the accounts with modifiedon greather than the latest\n modifiedon updated account. To change the defuault filter can use the\n param_modfiedon.\n\n Args:\n self (Accounts): Instance of Accounts.\n param_modifiedon (str): By defualt is an empty str, only used to\n force a modifiedon date.\n \"\"\"\n # get in dynamo the date of latest update\n table_modifiedon = self.dynamodb.Table('dynamics_accounts_greather_modifiedon')\n\n try:\n last_update=table_modifiedon.get_item( Key={ 'bbug_company_id':\n self.bbug_company_id })\n modifiedon=last_update['Item']['modifiedon']\n except:\n modifiedon='2000-01-01'\n\n # update all accounts greather than a param_modifiedon\n if param_modifiedon!='':\n modifiedon=param_modifiedon\n\n # get all accounts modifiedon after the latest update\n self.query({'$filter': 'modifiedon gt ' + modifiedon })\n self.data=json.loads(self.response.read())\n\n\n for account in self.data['value']:\n account['bbug_company_id']=self.bbug_company_id\n for k in account.keys():\n if isinstance(account[k] , float):\n account[k]=Decimal(str(account[k]))\n self.save(account)\n return self.get_messages()\n\n def get_messages(self):\n \"\"\"Get messages and clean the messages instance variable\n \"\"\"\n messages = self.messages\n self.messages=[]\n return messages\n\n def get_from_dynamo(self, limit = 100 ):\n response=self.table.query( KeyConditionExpression= Key('bbug_company_id').eq( self.bbug_company_id), Limit=limit)\n return response['Items']\n\n def to_update(self):\n response=self.table.query( KeyConditionExpression= Key('bbug_company_id').eq( self.bbug_company_id),\n FilterExpression='attribute_not_exists(bbug_updated_at)')\n return response['Items']\n","sub_path":"bbug_dynamics/accounts.py","file_name":"accounts.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"26085690","text":"import json\r\nimport time\r\nimport requests\r\nimport re\r\n\r\nfrom dateutil.parser import parse\r\nfrom .utils import get_soup\r\nfrom .parser import parse_legislate\r\n\r\nsearch_url = 'http://watch.peoplepower21.org/index.php?mid=Euian&show=&page={}&title={}&rec_num=1000&lname={}&sangim={}&bill_result={}'\r\nrequest_url = 'http://watch.peoplepower21.org/opages/Lawinfo/_vote_table.php'\r\nurl_base = 'http://watch.peoplepower21.org/?mid=LawInfo&bill_no={}'\r\n\r\n\r\ndef yield_law(bill_result, max_page =10, end_date = '2018-12-01', begin_date= '2017-12-01', title = '', lname = '', sangim ='', sleep=1.0):\r\n \"\"\"\r\n Artuments\r\n ---------\r\n law_status : str\r\n eg. 2018-01-01\r\n max_num : int\r\n Maximum number of news to be scraped\r\n sleep : float\r\n Sleep time. Default 1.0 sec\r\n\r\n It yields\r\n ---------\r\n news : json object\r\n \"\"\"\r\n\r\n # prepare parameters\r\n\r\n d_begin = parse(begin_date)\r\n d_end = parse(end_date)\r\n end_page = 30\r\n n_news = 0\r\n outdate = False\r\n\r\n for page in range(1, max_page+1):\r\n\r\n # check number of scraped news\r\n if outdate:\r\n break\r\n\r\n links_all =[]\r\n url = search_url.format(page, title, lname, sangim, bill_result)\r\n soup = get_soup(url)\r\n sub_links = soup.find_all('tr')[1:]\r\n links = [i.find('a')['href'] for i in sub_links]\r\n links_all = ['http://watch.peoplepower21.org/?mid=LawInfo&'+url[29:] for url in links]\r\n\r\n dates = soup.find_all('tr')[1:]\r\n day = [d.find('td').text for d in dates]\r\n\r\n for i, url in enumerate(links_all):\r\n d_news = parse(day[i])\r\n if d_end < d_news:\r\n print('ignore scrapping. {} legistlation was scrapped'.format(d_news))\r\n print('The newest legistlation has been created after {}'.format(end_date))\r\n continue\r\n else:\r\n new_json = parse_legislate(url)\r\n new_json['date'] = day[i]\r\n # check date\r\n if new_json is not None:\r\n\r\n if d_begin > d_news:\r\n outdate = True\r\n print('Stop scrapping. {} / {} legistlation was scrapped'.format(n_news, max_page*100))\r\n print('The oldest legistlation has been created after {}'.format(begin_date))\r\n break\r\n else:\r\n yield new_json\r\n\r\n else:\r\n continue\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef gather_url(bill_result, max_page =10,end_date = '2019-12-01',begin_date= '2016-04-01', title = '', lname = '', sangim ='', sleep=1.0):\r\n \"\"\"\r\n Artuments\r\n ---------\r\n law_status : str\r\n eg. 2018-01-01\r\n max_num : int\r\n Maximum number of news to be scraped\r\n sleep : float\r\n Sleep time. Default 1.0 sec\r\n\r\n It yields\r\n ---------\r\n news : json object\r\n \"\"\"\r\n\r\n # prepare parameters\r\n\r\n d_begin = parse(begin_date)\r\n d_end = parse(end_date)\r\n end_page = 30\r\n n_news = 0\r\n outdate = False\r\n\r\n for page in range(0, max_page+1):\r\n\r\n # check number of scraped news\r\n if outdate:\r\n break\r\n\r\n links_all =[]\r\n url = search_url.format(page, title, lname, sangim, bill_result)\r\n soup = get_soup(url)\r\n sub_links = soup.find_all('tr')[1:]\r\n links = [i.find('a')['href'] for i in sub_links]\r\n links_all = ['http://watch.peoplepower21.org/?mid=LawInfo&'+url[29:] for url in links if is_matched(url)]\r\n return links_all\r\n","sub_path":"scraper/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"127545737","text":"# Default imports\nfrom greyatomlib.python_intermediate.q05_read_csv_data.build import read_ipl_data_csv\npath = 'data/ipl_matches_small.csv'\nimport numpy as np\n# Enter Code Here\n\ndef get_unique_matches_count():\n ipl_matches = np.genfromtxt(path,delimiter=\",\",dtype='|S50',skip_header=1)\n ipl_matches1 = ipl_matches[:,0]\n ipl_matches2 = np.unique(ipl_matches1)\n return ipl_matches2.size\n","sub_path":"q06_get_unique_matches_count/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"147820836","text":"import hazelcast\n\nfrom hazelcast import ClientConfig\nfrom hazelcast.serialization.api import Portable\n\n\nclass Customer(Portable):\n FACTORY_ID = 1\n CLASS_ID = 1\n\n def __init__(self, id=None, name=None, last_order=None):\n self.id = id\n self.name = name\n self.last_order = last_order\n\n def read_portable(self, object_data_input):\n self.id = object_data_input.read_int(\"id\")\n self.name = object_data_input.read_utf(\"name\")\n self.last_order = object_data_input.read_long(\"last_order\")\n\n def write_portable(self, object_data_output):\n object_data_output.write_int(\"id\", self.id)\n object_data_output.write_utf(\"name\", self.name)\n object_data_output.write_long(\"last_order\", self.last_order)\n\n def get_factory_id(self):\n return self.FACTORY_ID\n\n def get_class_id(self):\n return self.CLASS_ID\n\n\nif __name__ == \"__main__\":\n config = ClientConfig()\n my_factory = {Customer.CLASS_ID: Customer}\n config.serialization_config.add_portable_factory(Customer.FACTORY_ID, my_factory)\n # Start the Hazelcast Client and connect to an already running Hazelcast Cluster on 127.0.0.1\n hz = hazelcast.HazelcastClient(config)\n # Customer can be used here\n hz.shutdown()\n","sub_path":"examples/org-website/portable_serializable_sample.py","file_name":"portable_serializable_sample.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"542996601","text":"import dramatiq\nimport requests\nimport json\nimport uuid\nimport os\nimport shutil\nfrom compiler import Compiler\nfrom JudgeClient import JudgeClient\nfrom judger_config import TEST_CASE_DIR, JUDGER_WORKSPACE_BASE\n\nrunner_id = '00001'\ncompiler_config = {\n \"src_name\": \"main.c\",\n \"exe_name\": \"main\",\n \"max_cpu_time\": 3000,\n \"max_memory\": 512 * 1024 * 1024,\n \"compile_command\": \"/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 {src_path} -lm -o {exe_path}\",\n }\ncode = r\"\"\"\n #include \n int main(){\n int a, b;\n scanf(\"%d%d\", &a, &b);\n printf(\"%d\\n\", a+b);\n return 0;\n }\n \"\"\"\n\n\ndef clean_up(path):\n print(\"CLEANING UP \", path)\n shutil.rmtree(path)\n\n\nif __name__ == '__main__':\n print(code)\n runner_dir = os.path.join(JUDGER_WORKSPACE_BASE, runner_id)\n if os.path.exists(runner_dir):\n clean_up(runner_dir)\n os.makedirs(runner_dir)\n src_path = os.path.join(runner_dir, compiler_config['src_name'])\n with open(src_path, 'w', encoding='utf-8') as code_file:\n code_file.write(code)\n exe_path = Compiler.compile(compiler_config, src_path, runner_dir)\n print(exe_path)\n","sub_path":"compile_test.py","file_name":"compile_test.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"414277815","text":"import os\n\nos.environ[\"APP_SETTINGS\"] = \"config.DevelopmentConfig\"\n# v3 database\nos.environ[\"DATABASE_URL\"] = \"postgres://ddrxtxgazwxidu:1b200c6e68a289654b65d64542d36da338105c7b40a2dd335f4a42420584ecf0@ec2-52-21-153-207.compute-1.amazonaws.com:5432/d1hdtre41fscdn\"\n# v2 database\n# os.environ[\"DATABASE_URL\"] = \"postgres://bivxusanexnbjp:12f8e000800ba66e4f98d0df4795edc962bdfd5318cbd9f19c7eaf16ef244f54@ec2-52-23-45-36.compute-1.amazonaws.com:5432/dd46p10a83f3m0\"\n# os.environ[\"DATABASE_URL\"] = \"postgresql://changwei:w45039w45039@localhost/app_trial\"\nimport json\nfrom app.irsystem.models.eigenvector import eigenvector\nfrom app.irsystem.models.game import Game\nfrom app.irsystem.models.movie import Movie\nfrom app import db\n\nDATA_DIR = os.path.abspath(os.path.join(__file__, \"..\", \"..\", \"..\", \"data\"))\n\n# TODO\nLOCAL_DATA_DIR = os.path.abspath(os.path.join(\n __file__, \"..\", \"..\", \"..\", \"data\", 'pca_svd'))\n\nEIGENVECTORS_PCA_COLUMNS = \"game_movie_eigenvectors_column.json\"\nEIGENVECTORS_PCA_COLUMNS_RESHAPED = \"game_movie_eigenvectors_column_reshaped.json\"\nTOKEN_LST_BEFORE_PCA = \"token_list_before_pca.json\"\nDICT_TOKEN_TO_IDX_BEFORE_PCA = \"dict_token_to_id_before_pca.json\"\nMOVIE_VECTORS_PCA = \"dict_movieid_to_vector_pca.json\"\nGAME_VECTORS_PCA = \"dict_gameid_to_vector_pca.json\"\nGAME_INFO_FILENAME = 'game_info.json'\nMOVIE_INFO_FILENAME = \"movie_info.json\"\nGAME_INFO_FILENAME = \"game_info.json\"\nTOP3000_MOVIE_GAME_TITLE_SIMILARITY_FILENAME = \"top3000movie_game_title_similarity.json\"\nGAMES_TITLE_SIMILARITY_FILENAME = \"games_title_similarity.json\"\nMOVIE_NAME_FILENAME = \"movie_id_to_title.json\"\n\n\ndef init_db():\n # Create tables\n print(\"Create db tables...\")\n db.create_all()\n\n # Dump data\n\n with open(os.path.join(DATA_DIR, MOVIE_INFO_FILENAME), \"r\") as in_json_file:\n movie_info = json.load(in_json_file)\n with open(os.path.join(DATA_DIR, GAME_INFO_FILENAME), \"r\") as in_json_file:\n game_info = json.load(in_json_file)\n with open(os.path.join(LOCAL_DATA_DIR, EIGENVECTORS_PCA_COLUMNS),\n \"r\") as in_json_file:\n eigenvectors_pca = json.load(in_json_file)\n\n # eigenvectors_pca_reshaped reshapes eigenvectors_pca vector to fit into 1388 rows\n # Original vector dimension: 9716 x 2576\n # Reshaped dimension: 1388 x 7 x 2576\n # with open(os.path.join(LOCAL_DATA_DIR, EIGENVECTORS_PCA_COLUMNS_RESHAPED), \"r\") as in_json_file:\n # eigenvectors_pca_reshaped = json.load(in_json_file)\n with open(os.path.join(LOCAL_DATA_DIR, MOVIE_VECTORS_PCA),\n \"r\") as in_json_file:\n movie_vectors = json.load(in_json_file)\n with open(os.path.join(LOCAL_DATA_DIR, GAME_VECTORS_PCA),\n \"r\") as in_json_file:\n game_vectors = json.load(in_json_file)\n with open(os.path.join(DATA_DIR, TOP3000_MOVIE_GAME_TITLE_SIMILARITY_FILENAME),\n \"r\") as in_json_file:\n movie_game_title_sim = json.load(in_json_file)\n with open(os.path.join(DATA_DIR, GAMES_TITLE_SIMILARITY_FILENAME), 'r' ) as in_json_file:\n game_title_sim = json.load(in_json_file)\n with open(os.path.join(DATA_DIR, MOVIE_NAME_FILENAME), \"r\") as in_json_file:\n movie_titles = json.load(in_json_file)\n\n print(\"Dump movie data...\")\n for (link, info) in movie_info.items():\n db.session.add(Movie(\n link_id=str(link),\n name=str(movie_titles[link]),\n games_review_match=json.dumps(info['games']),\n games_title_match=json.dumps(movie_game_title_sim.get(link, [])),\n genre=json.dumps(info['genre']),\n desc_keywords=json.dumps(info['desc_keywords']),\n vector_pca=json.dumps(movie_vectors[link])\n ))\n\n print(\"Dump game data...\")\n for (appid, info) in game_info.items():\n if info['mature_content'] == 'true':\n mature_content = True\n else:\n mature_content = False\n single_player = False\n multi_player = False\n if 'single-player' in info['num_players']:\n single_player = True\n if 'multi-player' in info['num_players']:\n multi_player = True\n db.session.add(Game(\n app_id=str(appid),\n name=info['name'],\n developer=json.dumps(info['developer']),\n publisher=json.dumps(info['publisher']),\n tags=json.dumps(info['tags']),\n genre=json.dumps(info['genre']),\n single_player=single_player,\n multi_player=multi_player,\n rating=str(info['rating']),\n mature_content=mature_content,\n url=str(info['url']),\n desc_keywords=json.dumps(info['desc_keywords']),\n vector_pca=json.dumps(game_vectors[appid]),\n games_title_match=json.dumps(game_title_sim.get(appid, []))\n ))\n\n print(\"Dump basis eigenvectors...\")\n # for row, vectors in eigenvectors_pca_reshaped.items():\n # db.session.add(eigenvector(rn=row, vec=json.dumps(vectors)))\n db.session.add(eigenvector(rn=\"1\", vec=json.dumps(eigenvectors_pca)))\n\n print(\"Dump basis eigenvectors complete...\")\n\n db.session.commit()\n\n print(\"init_db done\")\n\n\ndef drop_db():\n print(\"Drop all db tables...\")\n db.session.remove()\n db.drop_all()\n\n\ndef modify_db():\n with open(os.path.join(DATA_DIR, MOVIE_INFO_FILENAME), \"r\") as in_json_file:\n movie_info = json.load(in_json_file)\n with open(os.path.join(DATA_DIR, GAME_INFO_FILENAME), \"r\") as in_json_file:\n game_info = json.load(in_json_file)\n with open(os.path.join(LOCAL_DATA_DIR, EIGENVECTORS_PCA_COLUMNS),\n \"r\") as in_json_file:\n eigenvectors_pca = json.load(in_json_file)\n with open(os.path.join(LOCAL_DATA_DIR, MOVIE_VECTORS_PCA),\n \"r\") as in_json_file:\n movie_vectors = json.load(in_json_file)\n with open(os.path.join(LOCAL_DATA_DIR, GAME_VECTORS_PCA),\n \"r\") as in_json_file:\n game_vectors = json.load(in_json_file)\n\n print(\"adding in movie vector...\")\n for key in movie_info.keys():\n thisMovie = Movie.query.filter_by(link_id=key)\n thisMovie.vector_pca = json.dumps(movie_vectors[key])\n db.session.commit()\n print(\"adding in movie vector complete...\")\n\n print(\"adding in game vector...\")\n for key in game_info.keys():\n thisGame = Game.query.filter_by(app_id=key)\n thisGame.vector_pca = json.dumps(game_vectors[key])\n db.session.commit()\n print(\"adding in game vector complete...\")\n\n print(\"adding in basis eigenvectors...\")\n db.session.add(eigenvector(rn=\"1\", vec=json.dumps(eigenvectors_pca)))\n db.session.commit()\n print(\"adding in movie vector complete...\")\n\n\ndef modify_title_similarity():\n print(\"updating similarity scores ...\")\n with open(os.path.join(DATA_DIR,\n TOP3000_MOVIE_GAME_TITLE_SIMILARITY_FILENAME),\n \"r\") as in_json_file:\n movie_game_sim = json.load(in_json_file)\n\n for link_id in movie_game_sim.keys():\n movie_obj: Movie = Movie.query.filter_by(link_id=link_id).first()\n movie_obj.games_title_match = json.dumps(movie_game_sim[link_id])\n db.session.commit()\n print(\"finish updating similarity scores ...\")\n\n\nif __name__ == '__main__':\n # drop_db()\n init_db()\n # modify_db()\n # modify_title_similarity()\n","sub_path":"app/irsystem/models/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":7309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"490359256","text":"import random\n\nfrom datetime import *\nfrom django.utils import timezone\n\nfrom login.models import *\n\n\nclass CrimeModel:\n name = \"\"\n succes = .0\n nothing = .0\n waitMinutes = 0\n timesJail = 1\n\n pointsBySucces = 0\n pointsByJail = -0\n\n def _getResultOnChange(self):\n rf = random.random()\n if rf < self.succes:\n return \"succes\"\n elif rf < self.succes + self.nothing:\n return \"nothing\"\n else:\n return \"jail\"\n\n def Execute(self, user):\n result = self._getResultOnChange()\n newdate = timezone.now() + timedelta(minutes=self.waitMinutes) if result in [\"succes\", \"nothing\"] else timezone.now() + timedelta(minutes=self.waitMinutes*self.timesJail)\n message = \"for the crime \" + self.name + \" the action result in: \" + result + \" you have to wait to: \" + newdate.strftime(\"%H:%M:%S\")\n WaitAction(message=(message), user=user, waitUntil=newdate).save()\n\n if result == \"succes\":\n ScoreTransaction.objects.create(user=user, score=self.pointsBySucces)\n elif result == \"jail\":\n ScoreTransaction.objects.create(user=user, score=self.pointsByJail)\n\n return message\n\n\nclass StealCar(CrimeModel):\n def __init__(self):\n self.name = \"steal a car\"\n self.succes = 0.3\n self.nothing = 0.4\n self.waitMinutes = 15\n self.timesJail = 4\n\n self.pointsBySucces = 50\n self.pointsByJail = -30\n\n\nclass RobBank(CrimeModel):\n def __init__(self):\n self.name = \"rob a bank\"\n self.succes = 0.2\n self.nothing = 0.2\n self.waitMinutes = 25\n self.timesJail = 6\n\n self.pointsBySucces = 5000\n self.pointsByJail = -500\n\nclass SmugglingDrugs(CrimeModel):\n def __init__(self):\n self.name = \"smuggling drugs\"\n self.succes = .4\n self.nothing = .4\n self.waitMinutes = 10\n self.timesJail = 6\n\n self.pointsBySucces = 3000\n self.pointsByJail = -300\n\n\nclass CrimesHelper:\n @staticmethod\n def getDefaultCrimes():\n return [StealCar(), RobBank(), SmugglingDrugs()]\n\n @staticmethod\n def getByName(name):\n return [x for x in CrimesHelper.getDefaultCrimes() if x.name == name][0]\n","sub_path":"MaffiaGame/Crimes/crimeModels.py","file_name":"crimeModels.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"509587063","text":"# /DP\n\nimport sys,time\nimport numpy as np\n\nsys.path.insert(0, '../lib/')\n\nfrom load import load_funcs_2\nfrom DP_lib import cost_itemnum, percentile, DP_click, DP, DP_sse, create_emptycount, wvec2prob, gs_prob, full, isexistclick\n\ndatapath1 = '../../data/'\ndatapath2 = '../../python_preprocess/code/data/data_range/aggregate/'\n\nloads = load_funcs_2(datapath1, datapath2)\n\nsuffix = sys.argv[1]\n\nbin_size = 5\nbin_num = 4000\nthisK = 100\n\ncount_vec = np.array([0.0] * bin_num)\n\nfin = open(datapath1 + 'count/clickcount_' + suffix + '.txt', 'r')\nfout = open(datapath1 + 'count/partitions_' + suffix + '.txt', 'w')\n\nfor i in range(0, bin_num):\n\tline = fin.readline()\n\ttokens = line.strip('\\r\\n').split('\\t')\n\tidx = int(tokens[0])\n\tcount = float(tokens[1])\n\tcount_vec[idx] = count\n\ncum_sqr_sum = np.array([0.0] * (bin_num + 1))\ncum_sum = np.array([0.0] * (bin_num + 1))\n\ncum_sqr_sum[0] = 0\ncum_sum[0] = 0\n\nfor i in range(1, (bin_num + 1)):\n\tcum_sqr_sum[i] = cum_sqr_sum[i-1] + count_vec[i - 1] * count_vec[i - 1]\n\tcum_sum[i] = cum_sum[i-1] + count_vec[i - 1]\n\npartitions = DP_sse(bin_num, thisK, cum_sqr_sum, cum_sum)\nfor i in range(0, len(partitions)):\n\tfout.write(str(partitions[i] * bin_size) + '\\r\\n')\n\t\nfout.close()","sub_path":"DP/DP_bucket.py","file_name":"DP_bucket.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"632906049","text":"x = input()\nt_dict = {s:i for i, s in enumerate(x)}\nn = int(input())\ns = [input() for _ in range(n)]\n\ndef sort_key(t_dict, string):\n i = 10\n ans = 0\n for s in string:\n ans += (t_dict[s]+1) * (27 ** i)\n i -= 1\n return ans\n\ns.sort(key=lambda x: sort_key(t_dict, x))\n[print(i) for i in s]\n","sub_path":"contest/abc219/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"131080267","text":"import pytest\nfrom datetime import timedelta\n\nfrom django.utils.timezone import now as tz_now\nfrom django.test.utils import override_settings\n\nfrom awx.main.models import AuthToken, User\n\n\n@override_settings(AUTH_TOKEN_PER_USER=3)\n@pytest.mark.django_db\ndef test_get_tokens_over_limit():\n now = tz_now()\n # Times are relative to now\n # (key, created on in seconds , expiration in seconds)\n test_data = [\n # a is implicitly expired\n (\"a\", -1000, -10),\n # b's are invalid due to session limit of 3\n (\"b\", -100, 60),\n (\"bb\", -100, 60),\n (\"c\", -90, 70),\n (\"d\", -80, 80),\n (\"e\", -70, 90),\n ]\n user = User.objects.create_superuser('admin', 'foo@bar.com', 'password')\n for key, t_create, t_expire in test_data:\n AuthToken.objects.create(\n user=user,\n key=key,\n request_hash='this_is_a_hash',\n created=now + timedelta(seconds=t_create),\n expires=now + timedelta(seconds=t_expire),\n )\n invalid_tokens = AuthToken.get_tokens_over_limit(user, now=now)\n invalid_keys = [x.key for x in invalid_tokens]\n assert len(invalid_keys) == 2\n assert 'b' in invalid_keys\n assert 'bb' in invalid_keys\n","sub_path":"awx/main/tests/functional/test_auth_token_limit.py","file_name":"test_auth_token_limit.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"339036437","text":"import numpy as np\nfrom . import containers, httping, utils, wrk\nfrom copy import deepcopy\nfrom docker import DockerClient\nfrom loguru import logger\nfrom pandas import DataFrame, ExcelWriter\nfrom yaml import load, Loader\nfrom click import command, argument, File\n\n\ndef expand_setup(setup, name):\n \"\"\"\n \n \"\"\"\n for section in setup.keys():\n for node in ['X', 'Y', 'Z']:\n if node not in setup[section]:\n logger.warning(f\"Node '{node}' missing in section '{section}'.\")\n\n # Only expand when multiple delays are specified for X.\n network = setup['network']\n x_delay = network['X']['delay']\n if type(network['X']['delay']) is not list:\n return [setup]\n\n length = len(x_delay)\n y_delay = utils.as_list_with_len(network['Y']['delay'], length)\n z_delay = utils.as_list_with_len(network['Z']['delay'], length)\n \n setups = []\n for delays in zip(x_delay, y_delay, z_delay):\n s = deepcopy(setup)\n s['network']['X']['delay'] = delays[0]\n s['network']['Y']['delay'] = delays[1]\n s['network']['Z']['delay'] = delays[2]\n\n setups.append(s)\n\n return setups\n \n\n@command()\n@argument(\"file\", type=File('rb'))\ndef main(file: File):\n utils.configure_loguru()\n dc = DockerClient.from_env()\n\n # Load benchmark matrix\n matrix = load(file, Loader=Loader)\n client = matrix['client']\n output = matrix['output']\n runs_per_setup = matrix['runs-per-setup']\n defaults = matrix['defaults']\n\n # Setup the Docker network.\n tc = containers.create_tc_container(dc)\n net = containers.create_network(dc)\n\n # Results are written at the end.\n xlsx_sheets = {}\n\n for setup in matrix['setups']:\n setup_name = list(setup.keys())[0]\n logger.info(f\"===== {setup_name} =====\")\n\n setup = utils.merge(defaults, setup[setup_name])\n setups = expand_setup(setup, setup_name)\n\n for setup in setups:\n variant_times = DataFrame()\n variant_name = utils.add_delay_postfix(setup_name, setup)\n runs = range(1, runs_per_setup+1)\n\n for r in runs:\n try:\n logger.info(f\"===== {variant_name} ({r}/{runs_per_setup}) =====\")\n y, z = (None, None)\n\n if 'Y' in setup['containers']:\n y = containers.create_container('Y', setup, net, dc)\n\n if 'Z' in setup['containers']:\n z = containers.create_container('Z', setup, net, dc)\n\n # An X node is mandatory.\n x = containers.create_container('X', setup, net, dc)\n \n # Capture stdout until X completes.\n logger.info(f\"Waiting for container '{x.name}' (X) to finish.\")\n stdout = []\n for line in x.attach(stream=True):\n stdout.append(line)\n\n # Process results\n logger.info(f\"Container '{x.name}' (X) finished. Processing results.\")\n \n if client == \"httping\":\n (times, stats) = httping.extract_httping_run_result(stdout)\n elif client == \"wrk\":\n (times, stats) = wrk.extract_wrk_run_result(stdout)\n \n variant_times[f'run{r}'] = times\n variant_times[f'run{r}-stats'] = stats\n \n # Always perform cleanup\n finally:\n if y is not None:\n y.kill()\n\n if z is not None:\n z.kill()\n\n # Calculate variant-wide stats\n variant_stats = np.zeros(min(len(variant_times['run1']), 4))\n combined = np.array([])\n means = np.zeros(runs_per_setup)\n for (i, r) in enumerate(runs):\n means[i] = variant_times[f'run{r}-stats'][1]\n combined = np.append(combined, variant_times[f'run{r}'])\n \n variant_stats[0] = means.mean()\n variant_stats[1] = means.std()\n variant_stats[2] = combined.mean()\n variant_stats[3] = combined.std()\n\n # Add variant-wide stats to variant sheet\n variant_times['stats'] = variant_stats\n xlsx_sheets[variant_name] = variant_times\n\n # Write output to file\n logger.info(\"Writing output\")\n with ExcelWriter(output) as w:\n for (name, df) in xlsx_sheets.items():\n df.to_excel(w, sheet_name=name)\n\n # Cleanup\n net.remove()\n tc.kill()\n\n\nif __name__ == '__main__':\n main()","sub_path":"proxy_bench/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":4706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"46137158","text":"from .base import *\n\nSECRET_KEY = 'wzq(el+esq1ywilp&(u^gki183#a$i*c!u92(sx6l8rp-b1l54'\nDEBUG = True\nTEMPLATE_DEBUG = True\nDATABASES = {\n 'default':{\n 'ENGINE':'django.db.backends.sqlite3',\n 'NAME':os.path.join(os.path.dirname(BASE_DIR), 'db.sqlite3'),\n }\n}\n","sub_path":"lunch/settings/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"606816597","text":"import os\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\nimport pickle\n\nprob1 = False\n\nif __name__ == '__main__':\n if prob1:\n with open(\"saved_rewards/batch32.pkl\", \"rb\") as handle32:\n batch32 = pickle.load(handle32)\n time_step, mean_batch32, best_batch32 = batch32[\"time\"], batch32[\"mean\"], batch32[\"best\"]\n fig = plt.figure()\n ax = fig.add_subplot(111)\n mean32, = ax.plot(time_step, mean_batch32, label=\"mean rew for batch size 32\")\n best32, = ax.plot(time_step, best_batch32, label=\"best rew for batch size 32\")\n ax.set_title(\"Performance with Default Setting\")\n ax.set_xlabel(\"time step\")\n ax.set_ylabel(\"episode reward\")\n ax.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.2g'))\n ax.legend(handles=[mean32, best32], loc=\"lower right\", prop={'size': 11})\n plt.show()\n else:\n # batch size = 8, 16, 32, 64\n with open(\"saved_rewards/batch8.pkl\", \"rb\") as handle8:\n batch8 = pickle.load(handle8)\n with open(\"saved_rewards/batch16.pkl\", \"rb\") as handle16:\n batch16 = pickle.load(handle16)\n with open(\"saved_rewards/batch32.pkl\", \"rb\") as handle32:\n batch32 = pickle.load(handle32)\n with open(\"saved_rewards/batch64.pkl\", \"rb\") as handle64:\n batch64 = pickle.load(handle64)\n\n time_step = batch32[\"time\"]\n mean_batch8, best_batch8 = batch8[\"mean\"], batch8[\"best\"]\n mean_batch16, best_batch16 = batch16[\"mean\"], batch16[\"best\"]\n mean_batch32, best_batch32 = batch32[\"mean\"], batch32[\"best\"]\n mean_batch64, best_batch64 = batch64[\"mean\"], batch64[\"best\"]\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n mean8, = ax.plot(time_step, mean_batch8, label=\"mean rew for batch size 8\")\n best8, = ax.plot(time_step, best_batch8, label=\"best rew for batch size 8\")\n mean16, = ax.plot(time_step, mean_batch16, label=\"mean rew for batch size 16\")\n best16, = ax.plot(time_step, best_batch16, label=\"best rew for batch size 16\")\n mean32, = ax.plot(time_step, mean_batch32, label=\"mean rew for batch size 32\")\n best32, = ax.plot(time_step, best_batch32, label=\"best rew for batch size 32\")\n mean64, = ax.plot(time_step, mean_batch64, label=\"mean rew for batch size 64\")\n best64, = ax.plot(time_step, best_batch64, label=\"best rew for batch size 64\")\n ax.set_title(\"Performance with Different Batch Size\")\n ax.set_xlabel(\"time step\")\n ax.set_ylabel(\"episode reward\")\n ax.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.2g'))\n lst = [mean8, best8, mean16, best16, mean32, best32, mean64, best64]\n ax.legend(handles=lst, loc=\"best\", prop={'size': 11})\n plt.show()\n\n","sub_path":"hw3/plot_rewards.py","file_name":"plot_rewards.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"623784376","text":"import sys\nimport logging\nimport re\n\nfrom django.http import HttpResponse, StreamingHttpResponse\n\nfrom .filesystem import FileWrapper\n\n\nCHUNK_SIZE = 2**15\n\nlogger = logging.getLogger(__name__)\n\n\ndef stream_file(filelike, filename, request, content_type):\n start, end = 0, None\n file_size = filelike.seek(0,2)\n\n if \"HTTP_RANGE\" in request.META:\n try:\n start, end = re.findall(r\"/d+\", request.META[\"HTTP_RANGE\"])\n except TypeError:\n logger.exception(\n \"Malformed HTTP_RANGE in download request: {}\"\n .format(request.META[\"HTTP_RANGE\"])\n )\n return HttpResponse(\n status=416\n )\n\n if start > end or end > file_size:\n return HttpResponse(\n status=416\n )\n\n fwrapper = FileWrapper(\n filelike,\n blksize=CHUNK_SIZE,\n start=start,\n end=end\n )\n response = StreamingHttpResponse(\n fwrapper,\n content_type=content_type,\n )\n response[\"Content-Disposition\"] = \\\n 'attachment; filename=\"' + filename + '\"'\n response[\"Content-Length\"] = file_size\n response[\"Accept-Ranges\"] = 'bytes'\n\n if \"HTTP_RANGE\" in request.META:\n response[\"status\"] = 206\n response[\"Content-Range\"] = \"bytes {}-{}/{}\".format(start,\n end,\n file_size)\n\n return response\n","sub_path":"snodas/utils/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"611739569","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 7 18:15:22 2018\n\n@author: js-wxyu\n\"\"\"\n\ndef isprime(n):\n for k in range(2,int(n**0.5)+1):\n if n%k==0:\n return False\n return True\nn=3\nnum=1\nwhile num<=10000:\n if isprime(n):\n num+=1\n n+=2\nprint(num,n-2)","sub_path":"Q7.py","file_name":"Q7.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"188365387","text":"\"\"\"\nUtils\n\"\"\"\nfrom typing import List, Callable\n\nimport time\nfrom tqdm import tqdm\n\n# pylint: disable=too-many-arguments,too-many-locals\n\n\ndef row_generator_from_paginated_calls(\n skip: int,\n first: int,\n count_method: Callable[..., int],\n count_kwargs: dict,\n paged_call_method: Callable[..., List[dict]],\n paged_call_payload: dict,\n fields: List[str],\n disable_tqdm: bool,\n):\n \"\"\"\n Builds a row generator from paginated calls.\n\n Parameters\n ----------\n - skip : int\n Number of assets to skip (they are ordered by their date of creation, first to last).\n - first : int\n Maximum number of assets to return.\n - count_method: ... -> int\n Callable returning the number of available assets given `count_args`.\n - count_kwargs: dict\n Keyword arguments passed to the `count_method`.\n - paged_call_method: ... -> List[dict]\n Callable returning the list of samples.\n - paged_call_payload: dict\n Payload for the GraphQL query.\n - fields: List[str]\n The list of strings to retrieved.\n - disable_tqdm: bool\n If `True`, disables tqdm.\n \"\"\"\n count_rows_retrieved = 0\n if not disable_tqdm:\n count_rows_available = count_method(**count_kwargs)\n count_rows_queried_total = min(count_rows_available,\n first) if first is not None else count_rows_available\n else:\n # dummy value that won't have any impact since tqdm is disabled\n count_rows_queried_total = 1 if first != 0 else 0\n count_rows_query_default = min(100, first or 100)\n throttling_delay = 60 / 250\n\n if count_rows_queried_total == 0:\n yield from ()\n else:\n with tqdm(total=count_rows_queried_total, disable=disable_tqdm) as pbar:\n while True:\n query_start = time.time()\n rows = paged_call_method(\n count_rows_retrieved + skip,\n count_rows_query_default,\n paged_call_payload,\n fields,\n )\n query_time = time.time() - query_start\n\n if query_time < throttling_delay:\n time.sleep(throttling_delay - query_time)\n\n if rows is None or len(rows) == 0:\n break\n\n for row in rows:\n yield row\n\n count_rows_retrieved += len(rows)\n pbar.update(len(rows))\n if first is not None and count_rows_retrieved >= first:\n break\n","sub_path":"kili/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"517065885","text":"from setuptools import setup, find_packages\n\n\nwith open(\"README.md\", \"r\") as f:\n long_description = f.read()\n\nsetup(\n name=\"vvvvid-downloader\",\n version=\"1.1.0\",\n author=\"Nearata\",\n author_email=\"williamdicicco@protonmail.com\",\n description=\"Uno script in Python che permette di scaricare facilmente i video da VVVVID.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/nearata/vvvvid-downloader\",\n packages=find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.8\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Intended Audience :: End Users/Desktop\",\n \"Natural Language :: Italian\",\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: Console\"\n ],\n python_requires=\">=3.8\",\n install_requires=[\n \"requests==2.24.0\",\n \"inquirer==2.7.0\",\n \"colorama==0.4.3\"\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"505606403","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n#\nimport sys\nimport os\nimport MeCab\nimport numpy as np\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.cluster import KMeans\n\nDIRS = ['dokujo-tsushin', 'movie-enter', 'it-life-hack']\ntagger = MeCab.Tagger(\"-Ochasen\")\n\n\ndef mecab_tokenizer(text):\n word_list = list()\n node = tagger.parseToNode(text)\n while node:\n if node.surface != \"\":\n res = node.feature.split(\",\")\n if node.surface not in ['(', ')', '-', '+', '\"'] and \\\n res[0] in [\"名詞\", \"動詞\", \"形容詞\", \"副詞\"] and \\\n res[1] not in [\"数\", '記号', '非自立', '接尾']:\n basic_word = res[6] if res[6] != \"*\" else node.surface\n word_list.append(basic_word)\n\n node = node.next\n return word_list\n\n\ndef main():\n # 単なる単語頻度によるベクトル化\n vectorizer = CountVectorizer(tokenizer=mecab_tokenizer)\n\n # tf-idfベクトル化変数(正規化はL2, tfにlogを用いる)\n # vectorizer = TfidfVectorizer(norm='l2', sublinear_tf=True,\n # tokenizer=mecab_tokenizer)\n\n text_list = []\n id_list = []\n for d in DIRS:\n # ファイルリストから'LICENSE.txt'を除く\n files = [f for f in os.listdir(\"text/\" + d) if f != 'LICENSE.txt']\n # カテゴリごとに10ファイルずつ\n for fi in files[:10]:\n with open('text/{}/{}'.format(d, fi)) as f:\n lines = f.readlines()\n text_list.append(\"\".join(lines[3:]))\n id_list.append(fi.split('.')[0])\n\n # テキストデータのベクトル化\n weighted_matrix = vectorizer.fit_transform(text_list)\n\n # ベクトル情報を確認\n print(\"テキスト数:%d,単語の種類数:%d\" % weighted_matrix.shape)\n\n # k-meansの実行\n cluster = KMeans(n_clusters=3).fit_predict(weighted_matrix)\n\n ## 出力用のデータ編集\n index = weighted_matrix.toarray().argsort(axis=1)[:, ::-1]\n features = np.array(vectorizer.get_feature_names())\n feature_words = features[index]\n\n # 出力単語の数\n num_words = 5\n print(\"クラスタ\\tファイル名\\ttf-idf値の高���単語\")\n for cl, name, fwords in zip(cluster, id_list, feature_words[:, :num_words]):\n print(\"{}\\t{}\\t{}\".format(cl, name, fwords))\n\n\nif __name__ == '__main__':\n main()","sub_path":"practice_5/k-means.py","file_name":"k-means.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"363581598","text":"import requests\nfrom pyquery import PyQuery as pq\nfrom urllib.parse import urlparse\nimport multiprocessing\nimport csv\nimport time\n\n\nhearders = {\n\t'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',\n\t}\na_url = ['baidu', 'news', 'sike', 'qq', 'hao123', 'sport', 'sina', 'worldbank', \n'tuniu', 'liepin', '163', 'org', 'gov', 'net', '666c', 'eastmoney', 'fashion', \n'hotel', 'bbs', 'job', 'people', 'money', 'unionpay', 'ticket', 'ali', 'dujia', 'miss', 'voc', 'sohu', 'pingan', '.cn',\n'jmw', 'home', 'panjk', 'admaimai', 'zxart', 'gongjiao', 'jiancai', 'blog', '.tw', 'liebiao', '51sole', '591hx', '17house', 'space',\n'site', '.ltd', 'dream', 'java', 'sonhoo', 'zhaoshang100', 'chn0769', 'taobao', 'live', '360', 'gx211', 'huangye88', '554757', 'china', 'city', 'chat',\n'agent', 'zhuangyi', 'b2b', '99cfw', 'cnjy', 'game', 'ci123', 'house', 'bao315', 'xyj321', 'fenlei', 'mgd', 'kugou', 'bizhi', 'e2say', '54086', 'qy39', 'xyj321', '7999',\n'jixiexinxi', '.xyz', 'info', 'car', 'uc', 'shop', 'lin', 'xg557', 'xg67', 'club', '.st']\n\nb_url = ['.jpg', '.html', '.png', '.htm', '.php'\n]\n\n\n\ndef get_data(url):\n\ttry:\n\t\tres = requests.get(url, headers=hearders, timeout=5)\n\texcept:\n\t\tpass\n\telse:\n\t\tif res.status_code == 200:\n\t\t\tres.encoding = res.apparent_encoding\n\t\t\treturn res.text\n\n\ndef parse_data(url, html, l, d, n):\n\tdoc = pq(html)\n\taes = doc('a').items()\n\tlist_link = []\n\tfor a in aes:\n\t\tif ' %s\" %(gpp_trade, fa_trade))\n if not fa_trade:\n missing_trades[base_name].append(file_obj.line_to_row(line))\n \n for fn, lines in missing_trades.items():\n LOGGER.error(\"Missing GPP trades from: '%s'\", fn)\n for row in lines:\n print(row[1])\n \n if out_file: # output report is not mandatory\n with open(out_file, \"wb\") as csv_out_file:\n writer = csv.writer(csv_out_file)\n writer.writerow(ColumnIndexer.get_headers())\n for fn, lines in missing_trades.items():\n for row in lines:\n writer.writerow(row)\n LOGGER.info(\"Wrote output to: '%s'\", out_file)\n \n if LOGGER.msg_tracker.errors_counter:\n raise RuntimeError(\"ERRORS occurred. Please check the log.\")\n \n LOGGER.info(\"Completed successfully.\")\n \n","sub_path":"Python modules/pb_gpp_recon_trades.py","file_name":"pb_gpp_recon_trades.py","file_ext":"py","file_size_in_byte":6923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"521659381","text":"from .models import Message, Chat\nfrom rest_framework import serializers\nfrom users.serializers import UserSerializer\n\n\nclass MessageSerializer(serializers.ModelSerializer):\n user = UserSerializer(fields=('id', 'first_name'), read_only=True)\n\n class Meta:\n model = Message\n fields = ('id', 'user', 'date', 'message')\n\n\nclass ChatAbstractSerializer(serializers.ModelSerializer):\n users = UserSerializer(fields=('id', 'first_name'), read_only=True, many=True)\n last_message = MessageSerializer(read_only=True)\n title = serializers.SerializerMethodField(read_only=True)\n is_unread = serializers.SerializerMethodField(read_only=True)\n\n class Meta:\n model = Chat\n fields = ('id', 'title', 'date', 'users', 'last_message', 'is_unread')\n\n def get_title(self, obj):\n user_request_id = self.context['request'].user.id\n chat_user = obj.users.exclude(pk=user_request_id).first()\n if chat_user:\n return chat_user.first_name\n else:\n return None\n\n def get_is_unread(self, obj):\n return obj.unread.filter(user=self.context['request'].user).exists()\n\n\nclass ChatSerializer(ChatAbstractSerializer):\n\n class Meta:\n model = Chat\n fields = ('id', 'title', 'users')\n\n\nclass ChatListSerializer(ChatAbstractSerializer):\n\n class Meta:\n model = Chat\n fields = ('id', 'title', 'users', 'last_message', 'is_unread')\n","sub_path":"react_chat/apps/chats/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"522508123","text":"#!/usr/bin/python\n\nfrom random import randint\n\nglobal counter\n\ndef swap(x,i,j):\n x[i],x[j]=x[j],x[i]\n\ndef pivotFirst(x,lmark,rmark):\n pivot_val=x[lmark]\n pivot_idx=lmark\n while lmark<=rmark:\n while lmark <= rmark and x[lmark]<=pivot_val:\n lmark+=1\n while lmark <=rmark and x[rmark] >=pivot_val:\n rmark -=1\n if lmark <= rmark:\n swap(x,lmark,rmark)\n lmark+=1\n rmark-=1\n swap(x,pivot_idx,rmark)\n return rmark\n\ndef quickSort(x,pivotMethod=pivotFirst):\n def _qsort(x,first,last): #왼쪽 인덱스:first 오른쪽 인덱스 :last\n if first < last:\n splitpoint=pivotMethod(x,first,last)\n _qsort(x,first,splitpoint-1)\n _qsort(x,splitpoint+1,last)\n _qsort(x,0,len(x)-1)\n\ndef binary_search(a_list,wanted_data):\n global counter\n first=0\n las=len(a_list)-1\n\n while first <= last:\n idx=(first+last) //2\n counter+=1\n if a_list[idx] ==wanted_data:\n print('{item} found at position {i}'.format(item=wanted_data,i=idx))\n return True\n elif a_list[idx]>wanted_data:\n last=idx -1\n elif a_list[idx]>wanted_data:\n first =idx+1\n else:\n print('{item} not found in the list'.format(item=wanted_data))\n return False\ndef binary_search_recursive(a_list,wanted_data):\n global counter\n first=0\n last=len(a_list)-1\n\n if len(a_list)==0:\n print('{item} not found in the list'.format(item=wanted_data))\n return False\n else:\n idx=(first+last)//2\n counter+=1\n if wanted_data==a_list[idx]:\n print('{item} found at position {i}'.format(item=wanted_data, i=idx))\n return True\n else:\n if a_list[idx]< wanted_data:\n return binary_search_recursive(a_list[idx+1:],wanted_data)\n else:\n return binary_search_recursive(a_list[:idx], wanted_data)\n\nif __name__=='__main__':\n data=[]\n counter=0\n input_n = input(\"The number of data :\")\n data =[randint(1,100) for x in range (int(input_n))]\n\n print(\"\")\n print(data)\n\n quickSort(data)\n\n print(\"\")\n print(data)\n\n msg=binary_search_recursive(data,50)\n if msg==True:\n print(\"Compare {} times to search 50\".format(counter))\n\n","sub_path":"concepts/BinarySearch.py","file_name":"BinarySearch.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"343709335","text":"# Author:Zhang Yuan\nimport MyPackage\n\n\n__mypath__ = MyPackage.MyClass_Path.MyClass_Path() #路径类\nmyfile = MyPackage.MyClass_File.MyClass_File() #文件操作类\n\n# MyPackage_PathList = __mypath__.GetMyPackagePath()\nMyPackage_PathList = [\"C:\\\\Users\\\\i2011\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python37\\\\lib\\\\site-packages\\\\MyPackage\"]\n\n# ---备份到桌面\nmyfile.ZipDir(MyPackage_PathList[0], zipPath=\"Desktop\" , zipName=None, autoName=True)\n\n# ---备份到OneDrive的Work-Python备份文件夹\nZipPath = __mypath__.GetOneDrivePath() + \"\\\\Work-Python备份\"\nmyfile.ZipDir(MyPackage_PathList[0], zipPath=ZipPath , zipName=None, autoName=True)\n\n\n\n","sub_path":"My_Python_Items/AutoMyPackageZip.py","file_name":"AutoMyPackageZip.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"556598621","text":"\n\"\"\"\nERROR DEFINITION:\n\n1000-1999 Request Errors\n2000-2999 Account Errors\n\"\"\"\n\n\nclass ApplicationException(Exception):\n \"\"\"Base error class for application.\n code - A numeric code identifying the error for external use\n internal_code - A numeric code identifying the error for internal use\n message - A human-friendly description of the error suitable to display to users.\"\"\"\n\n def __init__(self, code, status_code, msg):\n self.code = code\n self.msg = msg\n self.status_code = status_code\n\n def __str__(self):\n return \"[PROFILE-%s] STATUS=%s MESSAGE=%s\" % (self.code, self.status_code, self.msg)\n\n\nclass GeneralException(ApplicationException):\n CODE = 1000\n STATUS_CODE = 500\n TEXT = 'General Exception: %s'\n\n def __init__(self, error='unknown'):\n new_msg = self.TEXT % (type(error).__name__)\n new_msg = \"%s %s\" % (new_msg, str(error)) \n ApplicationException.__init__(self, self.CODE, self.STATUS_CODE, new_msg)\n\n\nclass InvalidRequestException(GeneralException):\n CODE = 1001\n STATUS_CODE = 400\n TEXT = 'Invalid request: %s'\n\n\n","sub_path":"project/infection/common/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"184722803","text":"# Determine if one string is permutation of the other\n\ndef check_permutation(str1, str2):\n if len(str1) != len(str2):\n return False\n \n occur = dict()\n\n for c in str1:\n occur[c] = occur.get(c,0) + 1\n \n for c in str2:\n if occur.get(c, 0) == 0:\n return False\n else:\n occur[c] = occur.get(c) - 1\n \n return True\n\nprint(check_permutation(\"ameen\", \"neema\")) # true\nprint(check_permutation(\"ameen\", \"notme\")) # false","sub_path":"1. Strings/1.2 check_permutations.py","file_name":"1.2 check_permutations.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"298577697","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# author: kcc time:2020/1/16\n\nimport socket,time\n\n# TCP服务器\n\n# 1.创建套接字\nserver = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\n# 2.绑定端口号\nip = \"0.0.0.0\"\nport = 7330\nserver.bind((ip,port))\n\n# 监听端口,最大连接数128\nserver.listen(128)\n\n# 阻塞等待连接着发送数据,收到一个请求时\n# 返回一个新的套接字,和请求客户端的地址\nprint(\"-----等待客户端连接------\")\nclient_socket,clientAddr = server.accept()\nprint(\"已有客户端连接,连接地址是:{}\".format(clientAddr))\n\n# 阻塞等待客户端发送数据\nrecvdata = client_socket.recv(1024)\nprint(recvdata.decode(\"gbk\"))\n\nclient_socket.send(\"nihao\".encode(\"utf8\"))\n\n","sub_path":"自研究/网络编程/tcp服务器.py","file_name":"tcp服务器.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"565449732","text":"#!/usr/bin/env python3\n\nimport sys\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\n\ndef generator(file_name):\n for line in open(file_name, 'r'):\n yield tuple(map(float, line.split()))\n\ndef to_list(file_name):\n return list(map(list, zip(*generator(file_name))))\n\n\nlabel = ['IBM-M1', 'IBM-M2', 'IBM-M2-Rand(1)', 'IBM-M2-Rand(2)', 'IBM-M2-Rand(3)', 'IBM-M2-Uniform', 'IBM-M1-AddN', 'IBM-M1-SmoothHeavyNull', 'IBM-M1-AllImprove']\ncolor = ['red', 'green', 'blue', 'black', 'yellow', 'orange', 'pink', 'grey', 'cyan']\nperplexity = to_list(sys.argv[1])\nlikelihood = to_list(sys.argv[2])\nrecall = to_list(sys.argv[3])\nprecision = to_list(sys.argv[4])\naer = to_list(sys.argv[5])\nprint(len(aer), len(precision), len(recall), len(likelihood), len(perplexity))\n\niterations = [i for i in range(1, len(perplexity[0]) + 1)]\n \n\nwith PdfPages('perplexity_' + sys.argv[-1]) as pdf:\n fig, ax = plt.subplots()\n for perplexity_config, color_config, label_config in zip(perplexity, color, label):\n ax.plot(iterations, perplexity_config, color=color_config, label=label_config)\n plt.xlabel('Iteration')\n plt.ylabel('Perplexity')\n\n legend = ax.legend(loc='upper right', ncol=2, shadow=True, prop={'size':9})\n\n plt.grid(True)\n plt.figure(figsize=(8, 6))\n pdf.savefig(fig)\n plt.close()\n\nwith PdfPages('likelihood_' + sys.argv[-1]) as pdf:\n fig, ax = plt.subplots()\n for likelihood_config, color_config, label_config in zip(likelihood, color, label):\n ax.plot(iterations, likelihood_config, color=color_config, label=label_config)\n plt.xlabel('Iteration')\n plt.ylabel('Log-Likelihood')\n\n legend = ax.legend(loc='lower right', ncol=2, shadow=True, prop={'size':9})\n\n plt.grid(True)\n plt.figure(figsize=(8, 6))\n pdf.savefig(fig)\n plt.close()\n\nwith PdfPages('recall_' + sys.argv[-1]) as pdf:\n fig, ax = plt.subplots()\n for recall_config, color_config, label_config in zip(recall, color, label):\n ax.plot(iterations, recall_config, color=color_config, label=label_config)\n plt.xlabel('Iteration')\n plt.ylabel('Recall')\n\n legend = ax.legend(loc='lower right', ncol=2, shadow=True, prop={'size':9})\n\n plt.grid(True)\n plt.figure(figsize=(8, 6))\n pdf.savefig(fig)\n plt.close()\n\nwith PdfPages('precision_' + sys.argv[-1]) as pdf:\n fig, ax = plt.subplots()\n for precision_config, color_config, label_config in zip(precision, color, label):\n ax.plot(iterations, precision_config, color=color_config, label=label_config)\n plt.xlabel('Iteration')\n plt.ylabel('Precision')\n\n legend = ax.legend(loc='lower right', ncol=2, shadow=True, prop={'size':9})\n\n\n plt.grid(True)\n plt.figure(figsize=(8, 6))\n pdf.savefig(fig)\n plt.close()\n\nwith PdfPages('aer_' + sys.argv[-1]) as pdf:\n fig, ax = plt.subplots()\n for aer_config, color_config, label_config in zip(aer, color, label):\n ax.plot(iterations, aer_config, color=color_config, label=label_config)\n plt.xlabel('Iteration')\n plt.ylabel('AER')\n\n legend = ax.legend(loc='center right', ncol=2, shadow=True, prop={'size':9})\n\n plt.grid(True)\n plt.figure(figsize=(8, 6))\n pdf.savefig(fig)\n plt.close()\n","sub_path":"Assignment1/logs_25000/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":3225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"585340661","text":"import operator\nimport numpy as np\n\nfrom .utils import Base, ppm_error, range\n\n\nclass FittedPeak(Base):\n\n __slots__ = [\n \"mz\", \"intensity\", \"signal_to_noise\", \"peak_count\",\n \"index\", \"full_width_at_half_max\", \"area\",\n \"left_width\", \"right_width\"\n ]\n\n def __init__(self, mz, intensity, signal_to_noise, peak_count, index, full_width_at_half_max, area,\n left_width=0, right_width=0):\n self.mz = mz\n self.intensity = intensity\n self.signal_to_noise = signal_to_noise\n self.peak_count = peak_count\n self.index = index\n self.full_width_at_half_max = full_width_at_half_max\n self.area = area\n self.left_width = left_width\n self.right_width = right_width\n\n def clone(self):\n return FittedPeak(self.mz, self.intensity, self.signal_to_noise,\n self.peak_count, self.index, self.full_width_at_half_max,\n self.area, self.left_width, self.right_width)\n\n def __reduce__(self):\n return self.__class__, (self.mz, self.intensity, self.signal_to_noise,\n self.peak_count, self.index, self.full_width_at_half_max,\n self.area, self.left_width, self.right_width)\n\n def __hash__(self):\n return hash((self.mz, self.intensity, self.signal_to_noise, self.full_width_at_half_max))\n\n def __eq__(self, other):\n if other is None:\n return False\n return (abs(self.mz - other.mz) < 1e-5) and (\n abs(self.intensity - other.intensity) < 1e-5) and (\n abs(self.signal_to_noise - other.signal_to_noise) < 1e-5) and (\n abs(self.full_width_at_half_max - other.full_width_at_half_max) < 1e-5)\n\n def __ne__(self, other):\n return not (self == other)\n\n\ndef _get_nearest_peak(peaklist, mz):\n lo = 0\n hi = len(peaklist)\n\n tol = 1\n\n def sweep(lo, hi):\n best_error = float('inf')\n best_index = None\n for i in range(hi - lo):\n i += lo\n v = peaklist[i].mz\n err = abs(v - mz)\n if err < best_error:\n best_error = err\n best_index = i\n return peaklist[best_index], best_error\n\n def binsearch(lo, hi):\n if (hi - lo) < 5:\n return sweep(lo, hi)\n else:\n mid = (hi + lo) / 2\n v = peaklist[mid].mz\n if abs(v - mz) < tol:\n return sweep(lo, hi)\n elif v > mz:\n return binsearch(lo, mid)\n else:\n return binsearch(mid, hi)\n return binsearch(lo, hi)\n\n\nclass PeakSet(Base):\n def __init__(self, peaks):\n self.peaks = tuple(peaks)\n\n def __len__(self):\n return len(self.peaks)\n\n def reindex(self):\n self._index()\n\n def _index(self):\n self.peaks = sorted(self.peaks, key=operator.attrgetter('mz'))\n i = 0\n for i, peak in enumerate(self.peaks):\n peak.peak_count = i\n if peak.index == -1:\n peak.index = i\n return i\n\n def has_peak(self, mz, tolerance=1e-5):\n return binary_search(self.peaks, mz, tolerance)\n\n get_nearest_peak = _get_nearest_peak\n\n def __repr__(self):\n return \"\" % (len(self))\n\n def __getitem__(self, item):\n if isinstance(item, slice):\n return PeakSet(self.peaks[item])\n return self.peaks[item]\n\n def clone(self):\n return PeakSet(p.clone() for p in self)\n\n def between(self, m1, m2, tolerance=1e-5):\n p1, _ = self.get_nearest_peak(m1)\n p2, _ = self.get_nearest_peak(m2)\n\n return self[p1.peak_count - 1:p2.peak_count + 1]\n\n\ndef _sweep_solution(array, value, lo, hi, tolerance, verbose=False):\n best_index = -1\n best_error = float('inf')\n best_intensity = 0\n for i in range(hi - lo):\n target = array[lo + i]\n error = ppm_error(value, target.mz)\n abs_error = abs(error)\n if abs_error < tolerance and (abs_error < best_error * 1.1) and (target.intensity > best_intensity):\n best_index = lo + i\n best_error = abs_error\n best_intensity = target.intensity\n if best_index == -1:\n return None\n else:\n return array[best_index]\n\n\ndef _binary_search(array, value, lo, hi, tolerance, verbose=False):\n if (hi - lo) < 5:\n return _sweep_solution(array, value, lo, hi, tolerance, verbose)\n else:\n mid = (hi + lo) // 2\n target = array[mid]\n target_value = target.mz\n error = ppm_error(value, target_value)\n\n if abs(error) <= tolerance:\n return _sweep_solution(array, value, max(mid - (mid if mid < 5 else 5), lo), min(\n mid + 5, hi), tolerance, verbose)\n elif target_value > value:\n return _binary_search(array, value, lo, mid, tolerance, verbose)\n elif target_value < value:\n return _binary_search(array, value, mid, hi, tolerance, verbose)\n raise Exception(\"No recursion found!\")\n\n\ndef binary_search(array, value, tolerance=2e-5, verbose=False):\n size = len(array)\n if size == 0:\n return None\n return _binary_search(array, value, 0, size, tolerance, verbose)\n\n\ntry:\n _FittedPeak = FittedPeak\n _PeakSet = PeakSet\n _p_binary_search = binary_search\n from ._c.peak_set import FittedPeak, PeakSet\nexcept ImportError:\n pass\n\n\ndef to_array(peak_set):\n array = np.zeros((len(peak_set), 6))\n array[:, 0] = [p.mz for p in peak_set]\n array[:, 1] = [p.intensity for p in peak_set]\n array[:, 2] = [p.signal_to_noise for p in peak_set]\n array[:, 3] = [p.full_width_at_half_max for p in peak_set]\n array[:, 4] = [p.index for p in peak_set]\n array[:, 5] = [p.peak_count for p in peak_set]\n return array\n","sub_path":"ms_peak_picker/peak_set.py","file_name":"peak_set.py","file_ext":"py","file_size_in_byte":5843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"184942245","text":"from PyQt5 import QtWidgets\nfrom PyQt5.QtWidgets import QMainWindow\nfrom ApiHandler import ApiHandler\n\n\nclass GuiWindow(QMainWindow):\n def __init__(self):\n super(GuiWindow, self).__init__()\n self.setGeometry(200, 200, 500, 500)\n self.setWindowTitle(\"Weather Check\")\n self.initUI()\n\n def initUI(self):\n self.labelTemp = QtWidgets.QLabel(self)\n self.labelTemp.setText(\"Temp: \")\n self.labelTemp.move(50, 150)\n\n self.labelTempShow = QtWidgets.QLabel(self)\n self.labelTempShow.move(100, 150)\n\n self.labelTempMin = QtWidgets.QLabel(self)\n self.labelTempMin.setText(\"Temp min: \")\n self.labelTempMin.move(50, 200)\n\n self.labelTempMinShow = QtWidgets.QLabel(self)\n self.labelTempMinShow.move(100, 200)\n\n self.labelTempMax = QtWidgets.QLabel(self)\n self.labelTempMax.setText(\"Temp max: \")\n self.labelTempMax.move(50, 250)\n\n self.labelTempMaxShow = QtWidgets.QLabel(self)\n self.labelTempMaxShow.move(100, 250)\n\n self.labelWeatherDescription = QtWidgets.QLabel(self)\n self.labelWeatherDescription.setText(\"Warunki pogodowe: \")\n self.labelWeatherDescription.move(150, 150)\n\n self.labelWeatherDescriptionShow = QtWidgets.QLabel(self)\n self.labelWeatherDescriptionShow.move(250, 150)\n\n self.button = QtWidgets.QPushButton(self)\n self.button.setText(\"Sprawdz\")\n self.button.move(200, 100)\n self.button.clicked.connect(self.clicked)\n\n self.inputCity = QtWidgets.QLineEdit(self)\n self.inputCity.move(50, 100)\n\n def clicked(self):\n cityInput = self.inputCity.text()\n apiHandler = ApiHandler(str(cityInput))\n apiHandler.request()\n self.labelTempShow.setText(str(round(apiHandler.temp - 273.15)))\n self.labelTempMinShow.setText(str(round(apiHandler.tempMin - 273.15)))\n self.labelTempMaxShow.setText(str(round(apiHandler.tempMax - 273.15)))\n self.labelWeatherDescriptionShow.setText(str(apiHandler.weatherDescription))\n\n","sub_path":"GuiWindow.py","file_name":"GuiWindow.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"230662121","text":"from xml.etree import ElementTree\n\net = ElementTree.parse('stations.xml') # or parse(filename_or_file)\nfor lng in et.iter('lng'):\n newLNG = float(lng.text)/1000000\n lng.text = str(newLNG)\n\nfor lat in et.iter('lat'):\n newLAT = float(lat.text)/1000000\n lat.text = str(newLAT)\n\net.write('stations_updated.xml')\n","sub_path":"scripts_parsing/parseXMLLAT.py","file_name":"parseXMLLAT.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"193492883","text":"# -*- coding: utf-8 -*-\n'''\nBuilds a Vega grammar specification from vincent.Area()\n'''\n\nimport vincent\nimport random\n\nvis = vincent.Area()\nvis.tabular_data([random.randint(10, 100) for x in range(0, 16, 1)])\nvis.axis_label(x_label='X Axis Label', y_label='Y Axis Label', title='Title')\n\n#Generate both the Vega JSON and a data JSON. \npath = r'vega.json'\nvis.to_json(path, split_data=True, html=True)\n\n#Lets add a data interpolation parameter and resave the JSON\nvis += ({'value': 'monotone'}, 'marks', 0, 'properties', 'enter', 'interpolate')\nvis.to_json(path, split_data=True, html=True)","sub_path":"examples/vincent_area.py","file_name":"vincent_area.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"299783085","text":"#Create a 3x3 matrix with values ranging from 0 to 8.\nimport numpy as np\nnp.arange(9).reshape(3,3)\n\n#Create a random array of size 10 and sort it\nx=np.random.random(10)\nnp.sort(x)\n\n#Remove from one array those items that exist in another For example, a1 = [1, 2, 3], a2 = [1, 3] --> result = [2]\na1=np.array([1, 2, 3])\na2=np.array([1,3])\nnp.setdiff1d(a1,a2)\n\n#Get the positions where elements of two arrays match For example, a1 = [1, 2, 3, 10], a2 = [5, 4, 3, 10] --> result = [2, 3]\na1=np.array([1,2,3,10])\na2=np.array([5,4,3,10])\nnp.intersect1d(a1,a2)\n\n#Replace \"Michael\" with \"Mike\" in x x = np.array(['Hello name is Michael'], dtype=np.str)\nx = np.array(['Hello name is Michael'], dtype=np.str)\nx[0].replace(\"Michael\",\"Mike\")\n\n#Lex x be an array [[ 1, 2],[ 3, 4]] Rotate x 90 degrees counter-clockwise. expected result = [[3, 1], [4, 2]]\nx=np.array([[1,2],\n [3,4]])\nnp.rot90(x,-1)\n","sub_path":"summer-bootcamp/week1-intro/homework/{%github-liuwei}/week2-homework-Numpy.py","file_name":"week2-homework-Numpy.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"387843271","text":"import pyaudio\nimport numpy as np\nfrom Tkinter import *\n\np = pyaudio.PyAudio()\n\n\nclass Soundgenerator(object):\n\tdef __init__(self, master):\n\t\tself.master = master\n\t\tmaster.title(\"VINAYA TECHNOLOGIES\")\n\t\tself.initialising(master)\n\t\n\tdef initialising(self, master):\n\t\tself.entryVar_freq_box = DoubleVar()\n\t\tself.entryVar_samp_freq = IntVar()\n\t\tself.entryVar_duration = DoubleVar()\n\t\tself.entryVar_volume = DoubleVar()\n\t\t\n\t\tself.label_title = Label(master, text=\"FREQUENCY GENERATOR\", font = \"-weight bold\").grid(row=0, column=0, columnspan =2)\n\t\tself.label_freq_box = Label(master, text=\"FREQUENCY OF THE WAVE (Hz)\").grid(row=1, column=0)\n\t\tself.entry_freq_box = Entry(master, textvariable=self.entryVar_freq_box).grid(row=1, column=1)\n\t\tself.label_samp_freq = Label(master, text=\"SAMPLING FREQUENCY (Hz)\").grid(row=2, column=0)\n\t\tself.entry_samp_freq = Entry(master,textvariable=self.entryVar_samp_freq).grid(row=2, column=1)\n\t\tself.label_duration = Label(master, text = \"DURATION (s)\").grid(row=3, column=0)\n\t\tself.entry_duration = Entry(master,textvariable=self.entryVar_duration).grid(row=3, column=1)\n\t\tself.label_volumne = Label(master, text=\"VOLUME [0.1 - 1.0]\").grid(row=4, column=0)\n\t\tself.entry_volume = Entry(master,textvariable=self.entryVar_volume).grid(row=4, column=1)\n\t\tself.button = Button(master, text = \"GENERATE\", command=self.cal_data).grid(row=5, column=0, columnspan=2)\n\n\t\tself.entryVar_freq_box.set('25')\n\t\tself.entryVar_samp_freq.set('44100')\n\t\tself.entryVar_duration.set('1')\n\t\tself.entryVar_volume.set('0.3')\n\n\tdef cal_data(self):\n\t\tself.f = (self.entryVar_freq_box.get()) # range [0.0, 1.0]\n\t\tself.fs = (self.entryVar_samp_freq.get()) # sampling rate, Hz, must be integer\n\t\tself.duration = (self.entryVar_duration.get()) # in seconds, may be float\n\t\tself.volume = (self.entryVar_volume.get()) # sine frequency, Hz, may be float\n\t\t\t\t\n\t\t# generate samples, note conversion to float32 array\n\t\tsamples = (np.sin(2*np.pi*np.arange(self.fs*self.duration)*self.f/self.fs)).astype(np.float32)\n\n\t\t# for paFloat32 saample values must be in range [-1.0, 1.0]\n\t\tstream = p.open(format=pyaudio.paFloat32,\n\t\t\t\t\t\tchannels=1,\n\t\t\t\t\t\trate=self.fs,\n\t\t\t\t\t\toutput=True)\n\n\t\t# play. May repeat with different volume values (if done interactively) \n\n\t\tstream.write(self.volume*samples)\n\n\t\tstream.stop_stream()\n\t\tstream.close()\n\n\t\t#~ p.terminate()\n\nroot = Tk()\nSoundgenerator(root)\nroot.mainloop()\n","sub_path":"frequency_generator.py","file_name":"frequency_generator.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"21125928","text":"from proteus import *\nfrom dissipation_p import *\n\ntimeIntegration = BackwardEuler_cfl\nstepController = Min_dt_cfl_controller\n\nfemSpaces = {0:basis}\n\nmassLumping = False\nconservativeFlux = None\nnumericalFluxType = Dissipation.NumericalFlux\nsubgridError = Dissipation.SubgridError(coefficients=coefficients,nd=nd)\nshockCapturing = Dissipation.ShockCapturing(coefficients,nd,shockCapturingFactor=dissipation_shockCapturingFactor,\n lag=True)\n\nfullNewtonFlag = True\nmultilevelNonlinearSolver = Newton\nlevelNonlinearSolver = Newton\n\nnonlinearSmoother = None\nlinearSmoother = None\n#printNonlinearSolverInfo = True\nmatrix = SparseMatrix\nif use_petsc4py:\n multilevelLinearSolver = KSP_petsc4py\n levelLinearSolver = KSP_petsc4py\nelse:\n multilevelLinearSolver = LU\n levelLinearSolver = LU\n\nlinear_solver_options_prefix = 'dissipation_'\nlevelNonlinearSolverConvergenceTest = 'r'#'rits'\nlinearSolverConvergenceTest = 'r'#'rits'\n\ntolFac = 0.0\n\nnl_atol_res = 1.0e-6\nnl_rtol_res = 0.0\n\nmaxNonlinearIts = 10\nmaxLineSearches = 0\n\n","sub_path":"benchmarks/windtunnel/dissipation_n.py","file_name":"dissipation_n.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"524466256","text":"from mcpi.minecraft import Minecraft\nmc = Minecraft.create()\n\nimport random\n\n\nglobal level\nlevel = 0\n\t\nmc.setting(\"world_immutable\", False)\t\t### cannot break blocks\n\nx,y,z = mc.player.getTilePos()\n\n# mc.postToChat(str(x) + \" \" + str(y) + \" \" + str(z))\n\n\n\n### sets basic plain landscape\n'''\nmc.setBlocks(x-100, \ty-10, \tz-100, \tx+100, \ty-1, \tz+100, \t\t2)\nmc.setBlocks(x-100, \ty, \t\tz-100, \tx+100, \ty+20,\tz+100, \t\t0)\n'''\n\t\n############################################################ variables - 25 room\n\n\nblock = 48\nfill = 0\nwidth = 5\t\t#room is 5x5 block area \nrooms = 5 \t\t#5 x 5 rooms\n\nbx = x+5\nby = y\nbz = z+5\n\n\n############################################################ build solid building\n\nmc.setBlocks(bx, by, bz, bx+((width+1)*rooms), by+5, bz+((width+1)*rooms), block)\n\n\n############################################################ insert rooms\n\n\nbuildx = list(range(1,6))\nbuildz = list(range(1,6))\n\nfor x1 in buildx:\n\tfor z1 in buildz:\n\t\tmc.setBlocks(bx+x1+(width*(x1-1)), by+1, bz+z1+(width*(z1-1)), bx+(x1-1)+width*x1,\tby+4, bz+(width*z1)+(z1-1), fill)\n\n\t\t\n############################################################ doors (add step)\n\n# front door\n\nmc.setBlocks(bx+15,by+1,bz,bx+15,by+2,bz,0)\nmc.setBlock(bx+15,by,bz,67,2)\n\n# internal doors\n\ndoorx = [6,12,18,24]\ndoorz = [3,9,15,21,27]\n\nfor dx1 in doorx:\n\tfor dz1 in doorz:\n\t\tmc.setBlocks(bx+dx1, by+1, bz+dz1, bx+dx1, by+2, bz+dz1, 48)\n\t\tmc.setBlock (bx+dx1, by+4, bz+dz1, 89)\n\t\t\nfor dx1 in doorx:\n\tfor dz1 in doorz:\n\t\tmc.setBlocks(bx+dz1, by+1, bz+dx1, bx+dz1, by+2, bz+dx1, 48)\n\t\tmc.setBlock (bx+dz1, by+4, bz+dx1, 89)\n\t\t\n############################################################ door group per level\n\ndef redlevel():\n\t\n\tred \t= [(6,3), (12,3), (6,3), (3,6), (9,6), (6,9)]\n\t\n\tfor rx,rz in red:\n\t\tmc.setBlock (bx+rx, by+1, bz+rz, 0)\n\t\tmc.setBlock (bx+rx, by+2, bz+rz, 0)\n\t\ndef orangelevel():\n\n\torange\t= []\n\ndef yellowlevel():\n\n\tyellow\t= []\t\n\ndef greenlevel():\n\n\tgreen\t= []\n\t\ndef bluelevel():\n\n\tblue\t= []\n\t\ndef indigolevel():\n\n\tindigo\t= []\n\ndef violetlevel():\n\n\tviolet\t= []\n\n\nredlevel()\n\t\n############################################################ random location\n\nred1 = list(range(1,6))\nred2 = list(range(7,12))\n\nrandomred = []\nredspot = []\n\n\n\nfor r1x in red1:\n\tfor r1z in red1:\n\t\trandomred.append([r1x, r1z])\n\t\t\nfor r2x in red1:\n\tfor r2z in red2:\n\t\trandomred.append([r2x, r2z])\n\t\t\nfor r3x in red2:\n\tfor r3z in red1:\n\t\trandomred.append([r3x, r3z])\n\t\t\nfor r4x in red2:\n\tfor r4z in red2:\n\t\trandomred.append([r4x, r4z])\n\nredspot = random.choice(randomred)\n\na,c = redspot\n\nmc.setBlock(bx+a, by+1, bz+c, 46)\n\n\n","sub_path":"minecraft-pi/projects/pc/game005.py","file_name":"game005.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"549067937","text":"import numpy as np\r\nimport pandas as pd\r\nfrom sklearn.metrics import accuracy_score\r\nfrom numpy import linalg\r\nfrom numpy.linalg import norm\r\nimport xgboost\r\nimport tensorflow as tf\r\n\r\nimport sklearn\r\nfrom sklearn.manifold import TSNE\r\nfrom sklearn.datasets import load_digits\r\nfrom sklearn.preprocessing import scale\r\n\r\nX = pd.read_csv(\"MLB/X_sort.csv\", encoding='latin-1')\r\ny = pd.read_csv(\"MLB/y_sort.csv\", encoding='latin-1', names=['Score'])\r\n\r\nfrom constant_variables import features_top_list\r\nX2 = X[features_top_list]\r\nX3 = X2.drop('Expected_Runs', axis = 1)\r\n\r\n#X_train, X_validate, X_test = np.split(X.sample(frac=1), [int(.6*len(X)), int(.8*len(X))])\r\n#y_train, y_validate, y_test = np.split(y.sample(frac=1), [int(.6*len(y)), int(.8*len(y))])\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X3, y, test_size = 0.20, random_state = 0)\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_train1, y_train, y_train1 = train_test_split(X_train, y_train, test_size = 0.50, random_state = 0)\r\n\r\n# Feature Scaling (Important for high intensity computations)\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc = StandardScaler()\r\nX_train = sc.fit_transform(X_train)\r\nX_test = sc.transform(X_test)\r\nX_train1 = sc.fit_transform(X_train1)\r\n#X_test1 = sc.transform(X_test1)\r\n\r\n# Fitting XGBoost to the Training set\r\nfrom xgboost import XGBClassifier\r\nclassifier = XGBClassifier()\r\nclassifier.fit(X_train, y_train)\r\n\r\n# Fitting XGBoost to the Training set\r\nclassifier1 = XGBClassifier()\r\nclassifier1.fit(X_train1, y_train1)\r\n\r\n# Predicting the Test set results\r\ny_pred_X = classifier.predict(X_train)\r\ny_pred1_X1 = classifier.predict(X_train1)\r\ny_pred_X_test = classifier.predict(X_test)\r\n\r\nmae_X_test = np.round(abs(y_test.values - y_pred_X_test).mean(),decimals=2)\r\nrmse_X_test = (((y_test.values - y_pred_X_test)**2).mean())**(1/2)\r\nr_X_test = (((y_test.values-y_test.values.mean())*(y_pred_X_test - y_pred_X_test.mean())).sum()) / ((1-len(y_test))*(y_test.values.std())*(y_pred_X_test.std()))\r\n\r\ny_test_total = ((pd.DataFrame(y_pred_test_rd) + pd.DataFrame(y_pred_X_test.ravel()))/2).astype(int)\r\nmae_test_total = np.round(abs(y_test.values - y_test_total[0]).mean(),decimals=2)\r\nrmse_test_total = (((y_test.values - y_test_total[0])**2).mean())**(1/2)\r\nr_test_total = (((y_test.values-y_test.values.mean())*(y_test_total[0] - y_test_total[0].mean())).sum()) / ((1-len(y_test))*(y_test.values.std())*(y_test_total[0].std()))\r\n\r\n\r\ny_pred_error = y_train.values - pd.DataFrame(y_pred_X.ravel())\r\n\r\n# Fitting XGBoost to the Training set\r\nclassifier1 = XGBClassifier()\r\nclassifier1.fit(X_train, y_pred_error)\r\n\r\ny_pred_Xr = classifier1.predict(X_train)\r\ny_pred_error_r = y_pred_error - pd.DataFrame(y_pred_Xr.ravel())\r\ny_predicted = y_pred_X + y_pred_Xr\r\n\r\nmae_Xr = np.round(abs(y_test.values - y_predicted).mean(),decimals=2)\r\nmae_pred = abs(y_test.values - y_pred_test_rd).mean()\r\n\r\nrmse_Xr = (((y_test.values - y_predicted)**2).mean())**(1/2)\r\nrmse_pred = (((y_test.values - y_pred_test_rd)**2).mean())**(1/2)\r\n\r\nr_Xr = (((y_test.values-y_test.values.mean())*(y_pred_X - y_predicted.mean())).sum()) / ((1-len(y_test))*(y_test.values.std())*(y_predicted.std()))\r\nr_pred = (((y_test.values-y_test.values.mean())*(y_pred_test_rd - y_pred_test_rd.mean())).sum()) / ((1-len(y_test))*(y_test.values.std())*(y_pred_test_rd.std()))\r\n\r\ny_mean = y.mean().astype(int)\r\ny_res = y-y_mean\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Predicting the Test set results\r\n#y_pred1 = classifier1.predict(X_test1)\r\n\r\n# Making the Confusion Matrix\r\n#from sklearn.metrics import confusion_matrix\r\n#cm = confusion_matrix(y_test, y_pred)\r\n\r\n# Applying k-Fold Cross Validation\r\nfrom sklearn.model_selection import cross_val_score\r\naccuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)\r\nmean_acc = accuracies.mean()\r\ntrain_std = accuracies.std()\r\n\r\n# Applying k-Fold Cross Validation\r\naccuracies1 = cross_val_score(estimator = classifier1, X = X_train1, y = y_train1, cv = 10)\r\nmean_acc1 = accuracies1.mean()\r\ntrain1_std = accuracies1.std()\r\n'''\r\n# Applying k-Fold Cross Validation\r\naccuracies2 = cross_val_score(estimator = classifier2, X = X_test, y = y_test, cv = 10)\r\nmean_acc1 = accuracies1.mean()\r\naccuracies1.mean()\r\naccuracies1.std()'''\r\n\r\nfeature_importance = classifier.feature_importances_\r\nfeatures = pd.Series(feature_importance, index = X3.columns)\r\nfeatures_sorted = pd.Series(features.sort_values())\r\n\r\nfeature_importance1 = classifier1.feature_importances_\r\nfeatures1 = pd.Series(feature_importance1, index = X3.columns)\r\nfeatures_sorted1 = pd.Series(features1.sort_values())\r\n\r\n'''\r\nfeatures.sort_values()\r\nfeatures_index_sort = features.index()\r\n\r\nfeatures1.sort_values()\r\nfeatures_index_sort1 = features1.index()\r\n'''\r\n\r\nX_train_weighted = X_train*feature_importance\r\nX_train1_weighted = X_train1*feature_importance1\r\nX_train_weighted_total = np.concatenate([X_train_weighted, X_train1_weighted], axis=0)\r\nX_train_weighted_total_norm = (X_train_weighted_total - X_train_weighted_total.mean()) / (X_train_weighted_total.max() - X_train_weighted_total.min())\r\ny_train_weighted = np.concatenate([y_train, y_train1], axis=0)\r\n#X_test_total = np.concatenate([X_test, X_test1], axis=0)\r\n#y_test_total = pd.DataFrame(np.concatenate([y_test, y_test1], axis=0), index = list(np.concatenate([y_test.index,y_test1.index], axis=0)))\r\n'''\r\nfeatures_avg = (features + features1)/2\r\nX_test_weighted = X_test*features_avg.values\r\nX_test_weighted_norm = (X_test_weighted - X_test_weighted.mean()) / (X_test_weighted.max() - X_test_weighted.min())\r\n'''\r\n\r\nX4 = X_train_weighted_total_norm\r\ny1 = y_train_weighted\r\n\r\nimport keras\r\nfrom keras import optimizers\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Activation\r\nfrom keras.layers import Dropout\r\nfrom keras import objectives\r\nfrom keras import backend as K\r\n\r\n# Initialising the ANN\r\nregressor1 = Sequential()\r\n\r\n# Adding the input layer and the first hidden layer with dropout (start 0.1 (10%))\r\nregressor1.add(Dense(output_dim = 64, init = 'uniform', activation = 'relu', input_dim = len(X3.columns)))\r\nregressor1.add(Dropout(p=0.1))\r\n\r\n# Adding the second hidden layer\r\nregressor1.add(Dense(output_dim = 50, init = 'uniform', activation = 'relu'))\r\nregressor1.add(Dropout(p=0.1))\r\n\r\n# Adding the second hidden layer\r\nregressor1.add(Dense(output_dim = 35, init = 'uniform', activation = 'relu'))\r\nregressor1.add(Dropout(p=0.1))\r\n\r\n# Adding the third hidden layer\r\nregressor1.add(Dense(output_dim = 20, init = 'uniform', activation = 'relu'))\r\nregressor1.add(Dropout(p=0.1))\r\n\r\n# Adding the output layer\r\nregressor1.add(Dense(output_dim = 1, init = 'uniform'))\r\n\r\n# Compiling the ANN (adam[SGD] - optimizer function to find optimal weights)\r\n# Binary Dept Var(Binary_CrossEntropy) Dependent Var > 2 Outcomes (Categorical_CrossEntropy)\r\n# [Accuracy] in brackets because list expected\r\nregressor1.compile(optimizer = 'adam', loss = 'mse', metrics=['binary_crossentropy','acc'])\r\n\r\n# Fitting the ANN to the Training set\r\nregressor1.fit(X_train, y_train, batch_size = 35, epochs = 500)\r\n'''\r\n# Predicting the Test set results\r\ny_pred_test = regressor1.predict(X_test)\r\ny_pred_test_rd = np.round(y_pred_test)\r\ny_test_index = [x for x in y_test.index]\r\n\r\n# Predicting a new result\r\ny_pred_train = regressor1.predict(X4)\r\ny_pred_train_rd = np.round(y_pred_train)\r\ny_train_index = [x for x in y.index]'''\r\n\r\nfeatures_avg = (features + features1)/2\r\nX_test_weighted = X_test*features_avg.values\r\nX_test_weighted_norm = (X_test_weighted - X_test_weighted.mean()) / (X_test_weighted.max() - X_test_weighted.min())\r\n\r\n# Predicting the Test set results\r\ny_pred_test = regressor1.predict(X_test_weighted_norm)\r\ny_pred_test_rd = np.round(y_pred_test)\r\ny_test_total_index = [x for x in pd.Series(y_test.index)]\r\ny_pred_test1 = regressor1.predict(X_test)\r\ny_pred_test1_rd = np.round(y_pred_test1)\r\n\r\n\r\nexpected = X2['Expected_Runs']\r\ny_expected_test = expected[y_test_total_index]\r\ny_expected_test_round = np.round(y_expected_test)\r\n\r\nmae = np.round(abs(y_test.values - y_expected_test_round.values).mean(),decimals=2)\r\nmae_pred = abs(y_test.values - y_pred_test_rd).mean()\r\nmae_test = np.round(abs(y_test.values - y_pred_test1_rd).mean(),decimals=2)\r\n\r\nrmse = (((y_test.values - y_expected_test_round.values)**2).mean())**(1/2)\r\nrmse_pred = (((y_test.values - y_pred_test_rd)**2).mean())**(1/2)\r\nrmse_test = (((y_test.values - y_pred_test1_rd)**2).mean())**(1/2)\r\n\r\nr = (((y_test.values-y_test.values.mean())*(y_expected_test_round.values - y_expected_test_round.values.mean())).sum()) / ((1-len(y_test))*(y_test.values.std())*(y_expected_test_round.values.std()))\r\nr_pred = (((y_test.values-y_test.values.mean())*(y_pred_test_rd - y_pred_test_rd.mean())).sum()) / ((1-len(y_test))*(y_test.values.std())*(y_pred_test_rd.std()))\r\nr_test = (((y_test.values-y_test.values.mean())*(y_pred_test1_rd - y_pred_test1_rd.mean())).sum()) / ((1-len(y_test))*(y_test.values.std())*(y_pred_test1_rd.std()))\r\n\r\ny_test_total = ((pd.DataFrame(y_pred_test1_rd) + pd.DataFrame(y_pred_X_test.ravel()))/2).astype(int)\r\nmae_test_total = np.round(abs(y_test.values - y_test_total).mean(),decimals=2)\r\nrmse_test_total = (((y_test.values - y_test_total)**2).mean())**(1/2)\r\nr_test_total = (((y_test.values-y_test.values.mean())*(y_test_total - y_test_total.mean())).sum()) / ((1-len(y_test))*(y_test.values.std())*(y_test_total.std()))\r\n\r\n\r\nimport thinkstats2\r\nfrom thinkstats2 import *\r\nfrom code import *\r\nimport thinkplot\r\n\r\ny2 = y1.flatten()\r\n\r\npmf_scores = thinkstats2.Pmf(y2)\r\nthinkplot.Hist(pmf_scores)\r\nthinkplot.Config(xlabel='Runs Scored', ylabel='probability', axis=[0, 20, 0, 0.3])\r\n\r\ncdf_scores = thinkstats2.Cdf(y2, label='Runs Scored')\r\ncdf_ld = thinkstats2.Cdf(X3['bat_LD%'], label='Line Drives')\r\ncdf_pop = thinkstats2.Cdf(X3['bat_POP%'], label='Pop Ups')\r\ncdf_gb = thinkstats2.Cdf(X3['bat_GB%'], label='Ground Balls')\r\n\r\nthinkplot.PrePlot(4)\r\nthinkplot.Cdfs([cdf_scores, cdf_ld, cdf_pop, cdf_gb])\r\nthinkplot.Show(xlabel='balls in play (%)', ylabel='CDF')\r\n\r\n# Visualizing data in One Dimension (1-D)\r\nimport matplotlib.pyplot as plt\r\ny.hist(bins=15, color='steelblue', edgecolor='black', linewidth=1.0,\r\n xlabelsize=8, ylabelsize=8, grid=False) \r\nplt.tight_layout(rect=(0, 15, 0, 15)) \r\n\r\n# visualizing one of the continuous, numeric attributes\r\n# Histogram\r\nfig = plt.figure(figsize = (10,4))\r\ntitle = fig.suptitle(\"Runs\", fontsize=14)\r\nfig.subplots_adjust(top=0.85, wspace=0.1)\r\n\r\nax = fig.add_subplot(1,1, 1)\r\nax.set_xlabel(\"SDTHB_BAT\")\r\nax.set_ylabel(\"Frequency\") \r\nax.set_xlim([0.35, 0.55])\r\n#ax.text(0.8, 300, '%='+str(round(census_data['IncomePerCap'].dropna(),1)), fontsize=10)\r\nfreq, bins, patches = ax.hist(X3['SDTHB_BAT'].dropna(), color='steelblue', bins=15,\r\n edgecolor='black', linewidth=1)\r\n\r\n\r\n# Density Plot\r\nimport seaborn as sns\r\nfig = plt.figure(figsize = (6, 4))\r\ntitle = fig.suptitle(\"SDTHB_BAT\", fontsize=14)\r\nfig.subplots_adjust(top=0.85, wspace=0.3)\r\n\r\nax1 = fig.add_subplot(1,1, 1)\r\nax1.set_xlabel(\"SDTHB_BAT\")\r\nax1.set_ylabel(\"Frequency\") \r\nsns.kdeplot(X3['SDTHB_BAT'].dropna(), ax=ax1, shade=True, color='steelblue')\r\n\r\n# Multivariate Analysis\r\n# Visualizing data in Two Dimensions (2-D)\r\n# Correlation Matrix Heatmap\r\nf, ax = plt.subplots(figsize=(10, 6))\r\ncorr = X3.corr()\r\nhm = sns.heatmap(round(corr,2), annot=False, ax=ax, cmap=\"coolwarm\",fmt='.2f',\r\n linewidths=.05)\r\nf.subplots_adjust(top=0.93)\r\nt= f.suptitle('Game Correlation Heatmap', fontsize=14)\r\n\r\n\r\n# Pair-wise Scatter Plots\r\ncols = list(X3.columns)\r\npp = sns.pairplot(X3[cols[-15:]], size=1.8, aspect=1.8,\r\n plot_kws=dict(edgecolor=\"k\", linewidth=0.5),\r\n diag_kind=\"kde\", diag_kws=dict(shade=True))\r\n\r\nfig = pp.fig \r\nfig.subplots_adjust(top=0.93, wspace=0.3)\r\nt = fig.suptitle('Game Attributes Pairwise Plots', fontsize=14)\r\n\r\n# parallel coordinates\r\n# Scaling attribute values to avoid few outiers\r\ncols = list(X3.columns)\r\nsubset_df = X3[cols[-15:]]\r\n\r\nfrom sklearn.preprocessing import StandardScaler\r\nss = StandardScaler()\r\n\r\nscaled_df = ss.fit_transform(subset_df)\r\nscaled_df = pd.DataFrame(scaled_df, columns=cols[-15:])\r\nfinal_df = pd.concat([scaled_df, X3['SDTHB_BAT']], axis=1)\r\nfinal_df.head()\r\n\r\n\r\n# plot parallel coordinates\r\nfrom pandas.plotting import parallel_coordinates\r\npc = parallel_coordinates(final_df, 'SDTHB_BAT', color=('#FFE888', '#FF9999', 'DarkGreen'))\r\n\r\n# visualize two continuous, numeric attributes. Scatter plots and joint plots\r\n# Scatter Plot\r\nplt.scatter(X3['SDTHB_BAT'], y,\r\n alpha=0.4, edgecolors='w')\r\n\r\nplt.xlabel('SDTHB_BAT')\r\nplt.ylabel('bat_GB%')\r\nplt.title('SDTHB_BAT - bat_GB%',y=1.05)\r\n\r\n# Joint Plot\r\njp = sns.jointplot(x='SDTHB_BAT', y='bat_GB%', data=X3,\r\n kind='reg', space=0, size=5, ratio=4)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# visualizing two discrete, categorical attributes\r\n# Using subplots or facets along with Bar Plots\r\nfig = plt.figure(figsize = (10, 4))\r\ntitle = fig.suptitle(\"TB_batter - Era\", fontsize=14)\r\nfig.subplots_adjust(top=0.85, wspace=0.3)\r\n# red wine - wine quality\r\nax1 = fig.add_subplot(1,2, 1)\r\nax1.set_title(\"TB_batter for pitchers with ERA <= 3.5\")\r\nax1.set_xlabel(\"TB_batter\")\r\nax1.set_ylabel(\"Era\") \r\nrw_q = X3['TB_batter'][X3['pitcher_ERA']<=3.5].value_counts()\r\nrw_q = (list(rw_q.index), list(rw_q.values))\r\nax1.set_ylim([0, 2500])\r\nax1.tick_params(axis='both', which='major', labelsize=8.5)\r\nbar1 = ax1.bar(rw_q[0], rw_q[1], color='red', \r\n edgecolor='black', linewidth=1)\r\n\r\n# white wine - wine quality\r\nax2 = fig.add_subplot(1,2, 2)\r\nax2.set_title(\"New York\")\r\nax2.set_xlabel(\"Unemployment\")\r\nax2.set_ylabel(\"Frequency\") \r\nww_q = census_drop['Unemployment_Rate'][census_drop['State']=='New York'].value_counts()\r\nww_q = (list(ww_q.index), list(ww_q.values))\r\nax2.set_ylim([0, 2500])\r\nax2.tick_params(axis='both', which='major', labelsize=8.5)\r\nbar2 = ax2.bar(ww_q[0], ww_q[1], color='white', \r\n edgecolor='black', linewidth=1)\r\n\r\n\r\nxint = census_drop[\"Unemployment\"].astype(int)\r\n# stacked bars or multiple bars\r\n# Multi-bar Plot\r\ncp = sns.countplot(x=xint, hue=\"Unemployment_Rate\", data=census_drop, \r\n palette={\"high\": \"#FF9999\", \"medium\": \"#FFE888\", \"low\": '#001C7F'})\r\n\r\n\r\n# visualizing mixed attributes in two-dimensions\r\n# faceting\\subplots along with generic histograms or density plots.\r\n# facets with histograms\r\nfig = plt.figure(figsize = (10,4))\r\ntitle = fig.suptitle(\"pitcher_ERA vs runners that touched base\", fontsize=14)\r\nfig.subplots_adjust(top=0.85, wspace=0.3)\r\n\r\nax1 = fig.add_subplot(1,3, 1)\r\nax1.set_title(\"Low TB's\")\r\nax1.set_xlabel(\"pitcher_ERA\")\r\nax1.set_ylabel(\"Frequency\") \r\nax1.set_ylim([0, 200])\r\nax1.text(1.2, 800, r'$mu$='+str(round(X3['pitcher_ERA'][X3['TB_batter']<25].mean(),2)), \r\n fontsize=12)\r\nr_freq, r_bins, r_patches = ax1.hist(X3['pitcher_ERA'][X3['TB_batter']<25], color='red', bins=15,\r\n edgecolor='Black', linewidth=1)\r\n\r\nax2 = fig.add_subplot(1,3, 2)\r\nax2.set_title(\"Medium TB's\")\r\nax2.set_xlabel(\"pitcher_ERA\")\r\nax2.set_ylabel(\"Frequency\")\r\nax2.set_ylim([0, 200])\r\nax2.text(0.8, 800, r'$mu$='+str(round(X3['pitcher_ERA'][X3['TB_batter']<45].mean(),2)), \r\n fontsize=12)\r\nw_freq, w_bins, w_patches = ax2.hist(X3['pitcher_ERA'][X3['TB_batter']<45], color='white', bins=15,\r\n edgecolor='Black', linewidth=1)\r\n\r\n\r\nax3 = fig.add_subplot(1,3, 3)\r\nax3.set_title(\"High TB's\")\r\nax3.set_xlabel(\"pitcher_ERA\")\r\nax3.set_ylabel(\"Frequency\")\r\nax3.set_ylim([0, 200])\r\nax3.text(0.8, 800, r'$mu$='+str(round(X3['pitcher_ERA'][X3['TB_batter']>=45].mean(),2)), \r\n fontsize=12)\r\nw_freq, w_bins, w_patches = ax3.hist(X3['pitcher_ERA'][X3['TB_batter']>=45], color='green', bins=15,\r\n edgecolor='Black', linewidth=1)\r\n\r\n\r\n# facets with density plots\r\nfig = plt.figure(figsize = (10, 4))\r\ntitle = fig.suptitle(\"Unemployment Content in USA\", fontsize=14)\r\nfig.subplots_adjust(top=0.85, wspace=0.5)\r\n\r\nax1 = fig.add_subplot(1,3, 1)\r\nax1.set_title(\"Low Unemployment\")\r\nax1.set_xlabel(\"Black\")\r\nax1.set_ylabel(\"Density\") \r\nsns.kdeplot(X3['Black'][X3['Unemployment_Rate']=='low'], ax=ax1, shade=True, color='r')\r\n\r\nax2 = fig.add_subplot(1,3, 2)\r\nax2.set_title(\"Medium Unemployment\")\r\nax2.set_xlabel(\"Black\")\r\nax2.set_ylabel(\"Density\") \r\nsns.kdeplot(X3['Black'][X3['Unemployment_Rate']=='medium'], ax=ax2, shade=True, color='g')\r\n\r\nax3 = fig.add_subplot(1,3, 3)\r\nax3.set_title(\"High Unemployment\")\r\nax3.set_xlabel(\"Black\")\r\nax3.set_ylabel(\"Density\") \r\nsns.kdeplot(X3['Black'][X3['Unemployment_Rate']=='high'], ax=ax3, shade=True, color='y')\r\n\r\n\r\n# Using multiple Histograms \r\nfig = plt.figure(figsize = (6, 4))\r\ntitle = fig.suptitle(\"Unemployment Content in USA\", fontsize=14)\r\nfig.subplots_adjust(top=0.85, wspace=0.3)\r\nax = fig.add_subplot(1,1, 1)\r\nax.set_xlabel(\"Black\")\r\nax.set_ylabel(\"Frequency\") \r\n\r\ng = sns.FacetGrid(X3, hue='Unemployment_Rate', palette={\"high\": \"r\", \"medium\": \"y\", 'low': 'g'})\r\ng.map(sns.distplot, 'Black', kde=False, bins=15, ax=ax)\r\nax.legend(title='Unemployment')\r\nplt.close(3)\r\n\r\n\r\n# Box Plots\r\nf, (ax) = plt.subplots(1, 1, figsize=(12, 4))\r\nf.suptitle('Unemployment - Black', fontsize=14)\r\n\r\nsns.boxplot(x=\"Unemployment_Rate\", y=\"Black\", data=X3, ax=ax)\r\nax.set_xlabel(\"Unemployment\",size = 12,alpha=0.8)\r\nax.set_ylabel(\"Black %\",size = 12,alpha=0.8)\r\n\r\n\r\n# Violin Plots\r\nf, (ax) = plt.subplots(1, 1, figsize=(12, 4))\r\nf.suptitle('Unemployment - Black', fontsize=14)\r\n\r\nsns.violinplot(x=\"Unemployment_Rate\", y=\"Black\", data=X3, ax=ax)\r\nax.set_xlabel(\"Unemployment_Rate\",size = 12,alpha=0.8)\r\nax.set_ylabel(\"Black\",size = 12,alpha=0.8)\r\n\r\n\r\n# Visualizing data in Three Dimensions (3-D)\r\n# pair-wise scatter plot \r\n# Scatter Plot with Hue for visualizing data in 3-D\r\ncols = ['CensusTract', 'TotalPop', 'Men', 'Women', 'Hispanic', 'White', 'Black', 'Native', 'Asian', 'Pacific', 'Citizen',\r\n 'Income', 'IncomeErr', 'IncomePerCap', 'IncomePerCapErr', 'Poverty', 'ChildPoverty', 'Professional', 'Service', 'Office', 'Construction',\r\n 'Production', 'Drive', 'Carpool', 'Transit', 'Walk', 'OtherTransp', 'WorkAtHome', 'MeanCommute', 'Employed', 'PrivateWork', 'PublicWork',\r\n 'SelfEmployed', 'FamilyWork', 'Unemployment', 'Unempoyment_Rate']\r\npp = sns.pairplot(X3[cols], hue='Unemployment_Rate', size=1.8, aspect=1.8, \r\n palette={\"high\": \"#FF9999\", \"medium\": \"#FFE888\", \"low\": '#001C7F'},\r\n plot_kws=dict(edgecolor=\"black\", linewidth=0.5))\r\nfig = pp.fig \r\nfig.subplots_adjust(top=0.93, wspace=0.3)\r\nt = fig.suptitle('Unemployment_Rate Pairwise Plots', fontsize=14)\r\n\r\n\r\n# visualizing three continuous, numeric attributes\r\n# Visualizing 3-D numeric data with Scatter Plots\r\n# length, breadth and depth\r\nfig = plt.figure(figsize=(8, 6))\r\nax = fig.add_subplot(111, projection='3d')\r\n\r\nxs = X3['Black']\r\nys = X3['Professional']\r\nzs = X3['Unemployment']\r\nax.scatter(xs, ys, zs, s=50, alpha=0.6, edgecolors='w')\r\n\r\nax.set_xlabel('Black')\r\nax.set_ylabel('Professional')\r\nax.set_zlabel('Unemployment Rate')\r\n\r\n\r\n# # Visualizing 3-D numeric data with a bubble chart\r\n# length, breadth and size\r\nplt.scatter(X3['Black'], X3['Professional'], s=X3['Unemployment']*25, \r\n alpha=0.4, edgecolors='w')\r\n\r\nplt.xlabel('Professional')\r\nplt.ylabel('Black')\r\nplt.title('Black - Professional - Unemployment',y=1.05)\r\n\r\n\r\n# visualizing three discrete, categorical attributes\r\n# Visualizing 3-D categorical data using bar plots\r\n# leveraging the concepts of hue and facets\r\nfc = sns.factorplot(x=\"Black\", hue=\"Unemployment_Rate\", col=\"Unemployment_Rate\", \r\n data=X3, kind=\"count\",\r\n palette={\"high\": \"#FF9999\", \"medium\": \"#FFE888\", \"low\": '#001C7F'})\r\n\r\n\r\n\r\n# three mixed attributes\r\n# Visualizing 3-D mix data using scatter plots\r\n# leveraging the concepts of hue for categorical dimension\r\njp = sns.pairplot(X3, x_vars=[\"Black\"], y_vars=[\"Professional\"], size=4.5,\r\n hue=\"Unemployment_Rate\", palette={\"high\": \"#FF9999\", \"medium\": \"#FFE888\", \"low\": '#001C7F'},\r\n plot_kws=dict(edgecolor=\"k\", linewidth=0.5))\r\n \r\n# we can also view relationshipscorrelations as needed \r\nlp = sns.lmplot(x='Black', y='Professional', hue='Unemployment_Rate', \r\n palette={\"high\": \"#FF9999\", \"medium\": \"#FFE888\", \"low\": '#001C7F'},\r\n data=X3, fit_reg=True, legend=True,\r\n scatter_kws=dict(edgecolor=\"k\", linewidth=0.5)) \r\n\r\n\r\n \r\n# Visualizing 3-D mix data using kernel density plots\r\n# leveraging the concepts of hue for categorical dimension\r\nax = sns.kdeplot(X3['Black'][X3['Unemployment_Rate']=='high'], X3['Professional'][X3['Unemployment_Rate']=='high'],\r\n cmap=\"YlOrBr\", shade=True, shade_lowest=False)\r\nax = sns.kdeplot(X3['Black'][X3['Unemployment_Rate']=='low'], X3['Professional'][X3['Unemployment_Rate']=='low'],\r\n cmap=\"Reds\", shade=True, shade_lowest=False)\r\n \r\n \r\n\r\n# Predicting the Full Results\r\ny_pred_full = regressor.predict(X3)\r\ny_pred_full_rd = np.round(y_pred_full)\r\n\r\n# Predicting a new result\r\ny_pred_train = regressor.predict(X_train)\r\ny_pred_train_rd = np.round(y_pred_train)\r\ny_score_train = regressor.evaluate(X_train, y_train, batch_size = 10)\r\ny_score_test = regressor.evaluate(X_test, y_test, batch_size = 10)\r\n\r\n\r\n\r\n\r\nfeature_importance = classifier.feature_importances_\r\nfeatures = pd.Series(feature_importance, index=list(X.columns))\r\n\r\nfeatures.sort_values()\r\nfeatures_index_sort = features.sort_values()\r\nfeatures_index_sort1 = features_index_sort.ravel()\r\n\r\nfeatures_top = [x for x in features_index_sort1 if x>0.005]\r\nfeatures_top_name = features_index_sort[-65:]\r\nfeatures_top_list = [str(x) for x in features_top_name.index]\r\n\r\n\r\n\r\n\r\n","sub_path":"pretraining.py","file_name":"pretraining.py","file_ext":"py","file_size_in_byte":21919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"144375504","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport errno\nimport shutil\nimport logging\nimport sys\nimport imghdr\nimport ConfigParser\nfrom optparse import OptionParser\nfrom discogstagger.ext.mediafile import MediaFile\nfrom discogstagger.taggerutils import (\n TaggerUtils,\n create_nfo,\n create_m3u,\n get_images)\n\nlogger = logging.getLogger(__name__)\n\np = OptionParser()\np.add_option(\"-r\", \"--releaseid\", action=\"store\", dest=\"releaseid\",\n help=\"The discogs.com release id of the target album\")\np.add_option(\"-s\", \"--source\", action=\"store\", dest=\"sdir\",\n help=\"The directory that you wish to tag\")\np.add_option(\"-d\", \"--destination\", action=\"store\", dest=\"destdir\",\n help=\"The (base) directory to copy the tagged files to\")\np.add_option(\"-c\", \"--conf\", action=\"store\", dest=\"conffile\",\n help=\"The discogstagger configuration file.\")\n\np.set_defaults(conffile=\"/etc/discogstagger/discogs_tagger.conf\")\n(options, args) = p.parse_args()\n\nif not options.releaseid:\n p.error(\"Please specify the discogs.com releaseid ('-r')\")\n\nif not options.sdir or not os.path.exists(options.sdir):\n p.error(\"Please specify a valid source directory ('-s')\")\n\nif not options.destdir or not os.path.exists(options.destdir):\n destdir = options.sdir\nelse:\n destdir = options.destdir\n\nconfig = ConfigParser.ConfigParser()\nconfig.read(options.conffile)\n\nlogging.basicConfig(level=config.getint(\"logging\", \"level\"))\n\nkeep_original = config.getboolean(\"details\", \"keep_original\")\nembed_coverart = config.getboolean(\"details\", \"embed_coverart\")\nuse_style = config.getboolean(\"details\", \"use_style\")\n\nrelease = TaggerUtils(options.sdir, destdir, options.releaseid)\nrelease.nfo_format = config.get(\"file-formatting\", \"nfo\")\nrelease.m3u_format = config.get(\"file-formatting\", \"m3u\")\nrelease.dir_format = config.get(\"file-formatting\", \"dir\")\nrelease.song_format = config.get(\"file-formatting\", \"song\")\nrelease.group_name = config.get(\"details\", \"group\")\n\n# ensure we were able to map the release appropriately.\nif not release.tag_map:\n logging.error(\"Unable to match file list to discogs release '%s'\" %\n options.releaseid)\n sys.exit()\n\n#\n# start tagging actions.\n#\nlogging.info(\"Tagging album '%s - %s'\" % (release.album.artist,\n release.album.title))\n\nif os.path.exists(release.dest_dir_name):\n logging.error(\"Destination already exists %s\" % release.dest_dir_name)\n sys.exit(\"%s directory already exists, aborting.\" % release.dest_dir_name)\nelse:\n logging.info(\"Creating destination directory '%s'\" %\n release.dest_dir_name)\n os.mkdir(release.dest_dir_name)\n\nlogging.info(\"Downloading and storing images\")\nget_images(release.album.images, release.dest_dir_name)\n\nfor track in release.tag_map:\n logger.info(\"Writing file %s\" % os.path.join(release.dest_dir_name,\n track.new_file))\n logger.debug(\"metadata -> %.2d %s - %s\" % (track.position, track.artist,\n track.title))\n\n # copy old file into new location\n shutil.copyfile(os.path.join(options.sdir, track.orig_file),\n os.path.join(release.dest_dir_name, track.new_file))\n\n # load metadata information\n metadata = MediaFile(os.path.join(\n release.dest_dir_name, track.new_file))\n # remove current metadata\n metadata.delete()\n metadata.title = track.title\n metadata.artist = track.artist\n metadata.album = release.album.title\n metadata.composer = release.album.artist\n metadata.albumartist = release.album.artist\n metadata.label = release.album.label\n metadata.year = release.album.year\n # adding two are there is no standard. discogstagger pre v1\n # used (TXXX desc=\"Catalog #\")\n # mediafile uses TXXX desc=\"CATALOGNUMBER\"\n metadata.catalognum = release.album.catno\n metadata.catalognumber = release.album.catno\n\n genre = release.album.genre\n if use_style:\n genre = release.album.styles[0]\n\n metadata.genre = genre\n metadata.track = track.position\n metadata.tracktotal = len(release.tag_map)\n\n if embed_coverart and os.path.exists(os.path.join(release.dest_dir_name,\n \"00-image-01.jpg\")):\n imgdata = open(os.path.join(release.dest_dir_name,\n \"00-image-01.jpg\")).read()\n imgtype = imghdr.what(None, imgdata)\n\n if imgtype in (\"jpeg\", \"png\"):\n logger.info(\"Embedding album art.\")\n metadata.art = imgdata\n\n metadata.save()\n\n#\n# start supplementary actions\n#\nlogging.info(\"Generating .nfo file\")\ncreate_nfo(release.album.album_info, release.dest_dir_name,\n release.nfo_filename)\n\nlogging.info(\"Generating .m3u file\")\ncreate_m3u(release.tag_map, release.dest_dir_name, release.m3u_filename)\n\n# remove source directory, if configured as such.\nif not keep_original:\n logging.info(\"Deleting source directory '%s'\" % options.sdir)\n shutil.rmtree(options.sdir)\n\nlogging.info(\"Tagging complete.\")\n","sub_path":"scripts/discogs_tagger.py","file_name":"discogs_tagger.py","file_ext":"py","file_size_in_byte":5029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"622126044","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nimport subprocess\n\n\ndef mem():\n\n\n raw_data = subprocess.Popen(\"sudo dmidecode -t memory\", stdout=subprocess.PIPE, shell=True)\n raw_list = raw_data.stdout.read().decode().split(\"\\n\")\n raw_ram_list = []\n item_list = []\n for line in raw_list:\n if line.startswith(\"Memory Device\"):\n raw_ram_list.append(item_list)\n item_list = []\n else:\n item_list.append(line.strip())\n\n ram_list = []\n for item in raw_ram_list:\n item_ram_size = 0\n ram_item_to_dic = {}\n for i in item:\n data = i.split(\":\")\n if len(data) == 2:\n key, v = data\n if key == 'Size':\n if v.strip() != \"No Module Installed\":\n ram_item_to_dic['capacity'] = v.split()[0].strip()\n item_ram_size = round(float(v.split()[0]))\n else:\n ram_item_to_dic['capacity'] = 0\n\n if key == 'Type':\n ram_item_to_dic['model'] = v.strip()\n if key == 'Manufacturer':\n ram_item_to_dic['manufacturer'] = v.strip()\n if key == 'Serial Number':\n ram_item_to_dic['sn'] = v.strip()\n if key == 'Asset Tag':\n ram_item_to_dic['asset_tag'] = v.strip()\n if key == 'Locator':\n ram_item_to_dic['slot'] = v.strip()\n\n if item_ram_size == 0:\n pass\n else:\n ram_list.append(ram_item_to_dic)\n\n raw_total_size = subprocess.Popen(\"cat /proc/meminfo|grep MemTotal \", stdout=subprocess.PIPE, shell=True)\n raw_total_size = raw_total_size.stdout.read().decode().split(\":\")\n ram_data = {'ram': ram_list}\n if len(raw_total_size) == 2:\n total_gb_size = int(raw_total_size[1].split()[0]) / 1024**2\n ram_data['ram_size'] = total_gb_size\n\n\n print(ram_data)\n\nmem()","sub_path":"python/Hardware/mem.py","file_name":"mem.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"243502072","text":"# -*- coding: utf-8 -*-\n# flake8: noqa\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('millionmilestogether', '0004_moment'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='moment',\n options={'ordering': ('-occurred',)},\n ),\n migrations.RemoveField(\n model_name='photo',\n name='is_album_cover',\n ),\n ]\n","sub_path":"millionmilestogether/migrations/0005_no_album_cover.py","file_name":"0005_no_album_cover.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"358025862","text":"from machine import Pin\n\nclass Config:\n \n def __init__(self, box_id, pinList, patternList):\n self.state = 0\n self.box_id = box_id\n self.pinList = pinList\n self.numSwitch = len(pinList)\n self.patternList = patternList\n self.numPattern = len(patternList)\n self.switch_0 = Pin(pinList[0], Pin.OUT, value=0)\n if self.numSwitch > 1:\n self.switch_1 = Pin(pinList[1], Pin.OUT, value=0)\n if self.numSwitch > 2:\n self.switch_2 = Pin(pinList[2], Pin.OUT, value=0)\n if self.numSwitch > 3:\n self.switch_3 = Pin(pinList[3], Pin.OUT, value=0)\n #...\n #...\n \n def turn(self, pattern_num):\n p = self.patternList[pattern_num]\n self.switch_0.value(int(p[0]))\n if self.numSwitch > 1:\n self.switch_1.value(int(p[1]))\n if self.numSwitch > 2:\n self.switch_2.value(int(p[2]))\n if self.numSwitch > 3:\n self.switch_3.value(int(p[3]))\n #...\n #...\n\n def push(self):\n self.state += 1\n if self.state >= self.numPattern:\n self.state = 0\n return self.state\n","sub_path":"onebutton.py","file_name":"onebutton.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"352618281","text":"\nfrom dataset.kgforest import *\nfrom dataset.tool import *\n\nfrom net.rates import *\nfrom net.util import *\n\nfrom net.model.inceptionv3 import inception_v3 as Net\n\nSIZE = 256\nSRC = 'tif'\nCH = 'NIR'\nNCH = 1 # 4\nSEED = 123\n\nuse_gpu = True\n\n# CH = 'irrgb'\n# SRC = 'jpg' #channel\n#CH = 'rgb'\n#CH = 'irrg'\n\n\ndef loss_func(logits, labels):\n loss = nn.MultiLabelSoftMarginLoss()(logits, Variable(labels))\n return loss\n\n\ndef multi_f_measure(probs, labels, threshold=0.235, beta=2):\n\n SMALL = 1e-6 # 0 #1e-12\n batch_size = probs.size()[0]\n\n # weather\n l = labels\n p = (probs > threshold).float()\n\n num_pos = torch.sum(p, 1)\n num_pos_hat = torch.sum(l, 1)\n tp = torch.sum(l * p, 1)\n precise = tp / (num_pos + SMALL)\n recall = tp / (num_pos_hat + SMALL)\n\n fs = (1 + beta * beta) * precise * recall / \\\n (beta * beta * precise + recall + SMALL)\n f = fs.sum() / batch_size\n return f\n\n\ndef f2_score(y_pred, y_true, thres=0.235):\n y_true, y_pred, = np.array(y_true), np.array(y_pred)\n y_pred = y_pred > thres\n return fbeta_score(y_true, y_pred, beta=2, average='samples')\n\n\ndef augment(x, u=0.75):\n if random.random() < u:\n if random.random() > 0.5:\n x = randomDistort1(x, distort_limit=0.35, shift_limit=0.25, u=1)\n else:\n x = randomDistort2(x, num_steps=10, distort_limit=0.2, u=1)\n x = randomShiftScaleRotate(\n x, shift_limit=0.0625, scale_limit=0.10, rotate_limit=45, u=1)\n\n x = randomFlip(x, u=0.5)\n x = randomTranspose(x, u=0.5)\n #x = randomContrast(x, limit=0.2, u=0.5)\n #x = randomSaturation(x, limit=0.2, u=0.5),\n x = randomFilter(x, limit=0.5, u=0.2)\n return x\n\n\ndef do_thresholds(probs, labels):\n print('\\n--- [START %s] %s\\n\\n' %\n (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), '-' * 64))\n print('\\n')\n\n nClass = len(CLASS_NAMES)\n tryVals = np.arange(0, 1, 0.005)\n scores = np.zeros(len(tryVals))\n\n # single threshold\n for i, t in enumerate(tryVals):\n scores[i] = fbeta_score(labels, probs > t, beta=2, average='samples')\n\n best_single_thres = tryVals[scores.argmax()]\n best_single_thres_score = scores.max()\n\n print('*best_threshold (fixed)*\\n')\n print(\"%0.4f\" % best_single_thres)\n print('\\n')\n print('*best_score*\\n')\n print('%0.4f\\n' % best_single_thres_score)\n\n # per class threshold\n best_thresholds = np.ones(nClass) * best_single_thres\n best_multi_thres_score = 0\n noChange = 0\n for iter in range(nClass * 10):\n print(\"thres scan iter %i\" % iter)\n trial_thresholds = best_thresholds.copy()\n targetClass = iter % nClass\n for i, t in enumerate(tryVals):\n trial_thresholds[targetClass] = t\n scores[i] = fbeta_score(\n labels, probs > trial_thresholds, beta=2, average='samples')\n\n best_threshold = tryVals[scores.argmax()]\n best_multi_thres_score = scores.max()\n if best_threshold == best_thresholds[targetClass]:\n noChange += 1\n else:\n noChange = 0\n best_thresholds[targetClass] = best_threshold\n\n if noChange == nClass:\n break\n\n print('*best_threshold (per class)*\\n')\n print(np.array2string(best_thresholds, formatter={\n 'float_kind': lambda x: ' %.3f' % x}, separator=','))\n print('\\n')\n print('*best_score*\\n')\n print('%0.4f\\n' % best_multi_thres_score)\n\n return best_single_thres, best_thresholds\n\n\ndef do_predict(net, dataset, batch_size=20, silent=True):\n if use_gpu:\n net.cuda().eval()\n else:\n net.eval()\n\n num_classes = len(CLASS_NAMES)\n logits = np.zeros((len(dataset), num_classes), np.float32)\n probs = np.zeros((len(dataset), num_classes), np.float32)\n\n tot_samples = 0\n\n loader = DataLoader(\n dataset,\n sampler=SequentialSampler(dataset), # None,\n batch_size=batch_size,\n # drop_last = False,\n num_workers=0,\n pin_memory=True)\n\n for it, batch in enumerate(loader, 0):\n if not silent:\n print(\"predict batch %i / %i\" % (it, len(loader)))\n # images = batch['tif'][:,1:,:,:] #IR R G B to R G B\n images = batch[SRC]\n if SRC == 'tif':\n if CH == 'rgb':\n images = images[:, 1:, :, :] # IR R G B to R G B\n if CH == 'irrg':\n images = images[:, :3, :, :] # IR R G B to IR R G\n if CH == 'NIR':\n images = images[:, 0:1, :, :] # NIR\n if CH == 'irrgb':\n pass\n\n batch_size = len(images)\n tot_samples += batch_size\n start = tot_samples - batch_size\n end = tot_samples\n\n # forward\n if use_gpu:\n ls, ps = net(Variable(images.cuda(), volatile=True))\n else:\n ls, ps = net(Variable(images, volatile=True))\n logits[start:end] = ls.data.cpu().numpy().reshape(-1, num_classes)\n probs[start:end] = ps.data.cpu().numpy().reshape(-1, num_classes)\n\n assert(len(dataset) == tot_samples)\n\n return logits, probs\n\n\ndef do_submit(prob, thres, imgKeys, outfile=\"submit.csv\"):\n tagsVec = probs > thres\n tagsCol = []\n for arow in tagsVec:\n tags = [CLASS_NAMES[i] for i in np.where(arow)[0]]\n tags = \" \".join(tags)\n tagsCol.append(tags)\n output = pd.DataFrame()\n output['image_name'] = imgKeys\n output['tags'] = tagsCol\n output.to_csv(outfile, index=False)\n\n\ndef get_model(init_file=None):\n print('** net setting **\\n')\n num_classes = len(CLASS_NAMES)\n net = Net(in_shape=(NCH, SIZE, SIZE), num_classes=num_classes)\n print('%s\\n\\n' % (type(net)))\n print('\\n')\n\n # for param in net.parameters():\n # param.requires_grad = False\n # untrainable_layers = [\n # net.conv1,\n # #net.bn1,\n # net.relu,\n # net.maxpool,\n # net.layer1,\n # net.layer2,\n # net.layer3\n #]\n # for aLayer in untrainable_layers:\n # for param in aLayer.parameters():\n # param.requires_grad = False\n\n #trainable_layers = [net.layer4, net.fc]\n #trainable_paras = []\n # for aLayer in trainable_layers:\n # for param in aLayer.parameters():\n # param.requires_grad = True\n # trainable_paras.append(param)\n\n optimizer = optim.Adam(net.parameters())\n # optimizer = optim.SGD(net.parameters(), lr=0.1,\n # momentum=0.9, weight_decay=0.0005) # 0.0005\n # optimizer = optim.SGD(trainable_paras, lr=0.1, momentum=0.9,\n # weight_decay=0.0005) ###0.0005\n\n # resume from previous ----------------------------------\n start_epoch = 0\n if init_file is not None:\n init_content = torch.load(init_file)\n if isinstance(init_content, dict):\n if 'epoch' in init_content:\n # checkpoint\n start_epoch = init_content['epoch']\n optimizer.load_state_dict(init_content['optimizer_state'])\n load_model_weight(net, init_content[\n 'model_state'], skip_list=[])\n else:\n # pretrained weights\n if CH == 'irrgb':\n skip_list = ['conv1.weight', 'fc.weight', 'fc.bias']\n load_model_weight(net, init_content, skip_list=skip_list)\n tmp = init_content['conv1.weight']\n if isinstance(tmp, torch.nn.Parameter):\n tmp = tmp.data\n net.state_dict()['conv1.weight'][:, 1:, :, :] = tmp\n elif CH == 'NIR':\n # pretrained weights for inception model\n skip_list = ['Conv2d_1a_3x3.conv.weight',\n 'fc.weight', 'fc.bias']\n load_model_weight(\n net, init_content, skip_list=skip_list)\n tmp = torch.mean(init_content[\n 'Conv2d_1a_3x3.conv.weight'], 1)\n if isinstance(tmp, torch.nn.Parameter):\n tmp = tmp.data\n net.state_dict()['Conv2d_1a_3x3.conv.weight'][\n :, 0, :, :] = tmp\n else:\n skip_list = ['fc.weight', 'fc.bias']\n load_model_weight(net, init_content, skip_list=skip_list)\n else:\n # full model\n net = init_content\n\n return net, optimizer, start_epoch\n\n\ndef do_training(out_dir='../../output/inception_tif_NIR_out'):\n\n init_file = '../../input/inception_v3_google-1a9a5a14.pth'\n\n # ------------------------------------\n os.makedirs(out_dir + '/snap', exist_ok=True)\n # os.makedirs(out_dir + '/checkpoint', exist_ok=True)\n\n print('\\n--- [START %s] %s\\n\\n' %\n (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), '-' * 64))\n print('** some experiment setting **\\n')\n print('\\tSEED = %u\\n' % SEED)\n print('\\tfile = %s\\n' % __file__)\n print('\\tout_dir = %s\\n' % out_dir)\n print('\\n')\n\n # dataset ----------------------------------------\n print('** dataset setting **\\n')\n num_classes = len(CLASS_NAMES)\n batch_size = 20 # 48 #96 #96 #80 #96 #96 #96 #32 #96 #128 #\n\n train_dataset = KgForestDataset('train_35479.txt',\n # train_dataset =\n # KgForestDataset('train_320.txt',\n transform=[\n # tif_color_corr,\n augment,\n img_to_tensor,\n ],\n outfields=[SRC, 'label'],\n height=SIZE, width=SIZE,\n )\n\n train_loader = DataLoader(\n train_dataset,\n sampler=RandomSampler(train_dataset),\n batch_size=batch_size,\n # drop_last = True,\n num_workers=2,\n pin_memory=True)\n\n test_dataset = KgForestDataset('val_5000.txt',\n # test_dataset =\n # KgForestDataset('val_320.txt',\n height=SIZE, width=SIZE,\n transform=[\n # tif_color_corr,\n img_to_tensor,\n ],\n outfields=[SRC, 'label'],\n cacheGB=6,\n )\n\n # num worker = 0 is important\n test_loader = DataLoader(\n test_dataset,\n sampler=SequentialSampler(test_dataset), # None,\n batch_size=batch_size,\n # drop_last = False,\n num_workers=0,\n pin_memory=True)\n\n print('\\tbatch_size = %d\\n' % batch_size)\n print('\\ttrain_loader.sampler = %s\\n' % (str(train_loader.sampler)))\n print('\\ttest_loader.sampler = %s\\n' % (str(test_loader.sampler)))\n print('\\n')\n\n net, optimizer, start_epoch = get_model(init_file)\n\n if use_gpu:\n net.cuda()\n\n # optimiser ----------------------------------\n # LR = StepLR([ (0,0.1), (10,0.01), (25,0.005), (35,0.001), (40,0.0001), (43,-1)])\n # fine tunning\n # LR = StepLR([(0, 0.01), (10, 0.005),\n # (23, 0.001), (35, 0.0001), (38, -1)])\n # LR = CyclicLR(base_lr=0.001, max_lr=0.01, step=5., mode='triangular', gamma=1., scale_fn=None, scale_mode='cycle')\n\n num_epoches = 50 # 100\n it_print = 20 # 20\n epoch_test = 1\n epoch_save = 5\n\n # start training here! ##############################################3\n print('** start training here! **\\n')\n\n print(' optimizer=%s\\n' % str(optimizer))\n # print(' LR=%s\\n\\n' % str(LR))\n print(' epoch iter | smooth_loss | train_loss (acc) | valid_loss (acc) | min\\n')\n print('----------------------------------------------------------------------------------------\\n')\n\n smooth_loss = 0.0\n train_loss = np.nan\n train_acc = np.nan\n test_loss = np.nan\n test_acc = np.nan\n best_acc = 0\n time = 0\n\n start0 = timer()\n for epoch in range(start_epoch, num_epoches): # loop over the dataset multiple times\n start = timer()\n\n #---learning rate schduler ------------------------------\n # lr = LR.get_rate(epoch, num_epoches)\n # if lr < 0:\n # break\n\n # adjust_learning_rate(optimizer, lr)\n #--------------------------------------------------------\n\n smooth_loss_sum = 0.0\n smooth_loss_n = 0\n if use_gpu:\n net.cuda().train()\n else:\n net.train()\n num_its = len(train_loader)\n for it, batch in enumerate(train_loader, 0):\n # images = batch['tif'][:,1:,:,:] #IR R G B to R G B\n images = batch[SRC]\n if SRC == 'tif':\n if CH == 'rgb':\n images = images[:, 1:, :, :] # IR R G B to R G B\n if CH == 'irrg':\n images = images[:, :3, :, :] # IR R G B to IR R G\n if CH == 'NIR':\n images = images[:, 0:1, :, :] # NIR\n if CH == 'irrgb':\n pass\n labels = batch['label'].float()\n if use_gpu:\n logits, probs = net(Variable(images.cuda()))\n loss = loss_func(logits, labels.cuda())\n else:\n logits, probs = net(Variable(images))\n loss = loss_func(logits, labels)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # additional metrics\n smooth_loss_sum += loss.data[0]\n smooth_loss_n += 1\n\n # print statistics\n if it % it_print == it_print - 1:\n smooth_loss = smooth_loss_sum / smooth_loss_n\n smooth_loss_sum = 0.0\n smooth_loss_n = 0\n\n if use_gpu:\n train_acc = multi_f_measure(probs.data, labels.cuda())\n else:\n train_acc = multi_f_measure(probs.data, labels)\n train_loss = loss.data[0]\n\n print('\\r%5.1f %5d | %0.4f | %0.4f %6.4f | ... ' %\n (epoch + it / num_its, it + 1,\n smooth_loss, train_loss, train_acc),\n end='', flush=True)\n\n #---- end of one epoch -----\n end = timer()\n time = (end - start) / 60\n\n if epoch % epoch_test == epoch_test - 1 or epoch == num_epoches - 1:\n if use_gpu:\n net.cuda().eval()\n else:\n net.eval()\n test_logits, test_probs = do_predict(net, test_dataset)\n test_labels = torch.from_numpy(\n test_dataset.df[CLASS_NAMES].values.astype(np.float32))\n test_acc = f2_score(test_probs, test_labels.numpy())\n test_loss = loss_func(torch.autograd.Variable(\n torch.from_numpy(test_logits)), test_labels).data[0]\n\n print('\\r', end='', flush=True)\n print('%5.1f %5d | %0.4f | %0.4f %6.4f | %0.4f %6.4f | %3.1f min \\n' %\n (epoch + 1, it + 1, smooth_loss, train_loss, train_acc, test_loss, test_acc, time))\n\n if test_acc > best_acc:\n best_acc = test_acc\n torch.save(net, out_dir + '/snap/best_acc_inception_%s_%03d.torch' %\n ((\"%.4f\" % best_acc).replace('.', 'd'), epoch + 1))\n # torch.save(net, out_dir + '/snap/best_acc_inception.torch')\n\n # if epoch % epoch_save == epoch_save - 1 or epoch == num_epoches - 1:\n #torch.save(net, out_dir +'/snap/%03d.torch'%(epoch+1))\n # torch.save({\n # 'state_dict': net.state_dict(),\n # 'optimizer': optimizer.state_dict(),\n # 'epoch': epoch,\n # }, out_dir + '/checkpoint/%03d.pth' % (epoch + 1))\n # https://github.com/pytorch/examples/blob/master/imagenet/main.py\n\n #---- end of all epoches -----\n end0 = timer()\n time0 = (end0 - start0) / 60\n\n # check : load model and re-test\n torch.save(net, out_dir + '/snap/final.torch')\n\n net = torch.load(out_dir + '/snap/final.torch')\n if use_gpu:\n net.cuda().eval()\n else:\n net.eval()\n test_logits, test_probs = do_predict(net, test_dataset)\n test_labels = torch.from_numpy(\n test_dataset.df[CLASS_NAMES].values.astype(np.float32))\n test_acc = f2_score(test_probs, test_labels.numpy())\n test_loss = loss_func(torch.autograd.Variable(\n torch.from_numpy(test_logits)), test_labels).data[0]\n\n print('\\n')\n print('%s:\\n' % (out_dir + '/snap/final.torch'))\n print('\\tall time to train=%0.1f min\\n' % (time0))\n print('\\ttest_loss=%f, test_acc=%f\\n' % (test_loss, test_acc))\n\n return net\n\nif __name__ == '__main__':\n print('%s: calling main function ... ' % os.path.basename(__file__))\n\n do_training(out_dir='../../output/inception_tif_NIR_out')\n\n # find thres\n #net,_,_ = get_model(\"../../output/resnet34_tif_irrgb_nocorr_out/snap/best_acc_0d9221_026.torch\")\n # train_dataset = KgForestDataset('labeled.txt',\n # transform=[\n # #tif_color_corr,\n # img_to_tensor,\n # ],\n # outfields = [SRC, 'label'],\n # height=SIZE, width=SIZE,\n # )\n #logits, probs = do_predict(net, train_dataset, silent=False)\n #labels = train_dataset.df[CLASS_NAMES].values.astype(np.float32)\n #do_thresholds(probs, labels)\n\n # do submit\n # net, _, _ = get_model(\n # \"../../output/resnet34_tif_irrgb_nocorr_out/snap/best_acc_0d9221_026.torch\")\n test_dataset = KgForestDataset('unlabeled.txt',\n transform=[\n # tif_color_corr,\n img_to_tensor,\n ],\n outfields=[SRC],\n height=SIZE, width=SIZE,\n )\n logits, probs = do_predict(net, test_dataset, silent=False)\n\n # from resnet34_tif_rgb\n ##best_threshold = np.ones(len(CLASS_NAMES))* 0.2200\n # best_thresholds = np.array( [ 0.170, 0.245, 0.150, 0.195, 0.145, 0.230, 0.225, 0.245, 0.190, 0.240,\n # 0.095, 0.305, 0.255, 0.135, 0.145, 0.240, 0.060] )\n\n # from resnet34_tif_irgb\n ##best_threshold = np.ones(len(CLASS_NAMES))* 0.2250\n # best_thresholds = np.array([ 0.190, 0.250, 0.225, 0.125, 0.270, 0.235, 0.200, 0.240, 0.240, 0.250,\n # 0.120, 0.100, 0.240, 0.150, 0.210, 0.190, 0.050])\n\n # from resnet34_tif_irgb\n #best_threshold = np.ones(len(CLASS_NAMES))* 0.2200\n # best_thresholds = np.array(\n # [ 0.195, 0.235, 0.230, 0.095, 0.295, 0.215, 0.175, 0.250, 0.220, 0.250,\n # 0.130, 0.345, 0.145, 0.170, 0.215, 0.260, 0.090]\n # )\n\n # from resnet34_tif_irrgb\n best_threshold = np.ones(len(CLASS_NAMES)) * 0.2100\n best_thresholds = np.array(\n [0.155, 0.260, 0.225, 0.110, 0.280, 0.240, 0.225, 0.205, 0.205, 0.250,\n 0.080, 0.145, 0.180, 0.075, 0.130, 0.160, 0.075]\n )\n do_submit(probs, best_thresholds, test_dataset.df.index,\n \"submit_resnet34_tif_irrgb.csv\")\n","sub_path":"DVS_Inception/nnPyTorch/train-forest-inception_NIR.py","file_name":"train-forest-inception_NIR.py","file_ext":"py","file_size_in_byte":19671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"336351578","text":"import argparse\n\nimport numpy as np\nimport pandas as pd\nfrom sentence_transformers import SentenceTransformer\n\n\nclass BertEncoder:\n def __init__(self, model_name='bert-base-nli-stsb-mean-tokens'):\n self.model = SentenceTransformer(model_name)\n\n def encode(self, sentences):\n return np.stack(self.model.encode(sentences, show_progress_bar=True))\n\n\ndef main():\n argument_parser = argparse.ArgumentParser()\n argument_parser.add_argument(\"--data_src\", type=str,\n help='Input CSV file containing input data', required=False, default=None)\n args = argument_parser.parse_args()\n encoder = BertEncoder()\n sentences = pd.read_csv(args.corpus_file, index_col=0)['sentence'].values\n embs = encoder.encode(sentences)\n print(embs)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/encoders/bert_encoder.py","file_name":"bert_encoder.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"223077530","text":"# -*- coding : utf-8 -*-\r\n\r\nimport os, sys, subprocess\r\nimport urllib.request\r\nimport threading\r\nfrom PyQt5 import QtCore, QtWidgets\r\nfrom UI.updateUI import *\r\n\r\n#下载路径\r\nDOWNLOAD_PATH = \"https://raw.githubusercontent.com/q381528589/Publisher/master/Addwork/\"\r\nAPP_NAME = \"AddWork.exe\"\r\n\r\nclass CDownload(threading.Thread):\r\n Percent = 0\r\n bDownload = False\r\n \r\n def __init__(self):\r\n super(CDownload, self).__init__()\r\n \r\n def run(self):\r\n self.__HandleAddwork()\r\n return\r\n\r\n def Schedule(self, a,b,c):\r\n '''''\r\n a:已经下载的数据块\r\n b:数据块的大小\r\n c:远程文件的大小\r\n '''\r\n self.Percent = 100.0 * a * b / c\r\n if self.Percent > 100 :\r\n self.Percent = 100\r\n #print ('%.1f%%' % self.Percent)\r\n \r\n def __HandleAddwork(self):\r\n #获取网络上最新版本\r\n try:\r\n urllib.request.urlretrieve(DOWNLOAD_PATH+APP_NAME, \r\n \"./%s.download\" % (APP_NAME), self.Schedule)\r\n except:\r\n print (\"获取更新程序失败\")\r\n return\r\n \r\n #关闭程序\r\n try:\r\n subprocess.check_call(\"taskkill /F /IM %s\" % (APP_NAME))\r\n except:\r\n #TODO:用户手动关闭程序\r\n pass\r\n \r\n #下载更新完成\r\n self.bDownload = True\r\n return\r\n \r\nclass CUpdate(QtWidgets.QDialog, Ui_Dialog):\r\n __translate = QtCore.QCoreApplication.translate\r\n __cDownload = CDownload()\r\n __bShow = False\r\n \r\n def __init__(self):\r\n super(CUpdate, self).__init__()\r\n self.setupUi(self)\r\n self.Btn_OK.clicked.connect(self.__StartDownload)\r\n \r\n def closeEvent(self, event):\r\n #如果没有更新成功,在直接退出\r\n if (False == self.__cDownload.bDownload):\r\n event.accept()\r\n return\r\n \r\n #重命名文件\r\n if (os.path.exists(\"./%s\" % (APP_NAME))):\r\n os.remove(\"./%s\" % (APP_NAME))\r\n os.rename(\"./%s.download\" % (APP_NAME), \"./%s\" % (APP_NAME))\r\n #写入版本文件\r\n self.__WriteLocalVersion()\r\n \r\n #关闭窗口\r\n event.accept()\r\n return\r\n \r\n def Update(self):\r\n #是否需要更新\r\n __bUpdate = False\r\n #update程序版本\r\n __UpdateVersion=\"0.0.0.0\"\r\n #Addwork程序版本\r\n __AddWorkVersion=\"0.0.0.0\"\r\n \r\n #获取自身版本号和其它版本号\r\n if (0 != self.__ReadLocalVersion()):\r\n #TODO:后期版本更新:文件不存在时校验MD5,两者均相同下载version.txt,否则执行后续更新步骤\r\n print (\"读取本地文件发生错误\")\r\n sys.exit()\r\n #获取网络上最新版本号\r\n try:\r\n f = urllib.request.urlopen(DOWNLOAD_PATH+\"version.txt\")\r\n data = f.read().decode(\"utf-8\")\r\n f.close()\r\n except:\r\n print (\"获取版本信息失败\")\r\n sys.exit()\r\n VersionList = data.split(\"\\r\\n\")\r\n for VersionInfo in VersionList:\r\n #更新update\r\n if (-1 != VersionInfo.find(\"update\")):\r\n Version = VersionInfo.split('=')\r\n if (2 > len(Version)):\r\n continue\r\n self.__bUpdate = self.__CheckVersion(self.__UpdateVersion, Version[1])\r\n if (False == self.__bUpdate):\r\n continue\r\n self.__UpdateSelf()\r\n #写入版本文件\r\n self.__UpdateVersion = Version[1]\r\n self.__WriteLocalVersion()\r\n #更新AddWork\r\n elif (-1 != VersionInfo.find(\"AddWork\")):\r\n Version = VersionInfo.split('=')\r\n if (2 > len(Version)):\r\n continue\r\n self.__bUpdate = self.__CheckVersion(self.__AddWorkVersion, Version[1])\r\n if (False == self.__bUpdate):\r\n continue\r\n self.__UpdateAddwork(Version[1])\r\n #写入版本文件\r\n self.__AddWorkVersion = Version[1]\r\n \r\n #退出更新程序\r\n if (False == self.__bShow):\r\n sys.exit()\r\n return\r\n \r\n def __ReadLocalVersion(self):\r\n try:\r\n File = open(\"./version.txt\", 'r')\r\n Text = File.read()\r\n List = Text.split(\"\\n\")\r\n File.close()\r\n except:\r\n print (\"打开文件错误\")\r\n return -1\r\n \r\n for VersionInfo in List:\r\n #update版本\r\n if (-1 != VersionInfo.find(\"update\")):\r\n Version = VersionInfo.split('=')\r\n if (2 > len(Version)):\r\n continue\r\n self.__UpdateVersion = Version[1]\r\n #AddWork版本\r\n elif (-1 != VersionInfo.find(\"AddWork\")):\r\n Version = VersionInfo.split('=')\r\n if (2 > len(Version)):\r\n continue\r\n self.__AddWorkVersion = Version[1]\r\n \r\n return 0\r\n \r\n def __WriteLocalVersion(self):\r\n szTemp = \"update=%s\\n\" % (self.__UpdateVersion)\r\n szTemp += \"AddWork=%s\" % (self.__AddWorkVersion)\r\n try:\r\n File = open(\"./version.txt\", 'w')\r\n File.write(szTemp)\r\n File.close()\r\n except IOError as err:\r\n print (\"写入文件错误:%s\" % (str(err)))\r\n \r\n return\r\n \r\n def __CheckVersion(self, OldVersion, NewVersion):\r\n OldList = OldVersion.split('.')\r\n NewList = NewVersion.split('.')\r\n \r\n if (4!=len(NewList) or 4!=len(OldList)):\r\n return False\r\n \r\n #检查版本\r\n if (int(NewList[0]) > int(OldList[0])):\r\n #大版本更新\r\n return True\r\n elif (int(NewList[0]) < int(OldList[0])):\r\n return False\r\n \r\n if (int(NewList[1]) > int (OldList[1])):\r\n return True\r\n elif (int(NewList[1]) < int (OldList[1])):\r\n return False\r\n \r\n if (int(NewList[2]) > int (OldList[2])):\r\n return True\r\n elif (int(NewList[2]) < int (OldList[2])):\r\n return False\r\n \r\n #svn版本号更新的不算在列\r\n return False\r\n \r\n def __UpdateSelf(self):#TODO:多线程\r\n #静默更新\r\n #获取网络上最新版本\r\n try:\r\n f = urllib.request.urlopen(DOWNLOAD_PATH+\"update.exe\")\r\n data = f.read()\r\n f.close()\r\n except:\r\n print (\"获取更新程序失败\")\r\n sys.exit()\r\n #写至缓存文件\r\n try:\r\n File = open(\"./update.exe.download\", \"wb\")\r\n File.write(data)\r\n File.close()\r\n except:\r\n print (\"写入更新程序失败\")\r\n sys.exit()\r\n #重命名文件\r\n if (os.path.exists(\"./update.exe.tmp\")):\r\n os.remove(\"./update.exe.tmp\")\r\n os.rename(\"./update.exe.download\", \"./update.exe.tmp\")\r\n \r\n return\r\n \r\n def __UpdateProcessBar(self):\r\n while (True == self.__cDownload.isAlive()): \r\n self.progressBar.setValue(self.__cDownload.Percent) \r\n QtCore.QThread.msleep(100)\r\n QtWidgets.QApplication.processEvents()\r\n return\r\n \r\n def __UpdateAddwork(self, CurVersion):\r\n self.label.setText(self.__translate(\"Dialog\", \"发现新版本:%s,是否更新?\") % (CurVersion))\r\n self.progressBar.hide()\r\n self.__bShow = True\r\n self.show()\r\n return\r\n \r\n def __StartDownload(self):\r\n self.label.hide()\r\n self.Btn_OK.setText(self.__translate(\"Dialog\", \"下载中……\"))\r\n self.Btn_Cancel.setText(self.__translate(\"Dialog\", \"取消\"))\r\n self.Btn_OK.setEnabled(False)\r\n self.progressBar.show()\r\n self.__cDownload.setDaemon(True)\r\n self.__cDownload.start()\r\n self.__UpdateProcessBar()\r\n self.Btn_OK.hide()\r\n self.Btn_Cancel.setText(self.__translate(\"Dialog\", \"完成\"))\r\n return\r\n \r\nif __name__ == \"__main__\":\r\n #加载QT窗口\r\n app = QtWidgets.QApplication(sys.argv)\r\n cUpdate = CUpdate()\r\n cUpdate.Update()\r\n sys.exit(app.exec_())","sub_path":"Codes/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":8479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"101446402","text":"#!/usr/bin/env python\n\nfrom __future__ import division\n\nimport argparse\nimport datetime\nimport functools\nimport os.path as osp\nimport PIL.Image\nimport random\nimport socket\n\nimport chainer\nfrom chainer import training\nfrom chainer.training import extensions\nimport chainer_mask_rcnn as cmr\nfrom chainercv import transforms\nfrom chainercv.utils.mask.mask_to_bbox import mask_to_bbox\nimport fcn\nimport numpy as np\n\nfrom grasp_data_generator.datasets import OIDualarmGraspDatasetV1\nfrom grasp_data_generator.extensions import ManualScheduler\nfrom grasp_data_generator.models import OccludedMaskRCNNResNet101\nfrom grasp_data_generator.models import OccludedMaskRCNNTrainChain\n\n\nthisdir = osp.dirname(osp.abspath(__file__))\n\n\nclass Transform(object):\n\n def __init__(self, occluded_mask_rcnn):\n self.occluded_mask_rcnn = occluded_mask_rcnn\n\n def __call__(self, in_data):\n img, ins_label, label, _, _ = in_data\n bbox = mask_to_bbox(ins_label != 0)\n _, orig_H, orig_W = img.shape\n img = self.occluded_mask_rcnn.prepare(img)\n _, H, W = img.shape\n scale = H / orig_H\n ins_label = transforms.resize(ins_label, (H, W), PIL.Image.NEAREST)\n bbox = transforms.resize_bbox(bbox, (orig_H, orig_W), (H, W))\n\n return img, ins_label, label, bbox, scale\n\n\ndef main():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\n '--dataset', choices=['v1'], default='v1', help='Dataset version')\n parser.add_argument('--gpu', '-g', type=int, help='GPU id.')\n parser.add_argument('--multi-node', action='store_true',\n help='use multi node')\n parser.add_argument('--max-epoch', type=float,\n default=12, help='epoch')\n parser.add_argument('--seed', '-s', type=int, default=1234)\n args = parser.parse_args()\n\n if args.multi_node:\n import chainermn\n comm = chainermn.create_communicator('hierarchical')\n device = comm.intra_rank\n\n args.n_node = comm.inter_size\n args.n_gpu = comm.size\n chainer.cuda.get_device_from_id(device).use()\n else:\n args.n_node = 1\n args.n_gpu = 1\n chainer.cuda.get_device_from_id(args.gpu).use()\n device = args.gpu\n\n now = datetime.datetime.now()\n random.seed(args.seed)\n np.random.seed(args.seed)\n\n # Default Config\n # args.min_size = 800\n # args.max_size = 1333\n # args.anchor_scales = (2, 4, 8, 16, 32)\n args.min_size = 600\n args.max_size = 1000\n args.anchor_scales = (4, 8, 16, 32)\n args.rpn_dim = 512\n\n if not args.multi_node or comm.rank == 0:\n out = osp.join(thisdir, 'logs', now.strftime('%Y%m%d_%H%M%S.%f'))\n else:\n out = None\n\n if args.multi_node:\n args.out = comm.bcast_obj(out)\n else:\n args.out = out\n del out\n\n # 0.00125 * 8 = 0.01 in original\n args.batch_size = 1 * args.n_gpu\n args.lr = 0.00125 * args.batch_size\n args.weight_decay = 0.0001\n\n args.step_size = [2 / 3 * args.max_epoch, 8 / 9 * args.max_epoch]\n\n # -------------------------------------------------------------------------\n # Dataset\n if args.dataset == 'v1':\n train_data = OIDualarmGraspDatasetV1(split='train')\n else:\n raise ValueError(\n 'Given dataset is not supported: {}'.format(args.dataset))\n # test_data = OIDualarmGraspDatasetV1(split='test', imgaug=False)\n label_names = train_data.label_names\n\n # -------------------------------------------------------------------------\n # Model + Optimizer.\n occluded_mask_rcnn = OccludedMaskRCNNResNet101(\n n_fg_class=len(label_names),\n anchor_scales=args.anchor_scales,\n min_size=args.min_size,\n max_size=args.max_size,\n rpn_dim=args.rpn_dim)\n occluded_mask_rcnn.nms_thresh = 0.3\n occluded_mask_rcnn.score_thresh = 0.05\n\n model = OccludedMaskRCNNTrainChain(occluded_mask_rcnn)\n if args.multi_node or args.gpu >= 0:\n model.to_gpu()\n\n optimizer = chainer.optimizers.MomentumSGD(lr=args.lr, momentum=0.9)\n if args.multi_node:\n optimizer = chainermn.create_multi_node_optimizer(optimizer, comm)\n optimizer.setup(model)\n optimizer.add_hook(chainer.optimizer.WeightDecay(rate=args.weight_decay))\n\n occluded_mask_rcnn.extractor.conv1.disable_update()\n occluded_mask_rcnn.extractor.bn1.disable_update()\n occluded_mask_rcnn.extractor.res2.disable_update()\n for link in occluded_mask_rcnn.links():\n if isinstance(link, cmr.links.AffineChannel2D):\n link.disable_update()\n\n # -------------------------------------------------------------------------\n # Transform dataset.\n train_data = chainer.datasets.TransformDataset(\n train_data, Transform(occluded_mask_rcnn))\n\n # -------------------------------------------------------------------------\n # Iterator.\n\n if args.multi_node:\n if comm.rank != 0:\n train_data = None\n train_data = chainermn.scatter_dataset(train_data, comm, shuffle=True)\n\n # for training\n train_iter = chainer.iterators.SerialIterator(train_data, batch_size=1)\n # test_iter = chainer.iterators.SerialIterator(\n # test_data, batch_size=1, repeat=False, shuffle=False)\n\n # -------------------------------------------------------------------------\n converter = functools.partial(\n cmr.datasets.concat_examples,\n padding=0,\n # img, ins_labels, labels, bboxes, scales\n indices_concat=[0, 1, 2, 4], # img, ins_labels, labels, _, scales\n indices_to_device=[0, 3], # img, bbox\n )\n updater = chainer.training.updater.StandardUpdater(\n train_iter, optimizer, device=device,\n converter=converter)\n\n trainer = training.Trainer(\n updater, (args.max_epoch, 'epoch'), out=args.out)\n\n def lr_schedule(updater):\n base_lr = 0.0005 * 1.25 * args.batch_size\n if args.multi_node:\n base_lr = base_lr * comm.size\n warm_up_duration = 500\n warm_up_rate = 1 / 3\n\n iteration = updater.iteration\n if iteration < warm_up_duration:\n rate = warm_up_rate \\\n + (1 - warm_up_rate) * iteration / warm_up_duration\n elif iteration < (args.step_size[0] * len(train_data)):\n rate = 1\n elif iteration < (args.step_size[1] * len(train_data)):\n rate = 0.1\n else:\n rate = 0.01\n return base_lr * rate\n\n trainer.extend(ManualScheduler('lr', lr_schedule))\n\n # eval_interval = 1, 'epoch'\n log_interval = 20, 'iteration'\n plot_interval = 0.1, 'epoch'\n print_interval = 20, 'iteration'\n\n if not args.multi_node or comm.rank == 0:\n # evaluator = InstanceSegmentationVOCEvaluator(\n # test_iter, model.occluded_mask_rcnn, device=device,\n # use_07_metric=False, label_names=label_names)\n # trainer.extend(evaluator, trigger=eval_interval)\n # trainer.extend(\n # extensions.snapshot_object(\n # model.occluded_mask_rcnn, 'snapshot_model.npz'),\n # trigger=training.triggers.MaxValueTrigger(\n # 'validation/main/mpq', eval_interval))\n model_name = model.occluded_mask_rcnn.__class__.__name__\n trainer.extend(\n chainer.training.extensions.snapshot_object(\n model.occluded_mask_rcnn,\n savefun=chainer.serializers.save_npz,\n filename='%s_model_iter_{.updater.iteration}.npz'\n % model_name),\n trigger=(1, 'epoch'))\n args.git_hash = cmr.utils.git_hash()\n args.hostname = socket.gethostname()\n trainer.extend(fcn.extensions.ParamsReport(args.__dict__))\n # trainer.extend(\n # InstanceSegmentationVisReport(\n # test_iter, model.occluded_mask_rcnn,\n # label_names=label_names),\n # trigger=eval_interval)\n trainer.extend(chainer.training.extensions.observe_lr(),\n trigger=log_interval)\n trainer.extend(extensions.LogReport(trigger=log_interval))\n trainer.extend(extensions.PrintReport(\n ['iteration', 'epoch', 'elapsed_time', 'lr',\n 'main/loss',\n 'main/roi_loc_loss',\n 'main/roi_cls_loss',\n 'main/roi_mask_loss',\n 'main/rpn_loc_loss',\n 'main/rpn_cls_loss',\n 'validation/main/mpq']),\n trigger=print_interval,\n )\n trainer.extend(extensions.ProgressBar(update_interval=10))\n\n # plot\n assert extensions.PlotReport.available()\n trainer.extend(\n extensions.PlotReport(\n ['main/loss',\n 'main/roi_loc_loss',\n 'main/roi_cls_loss',\n 'main/roi_mask_loss',\n 'main/rpn_loc_loss',\n 'main/rpn_cls_loss'],\n file_name='loss.png', trigger=plot_interval,\n ),\n trigger=plot_interval,\n )\n # trainer.extend(\n # extensions.PlotReport(\n # ['validation/main/map',\n # 'validation/main/msq',\n # 'validation/main/mdq',\n # 'validation/main/mpq'],\n # file_name='accuracy.png', trigger=plot_interval\n # ),\n # trigger=eval_interval,\n # )\n\n trainer.extend(extensions.dump_graph('main/loss'))\n\n trainer.run()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"demos/grasp_data_generator/experiments/occluded_mask_rcnn/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"29991085","text":"import sys\nimport os\nsys.path.append(os.path.dirname(os.path.abspath(__file__)) + \"/..\")\n\nimport numpy as np\nimport logging\nimport pandas as pd\nimport pickle as pkl\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nimport torch\nimport torch.nn as nn\nimport torch.utils.data as utils\nfrom models.eigan import DiscriminatorFCN\nfrom common.torchsummary import summary\nfrom common.utility import log_shapes, log_time, torch_device,\\\n time_stp, logger, sep, weights_init, load_processed_data\nfrom common.argparser import comparison_argparse\n\n\ndef main(\n model,\n time_stamp,\n device,\n encoding_dim,\n hidden_dim,\n leaky,\n test_size,\n batch_size,\n n_epochs,\n shuffle,\n lr,\n expt,\n pca_ckpt,\n autoencoder_ckpt,\n encoder_ckpt,\n):\n device = torch_device(device=device)\n\n X, targets = load_processed_data(\n expt, 'processed_data_X_targets.pkl')\n log_shapes(\n [X] + [targets[i] for i in targets],\n locals(),\n 'Dataset loaded'\n )\n\n targets = {i: elem.reshape(-1, 1) for i, elem in targets.items()}\n\n X_train, X_valid, \\\n y_adt_train, y_adt_valid = train_test_split(\n X,\n targets['admission_type'],\n test_size=test_size,\n stratify=pd.DataFrame(np.concatenate(\n (\n targets['admission_type'],\n ), axis=1)\n )\n )\n\n log_shapes(\n [\n X_train, X_valid,\n y_adt_train, y_adt_valid,\n ],\n locals(),\n 'Data size after train test split'\n )\n\n y_train = y_adt_train\n y_valid = y_adt_valid\n\n scaler = StandardScaler()\n X_normalized_train = scaler.fit_transform(X_train)\n X_normalized_valid = scaler.transform(X_valid)\n\n log_shapes([X_normalized_train, X_normalized_valid], locals())\n\n ckpts = {\n # 12A: checkpoints/mimic/n_advr_ind_gan_training_history_02_12_2020_19_30_38.pkl\n 0: 'checkpoints/mimic/n_advr_eigan_torch_model_02_12_2020_00_10_16_A_n_1_device_cuda_dim_256_hidden_512_batch_32768_epochs_1001_advr_0_encd_-0.1220_advr_0.4970.pkl',\n # 12A: checkpoints/mimic/n_advr_ind_gan_training_history_02_12_2020_19_30_38.pkl\n 1: 'checkpoints/mimic/n_advr_eigan_torch_model_02_12_2020_02_02_15_A_n_2_device_cuda_dim_256_hidden_512_batch_32768_epochs_1001_advr_1_encd_-0.1086_advr_0.4969.pkl',\n # 34A: checkpoints/mimic/n_advr_ind_gan_training_history_02_12_2020_20_01_01.pkl\n 2: 'checkpoints/mimic/n_advr_eigan_torch_model_02_12_2020_15_03_17_A_n_3_device_cuda_dim_256_hidden_512_batch_32768_epochs_1001_advr_2_encd_-0.0949_advr_0.4908.pkl',\n # 34A: checkpoints/mimic/n_advr_ind_gan_training_history_02_12_2020_20_01_01.pkl\n 3: 'checkpoints/mimic/n_advr_eigan_torch_model_02_12_2020_15_02_44_A_n_4_device_cuda_dim_256_hidden_512_batch_32768_epochs_1001_advr_3_encd_-0.1082_advr_0.4981.pkl',\n # 56A: checkpoints/mimic/n_advr_ind_gan_training_history_02_12_2020_23_07_22.pkl\n 4: 'checkpoints/mimic/n_advr_eigan_torch_model_02_12_2020_20_01_18_A_n_5_device_cuda_dim_256_hidden_512_batch_32768_epochs_1001_advr_4_encd_-0.1145_advr_0.4966.pkl',\n # 56A: checkpoints/mimic/n_advr_ind_gan_training_history_02_12_2020_23_07_22.pkl\n 5: 'checkpoints/mimic/n_advr_eigan_torch_model_02_12_2020_21_34_32_A_n_6_device_cuda_dim_256_hidden_512_batch_32768_epochs_1001_advr_5_encd_-0.1172_advr_0.4960.pkl',\n # 789A: checkpoints/mimic/n_advr_ind_gan_training_history_02_13_2020_13_54_53.pkl\n 6: 'checkpoints/mimic/n_advr_eigan_torch_model_02_12_2020_23_56_04_A_n_7_device_cuda_dim_256_hidden_512_batch_32768_epochs_1001_advr_6_encd_-0.0955_advr_0.4904.pkl',\n # 789A: checkpoints/mimic/n_advr_ind_gan_training_history_02_13_2020_13_54_53.pkl\n 7: 'checkpoints/mimic/n_advr_eigan_torch_model_02_12_2020_23_59_23_A_n_8_device_cuda_dim_256_hidden_512_batch_16384_epochs_1001_advr_7_encd_-0.1173_advr_0.4964.pkl',\n # 789A: checkpoints/mimic/n_advr_ind_gan_training_history_02_13_2020_13_54_53.pkl\n 8: 'checkpoints/mimic/n_advr_eigan_torch_model_02_13_2020_04_35_19_A_n_9_device_cuda_dim_256_hidden_512_batch_32768_epochs_1001_advr_8_encd_-0.1105_advr_0.4947.pkl',\n # nA: checkpoints/mimic/n_advr_ind_gan_training_history_02_13_2020_18_31_15.pkl\n 9: 'checkpoints/mimic/n_advr_eigan_torch_model_02_13_2020_13_32_21_A_n_10_device_cuda_dim_256_hidden_512_batch_32768_epochs_1001_advr_9_encd_-0.1104_advr_0.4955.pkl',\n }\n\n h = {}\n\n for idx, ckpt in ckpts.items():\n encoder = torch.load(ckpt, map_location=device)\n encoder.eval()\n\n optim = torch.optim.Adam\n criterionBCEWithLogits = nn.BCEWithLogitsLoss()\n\n h[idx] = {\n 'epoch_train': [],\n 'epoch_valid': [],\n 'advr_train': [],\n 'advr_valid': [],\n }\n\n dataset_train = utils.TensorDataset(\n torch.Tensor(X_normalized_train),\n torch.Tensor(y_train),\n )\n\n dataset_valid = utils.TensorDataset(\n torch.Tensor(X_normalized_valid),\n torch.Tensor(y_valid),\n )\n\n def transform(input_arg):\n return encoder(input_arg)\n\n dataloader_train = torch.utils.data.DataLoader(\n dataset_train,\n batch_size=batch_size,\n shuffle=shuffle,\n num_workers=1\n )\n\n dataloader_valid = torch.utils.data.DataLoader(\n dataset_valid,\n batch_size=batch_size,\n shuffle=shuffle,\n num_workers=1\n )\n\n clf = DiscriminatorFCN(\n encoding_dim, hidden_dim, 1,\n leaky).to(device)\n\n clf.apply(weights_init)\n\n sep('{} {}'.format(idx+1, 'ally'))\n summary(clf, input_size=(1, encoding_dim))\n\n optimizer = optim(clf.parameters(), lr=lr)\n\n # adversary 1\n sep(\"adversary with {} ally encoder\".format(idx+1))\n logging.info('{} \\t {} \\t {}'.format(\n 'Epoch',\n 'Advr Train',\n 'Advr Valid',\n ))\n\n for epoch in range(n_epochs):\n clf.train()\n\n nsamples = 0\n iloss_advr = 0\n for i, data in enumerate(dataloader_train, 0):\n X_train_torch = transform(data[0].to(device))\n y_advr_train_torch = data[1].to(device)\n\n optimizer.zero_grad()\n y_advr_train_hat_torch = clf(X_train_torch)\n\n loss_advr = criterionBCEWithLogits(\n y_advr_train_hat_torch, y_advr_train_torch)\n loss_advr.backward()\n optimizer.step()\n\n nsamples += 1\n iloss_advr += loss_advr.item()\n\n h[idx]['advr_train'].append(iloss_advr/nsamples)\n h[idx]['epoch_train'].append(epoch)\n\n if epoch % int(n_epochs/10) != 0:\n continue\n\n clf.eval()\n\n nsamples = 0\n iloss_advr = 0\n correct = 0\n total = 0\n\n for i, data in enumerate(dataloader_valid, 0):\n X_valid_torch = transform(data[0].to(device))\n y_advr_valid_torch = data[1].to(device)\n y_advr_valid_hat_torch = clf(X_valid_torch)\n\n valid_loss_advr = criterionBCEWithLogits(\n y_advr_valid_hat_torch, y_advr_valid_torch,)\n\n predicted = y_advr_valid_hat_torch > 0.5\n\n nsamples += 1\n iloss_advr += valid_loss_advr.item()\n total += y_advr_valid_torch.size(0)\n correct += (predicted == y_advr_valid_torch).sum().item()\n\n h[idx]['advr_valid'].append(iloss_advr/nsamples)\n h[idx]['epoch_valid'].append(epoch)\n\n logging.info(\n '{} \\t {:.8f} \\t {:.8f} \\t {:.8f}'.\n format(\n epoch,\n h[idx]['advr_train'][-1],\n h[idx]['advr_valid'][-1],\n correct/total\n ))\n\n checkpoint_location = \\\n 'checkpoints/{}/{}_training_history_{}.pkl'.format(\n expt, model, time_stamp)\n sep()\n logging.info('Saving: {}'.format(checkpoint_location))\n pkl.dump(h, open(checkpoint_location, 'wb'))\n\n\nif __name__ == \"__main__\":\n expt = 'mimic'\n model = 'n_advr_ind_gan'\n marker = 'A'\n pr_time, fl_time = time_stp()\n\n logger(expt, model, fl_time, marker)\n\n log_time('Start', pr_time)\n args = comparison_argparse()\n main(\n model=model,\n time_stamp=fl_time,\n device=args['device'],\n encoding_dim=args['dim'],\n hidden_dim=args['hidden_dim'],\n leaky=args['leaky'],\n test_size=args['test_size'],\n batch_size=args['batch_size'],\n n_epochs=args['n_epochs'],\n shuffle=args['shuffle'] == 1,\n lr=args['lr'],\n expt=args['expt'],\n pca_ckpt=args['pca_ckpt'],\n autoencoder_ckpt=args['autoencoder_ckpt'],\n encoder_ckpt=args['encoder_ckpt']\n )\n log_time('End', time_stp()[0])\n sep()\n","sub_path":"expt_mimic/training_on_gan_n_advr.py","file_name":"training_on_gan_n_advr.py","file_ext":"py","file_size_in_byte":9211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"227800902","text":"from queue import Queue\n\n\n# 定义 Queue 对象,并初始化容量为 10\nq = Queue(10)\n\n# 向队列中添加元素\nq.put('yang')\nq.put(4)\nq.put(['yan', 'xing'])\n\n# 从队列中取出元素,默认的队列是先进先出的\nq.get()\n# 'yang'\nq.get()\n# 4\nq.get()\n# ['yan', 'xing']\n","sub_path":"Basement/code/section_18/pqueue.py","file_name":"pqueue.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"58941251","text":"is_increasing = lambda pwd: not True in [pwd[i] > pwd[i + 1] for i in range(len(pwd) - 1)]\n\n# If we know that each succeeding value is greater,\n# then multiple occurrences of the same number must be \n# adjacent (not 6 unique elements)\nhas_adjacent = lambda pwd: len(set(pwd)) != 6\n\ndef is_larger_group(pwd):\n\tgroups = dict([(char, pwd.count(char)) for char in pwd])\n\treturn not 2 in groups.values()\n\ndef is_valid(pwd, part_2=False):\n\ts = str(pwd)\n\tcriteria = (part_2 and is_larger_group(s)) or (not has_adjacent(s) or not is_increasing(s))\n\treturn False if criteria else s\t\n\nif __name__ == '__main__':\n\twith open('input.txt', 'r') as f:\n\t\tFROM, TO = map(int, f.read().split(','))\n\n\t\t# Part 1\n\t\ta = [is_valid(p) for p in range(FROM, TO + 1)]\n\t\ta = list(filter(lambda x: x, a))\n\t\tprint(len(a))\n\n\t\t# Part 2\n\t\tv = [is_valid(p, part_2=True) for p in a]\n\t\tv = list(filter(lambda x: x, v))\n\t\tprint(len(v))","sub_path":"04/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"366814182","text":"# NOTE: Consider adding logging to capture the year, month, day of the geoIP Database file\n# Import modules needed for script to work\n# StringIO: This module implements a file-like class, StringIO, that reads and writes a \n# string buffer (also known as memory files).\n# ZipFile: The ZIP file format is a common archive and compression standard. This module \n# provides tools to create, read, write, append, and list a ZIP file\n# urlopen: This module provides a high-level interface for fetching data across the World \n# Wide Web. In particular, the urlopen() function is similar to the built-in function \n# open(), but accepts Universal Resource Locators (URLs) instead of filenames.\n# os: This module provides a portable way of using operating system dependent \n# functionality.\nfrom StringIO import StringIO\nfrom zipfile import ZipFile\nfrom urllib import urlopen\nfrom os.path import lexists\nfrom os import makedirs\n\n# Establish global variable used by the Python script\nipsetRulesFile = \"ipset.us.rules\"\nipsetRulesDir = \"/etc/ipset/US\"\nipsetName = \"usnetworks\"\nipsetType = \"hash:net\"\nipsetFamily = \"inet\"\nipsetHashSize = \"131072\"\nipsetmaxelem = \"100000\"\nzipMember = \"GeoLite2-Country-Blocks-IPv4.csv\"\ngeoipDBurl = \"http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country-CSV.zip\"\nusCountryID = \"6252001\"\n\n# Check to see if ipset rules directory exists, if it does not then create it.\nif not lexists(ipsetRulesDir):\n #print (\"INFO: \" + ipsetRulesDir + \" directory does not exist. Creating directory.\")\n makedirs(ipsetRulesDir)\n#else:\n# print (\"INFO: \" + ipsetRulesDir + \" already exists.\")\n \n# Create ipset file for writing out networks that are part of the United States\n#print (\"INFO: Creating file \" + ipsetRulesDir + \"/\" + ipsetRulesFile + \" for ipset rules.\")\nipsetfile = open(ipsetRulesDir + \"/\" + ipsetRulesFile, \"w\")\n\n# Write first row of file establishing maxelem\nipsetfile.write(\"%s\\n\" % (\"create \" + ipsetName + \" \" + ipsetType + \" family \" + ipsetFamily + \" hashsize \" + ipsetHashSize + \" maxelem \" + ipsetmaxelem))\n\n# Download the GeoLite2 Country Files\nurl = urlopen(geoipDBurl)\n\n# Read the zipfile\nzipfile = ZipFile(StringIO(url.read()))\n\n# Store the list of zipfile members to the namelist array\nnamelist = zipfile.namelist()\n\n# Step through each zipfile member that is part of the namelist value\nfor fileName in namelist:\n # Check to see if the file name ends with the TargetFile value.\n #print (\"INFO: Checking \" + fileName)\n \n if fileName.endswith(zipMember):\n #print (\"INFO: We found the file we are looking for: \" + zipMember)\n # Step through each line\n with zipfile.open(fileName) as geoList:\n for geoEntry in geoList:\n currentLine = geoEntry.split(\",\")\n countryGeoID = currentLine[1]\n if countryGeoID == usCountryID:\n networkAddress = currentLine[0]\n #print (\"Network Address: \" + networkAddress)\n ipsetfile.write(\"%s\\n\" % (\"add \" + ipsetName + \" \" + networkAddress))\n","sub_path":"getGeo.py","file_name":"getGeo.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"333452995","text":"import sys, pygame, math\n\n# Compute the area by triangle fan\ndef area(coords):\n area = 0\n for i in range(len(coords)-2):\n v1,v2,v3 = 0,i+1,i+2\n area += math.fabs(0.5 * (\n coords[v1].x*(coords[v2].y - coords[v3].y) +\n coords[v2].x*(coords[v3].y - coords[v1].y) +\n coords[v3].x*(coords[v1].y - coords[v2].y)\n ))\n if( area == 0.0):\n print(\"zero\")\n return 1.0\n\n return area\n\ndef squeeze(ref, mobile, proportion):\n mobile.x = ref.x + (mobile.x - ref.x) * proportion\n mobile.y = ref.y + (mobile.y - ref.y) * proportion\n\n# keep this puppy on screen\ndef boxin(pt):\n a = pt.x\n b = pt.y\n pt.x, pt.y = min(max(0.0,pt.x), 800.0), min(max(0.0,pt.y), 600.0)\n if( a != pt.x or b != pt.y):\n print(\"changed\")\n\ndef circumference(poly):\n circ = 0.0\n for i in range(1,len(poly)):\n circ += poly[i].distance_to(poly[i-1])\n return circ\n\n# one frame's total blob move\ndef moveblob(blob):\n for pt in blob:\n pt.y += 3 # Aristotelian gravity\n\n for iter in range(10):\n prop = math.sqrt(6000.0 / area(blob))\n \n squeeze(blob[-1], blob[0], prop)\n boxin(blob[0])\n for i in range(1,len(blob)):\n squeeze(blob[i-1], blob[i], prop)\n boxin(blob[i])\n\n\n\n\npygame.init()\n\nsize = width, height = 800, 600\nspeed = [2, 2]\nblack = 0, 0, 0\ngreen = 0, 255, 0\nred = 255, 0, 0\n\nscreen = pygame.display.set_mode(size)\n\nball = pygame.image.load(\"intro_ball.gif\")\nballrect = ball.get_rect()\npoints = [\n pygame.Vector2(50,50), \n pygame.Vector2(50, 100), \n pygame.Vector2(150, 75)]\nmorepoints = [\n pygame.Vector2(60,50), \n pygame.Vector2(60, 100), \n pygame.Vector2(110, 75)]\n\nprint(area(points))\n\nblob = []\nfor i in range(31):\n blob.append(\n pygame.Vector2(\n 400 + 100 * math.sin(math.pi * 2.0 * i / 31.0),\n 300 + 100 * math.cos(math.pi * 2.0 * i / 31.0)\n ) )\n\n\n\nwhile 1:\n pygame.time.wait(30)\n for event in pygame.event.get():\n if event.type == pygame.QUIT: sys.exit()\n\n ballrect = ballrect.move(speed)\n if ballrect.left < 0 or ballrect.right > width:\n speed[0] = -speed[0]\n if ballrect.top < 0 or ballrect.bottom > height:\n speed[1] = -speed[1]\n moveblob(blob)\n\n screen.fill(black)\n pygame.draw.polygon(screen, green, points)\n pygame.draw.polygon(screen, red, blob)\n screen.blit(ball, ballrect)\n pygame.display.flip()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"63002986","text":"\n\nfrom xai.brain.wordbase.verbs._delegate import _DELEGATE\n\n#calss header\nclass _DELEGATED(_DELEGATE, ):\n\tdef __init__(self,): \n\t\t_DELEGATE.__init__(self)\n\t\tself.name = \"DELEGATED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"delegate\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_delegated.py","file_name":"_delegated.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"456281455","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/11/18 下午8:57\n# @Author : zhaoyu\n# @Site : \n# @File : test1.py\n# @Software: PyCharm\n\nimport sys, os\nfrom PIL import Image\nfrom functools import reduce\nimport numpy as np\nimport operator\nimport math\nimport xlrd\nfrom xlwt import *\nfrom common_requests import get_request\n\n\ndef compose(*func):\n return reduce(lambda f, g: lambda *a, **b: g(f(*a, **b)), func)\n\n\ndef comp1(a, b):\n c = a + b\n print(c)\n return c\n\n\ndef comp2(a):\n c = a * a\n print(c)\n return c\n\n\ndef comp3(a):\n c = a / (a + a)\n print(c)\n return c\n\n\ndef comp4(a):\n c = a * (a + a)\n print(c)\n return c\n\n\ndef comp5(a, b):\n c = a * a * b * b\n print(c)\n return c\n\n\ndef testcomp():\n temp = compose(comp1, comp2, comp3, comp4, comp5(1))(3, 4)\n a = temp\n print(a)\n\n\ndef test():\n \"\"\"\n a = os.system('./test1.sh')\n a = a >> 8\n print(a)\n \"\"\"\n h = 200\n w = 400\n num_anchors = 9\n num_classes = 20\n a = [(h // {0: 32, 1: 16}[l], w // {0: 32, 1: 16}[l], num_anchors // 2, num_classes + 5) for l in range(2)]\n test1(*a)\n test2(a)\n c = lambda a, b: b\n print(c)\n\n\ndef test1(*a):\n b = a\n print(b)\n\n\ndef test2(a):\n b = a\n print(b)\n\n\ndef DarknetConv2D_BN_Leaky(*args, **kwargs):\n print(args)\n print(kwargs)\n\n\ndef tiny_yolo_body(inputs, num_anchors, num_classes):\n a = DarknetConv2D_BN_Leaky(16, (3, 3))\n print(a)\n\n\ndef test_lstm1():\n length = 5\n seq = np.array([i / float(length) for i in range(length)])\n print(seq)\n\n\ndef fei(years, ratio, per_num):\n sum_num = 0\n for i in range(years):\n if i > 13:\n sum_num = sum_num * (1 + ratio)\n else:\n sum_num = (sum_num + per_num) * (1 + ratio)\n print(sum_num)\n\n\ndef comp():\n w1 = np.load('emb_weights.npy')\n w2 = np.load('emb_weights.npy.1')\n dif = w1 - w2\n print(dif)\n\n\ndef sales(count):\n ini = 6\n rate = 0.1\n all_sale = ini\n for i in range(count - 1):\n ini = ini * (1 + rate)\n # print('{} {}'.format(i, ini))\n all_sale += ini\n print('{} {}'.format(i + 1, all_sale))\n\n\ndef temp():\n feed = ['feed_id','notice_type','state','fantuan_id','typ','my_sort_time','notice_type','fantuan_id','state','typ','weight','fantuan_id','state','notice_type','my_sort_time','fantuan_id','uuid','state','typ','weight','hot_count','comment_count','praise_count','id','fantuan_id','uuid','state','typ','weight','id','hot_count','comment_count','praise_count','feed_id','uuid','notice_type','state','typ','source','id','data_key','data_key','typ','typ','data_key','state','fantuan_id','notice_type','typ','create_date','uuid','fantuan_id','id','state','fantuan_id','id','state','create_time','uuid','fantuan_id','fantuan_id','state','state','fantuan_id','id','state','fantuan_id','uuid','notice_type','id','state','fantuan_id','uuid','typ','notice_type','id','state','fantuan_id','uuid','typ','notice_type','feed_id','id','fantuan_id','state','notice_type','typ','id','source','link_key','typ','source','data_key']\n feed_bell = ['state','expire_time','feed_id','bell_type','fnatuan_id','topic_id','hot_search_id','update_time','feed_id','bell_type','state','expire_time','feed_id','state','expire_time','bell_type','bell_type','feed_id','fnatuan_id','topic_id','hot_search_id','update_time','id']\n feed_expand = ['feed_id','id','feed_id','feed_id','id']\n feed_rec = ['feed_id','state','update_time','id','feed_id','id','feed_id','state','feed_id','state','fantuan_id','uuid','create_time']\n\n dic_f = {}\n for f in feed:\n if f in dic_f.keys():\n dic_f[f] = dic_f[f] + 1\n else:\n dic_f[f] = 1\n sorted_list_a = sorted(dic_f.items(), key=operator.itemgetter(1))\n print('feed')\n print(sorted_list_a)\n\n dic_f = {}\n for f in feed_bell:\n if f in dic_f.keys():\n dic_f[f] = dic_f[f] + 1\n else:\n dic_f[f] = 1\n sorted_list_a = sorted(dic_f.items(), key=operator.itemgetter(1))\n print('feed_bell')\n print(sorted_list_a)\n\n dic_f = {}\n for f in feed_expand:\n if f in dic_f.keys():\n dic_f[f] = dic_f[f] + 1\n else:\n dic_f[f] = 1\n sorted_list_a = sorted(dic_f.items(), key=operator.itemgetter(1))\n print('feed_expand')\n print(sorted_list_a)\n\n dic_f = {}\n for f in feed_rec:\n if f in dic_f.keys():\n dic_f[f] = dic_f[f] + 1\n else:\n dic_f[f] = 1\n sorted_list_a = sorted(dic_f.items(), key=operator.itemgetter(1))\n print('feed_rec')\n print(sorted_list_a)\n\n s = 'abc'\n per = int(len(s)/2)\n print(per)\n s1 = 'abcd'\n per1 = int(len(s1)/2)\n print(per1)\n\n\n x = s[math.ceil(len(s)/2):]+s1[math.ceil(len(s1)/2):]+s[:math.ceil(len(s)/2)]+s1[:math.ceil(len(s1)/2)]\n print(x)\n\n\ndef fill_user_mobile():\n # ------------------读数据---------------------------------\n fileName = \"/Users/xiangzy/Desktop/py.xls\"\n bk = xlrd.open_workbook(fileName)\n shxrange = range(bk.nsheets)\n try:\n sh = bk.sheet_by_name(\"Sheet1\")\n except Exception as e:\n print('read exception {}'.format(e))\n nrows = sh.nrows # 获取行数\n book = Workbook(encoding='utf-8')\n sheet = book.add_sheet('Sheet1') # 创建一个sheet\n for i in range(1, nrows):\n row_data = sh.row_values(i)\n # 获取第i行第3列数据\n # sh.cell_value(i,3)\n # ---------写出文件到excel--------\n print(\"-----正在写入 \" + str(i) + \" 行\")\n try:\n uuid = sh.cell_value(i, 4)\n data = get_request('http://idp.hifuntv.com/in/GetUserInfoByUuid?invoker=itvsdk&sign=d3cafca88773700f411999fec9e159a9f38daf4f&data=%7B%22uuid%22%3A%22{}%22%2C%22return%22%3A%22relate_mobile%22%2C%22_support%22%3A%2210000000%22%2C%22uip%22%3A%22127.0.0.1%22%2C%22seqid%22%3A%2220b9bc2644476e5f2dff094bc7d8b3c5%22%2C%22is_sign%22%3A1%7D'.format(uuid))\n print('uuid:{} result:{}'.format(uuid, data))\n if data is not None:\n mobile = data.get('msg', {}).get('relate_mobile', '')\n if len(mobile) < 1:\n continue\n sheet.write(i, 38, label=mobile) # 向第1行第1列写入获取到的值\n except Exception as e:\n print('{} have exception {}'.format(i, e))\n book.save(\"/Users/xiangzy/Desktop/py-mobile.xls\")\n\n\n# test()\n# tiny_yolo_body(1, 3, 20)\n# testcomp()\n# test_lstm1()\n# fei(3, 0.02, 1000)\n# comp()\n# sales(40)\n# temp()\nfill_user_mobile()","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":6546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"548189634","text":"\"\"\"video_project URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.urls import include, path\r\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.contrib import admin\r\nfrom django.urls import path, re_path\r\nfrom django.conf import settings\r\nfrom django.conf.urls.static import static\r\nfrom app_main import views\r\n\r\nurlpatterns = [\r\n path('', views.index, name='index'),\r\n path('index2/', views.index2, name='index2'),\r\n path('rank/', views.rank, name='rank'),\r\n path('rank2/', views.rank2, name='rank2'),\r\n path('radom/', views.radom, name='radom'),\r\n path('upload/', views.upload, name='upload'),\r\n path('rank_update/', views.rank_update, name='rank_update'),\r\n path('del_update/', views.del_update, name='del_update'),\r\n path('favorite/', views.favorite, name='favorite'),\r\n path('admin/', admin.site.urls),\r\n]\r\n\r\nif settings.DEBUG:\r\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # noqa\r\n","sub_path":"video_project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"115340357","text":"class Address:\n def __init__(self, address):\n self.address = address\n\n def __repr__(self):\n return str(self.address)\n\n\nclass Contact:\n def __init__(self, name, addresses=[]):\n self.name = name\n self.addresses = addresses\n\n\njose = Contact(name='Jose Jimenez')\njsc = Address('2101 E NASA Pkwy, Houston, TX')\njose.addresses.append(jsc)\nprint(jose.addresses)\n# [2101 E NASA Pkwy, Houston, TX]\n\nivan = Contact(name='Ivan Ivanovich')\nprint(ivan.addresses)\n# [2101 E NASA Pkwy, Houston, TX]\n","sub_path":"object-oriented-programming/src/oop-init-shared-state.py","file_name":"oop-init-shared-state.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"85274808","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.\nCopyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.\nLicensed under the MIT License (the \"License\"); you may not use this file except in compliance with the License.\nYou may obtain a copy of the License at http://opensource.org/licenses/MIT\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on\nan \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\"\"\"\n\nfrom django.utils.deprecation import MiddlewareMixin\n\nfrom .http import force_response_ee_format, force_response_raw_format, should_use_raw_response\n\n\nclass MethodOverrideMiddleware(MiddlewareMixin):\n METHOD_OVERRIDE_HEADER = \"HTTP_X_HTTP_METHOD_OVERRIDE\"\n\n def process_request(self, request):\n \"\"\"因为 GET 方法 URL 长度有限制,可以使用 POST 实现 GET 效果\"\"\"\n if request.method == \"POST\" and self.METHOD_OVERRIDE_HEADER in request.META:\n request.method = request.META[self.METHOD_OVERRIDE_HEADER]\n\n\nclass DynamicResponseFormatMiddleware:\n \"\"\"根据动态修改返回值格式\n - 原生格式\n - 企业版包装格式\n \"\"\"\n\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n response = self.get_response(request)\n\n # exception handler 将添加标记, 避免重复处理\n if getattr(response, \"from_exception\", None):\n return response\n\n if should_use_raw_response(request, response):\n return force_response_raw_format(response)\n else:\n return force_response_ee_format(response)\n","sub_path":"src/api/bkuser_core/common/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"586154179","text":"import argparse\nimport os\nfrom time import sleep\n\nimport requests\n\nfrom .client import Client, HttpError\n\ndef get_auth_token():\n parser = argparse.ArgumentParser(description='Obtain an authentication token')\n add_auth_arguments(parser)\n _args, client = parse_args(parser)\n\n print(\"Authentication token: {}\".format(client.token))\n\ndef upload_video():\n parser = argparse.ArgumentParser(description='Upload a video file')\n parser.add_argument('--playlist', help='Playlist ID to which the video should be added')\n parser.add_argument('video', help='Path to video file')\n add_auth_arguments(parser)\n args, client = parse_args(parser)\n video_path = args.video\n\n # Create upload url\n data = {'playlist': args.playlist} if args.playlist else {}\n upload_url = client.post('videouploadurls/', data=data).json()\n\n # Upload the file\n video_id = upload_url['id']\n requests.post(\n client.endpoint(\"videos/{}/upload/\".format(video_id)),\n files={'file': open(video_path)},\n )\n\n # Monitor transcoding progress\n video = client.get('videos/' + video_id).json()\n title = video['title']\n video_id = video['id']\n print(u\"Video uploaded: id={} title='{}'\".format(video_id, title))\n message = None\n status = None\n while status is None or status in ['processing', 'pending']:\n sleep(1) # don't flood the server\n video = client.get('videos/' + video_id).json()\n status = video['processing']['status']\n new_message = \" {} {:.2f}%\".format(status, video['processing']['progress'])\n if message != new_message:\n message = new_message\n print(message)\n\n for video_format in video['formats']:\n print(\" {}: {}\".format(video_format['name'], video_format['url']))\n\n\ndef delete_videos():\n parser = argparse.ArgumentParser(description='Delete a video')\n add_auth_arguments(parser)\n parser.add_argument('video_ids', nargs='+', help='Video IDs')\n args, client = parse_args(parser)\n\n for video_id in args.video_ids:\n try:\n response = client.delete('videos/' + video_id)\n except HttpError as e:\n print(u\"Failed to delete video: id={} error={}\".format(video_id, e.message))\n else:\n print(u\"Video deleted: id={} status code={}\".format(video_id, response.status_code))\n\ndef search_playlists():\n parser = argparse.ArgumentParser(description='Search playlists that have a given name')\n add_auth_arguments(parser)\n parser.add_argument('name', help='Playlist name')\n args, client = parse_args(parser)\n\n response = client.get('playlists', params={'name': args.name})\n playlists = response.json()\n print(\"{} results found\".format(len(playlists)))\n for playlist in playlists:\n print(\" id={} name='{}'\".format(playlist['id'], playlist['name']))\n\ndef create_playlist():\n parser = argparse.ArgumentParser(description='Create a playlist')\n add_auth_arguments(parser)\n parser.add_argument('name', help='Playlist name')\n args, client = parse_args(parser)\n\n response = client.post('playlists/', data={'name': args.name})\n playlist = response.json()\n print(playlist)\n\ndef delete_playlists():\n parser = argparse.ArgumentParser(description='Create a playlist')\n add_auth_arguments(parser)\n parser.add_argument('playlist_ids', nargs='+', help='Playlist ID')\n args, client = parse_args(parser)\n\n for playlist_id in args.playlist_ids:\n client.delete('playlists/{}'.format(playlist_id))\n print(\"Deleted {}\".format(playlist_id))\n\ndef upload_subtitle():\n parser = argparse.ArgumentParser(description='Upload a subtitle file')\n add_auth_arguments(parser)\n parser.add_argument('video_id', help='Video ID')\n parser.add_argument('language', help='Language code. E.g: \"fr\"')\n parser.add_argument('path', help='Path to subtitle file')\n args, client = parse_args(parser)\n\n response = client.post(\n 'videos/{}/subtitles/'.format(args.video_id),\n data={'language': args.language},\n files={'file': open(args.path, 'rb')},\n )\n subtitle = response.json()\n print(subtitle)\n\ndef add_auth_arguments(parser):\n \"\"\"\n Add arguments for authenticating with the remote host.\n \"\"\"\n parser.add_argument('--host', default=os.environ.get('VIDEOFRONT_HOST', 'http://127.0.0.1:8000'),\n help='Videofront host. You may define the VIDEOFRONT_HOST environment variable instead.')\n parser.add_argument('-t', '--token',\n help='Authentication token. You may define the VIDEOFRONT_TOKEN environment variable instead.')\n parser.add_argument('-u', '--username', help='Authentication username')\n parser.add_argument('-p', '--password', help='Authentication password')\n\ndef parse_args(parser):\n \"\"\"\n Parse CLI arguments with authentication credentials.\n \"\"\"\n args = parser.parse_args()\n\n try:\n client = Client(args.host, token=args.token, username=args.username, password=args.password)\n except ValueError as e:\n raise argparse.ArgumentError(None, e.message)\n\n return args, client\n","sub_path":"videofront/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":5141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"263274818","text":"import tweepy\nimport os\nimport logging\n\nfrom flask import Flask, render_template\n\napp = Flask(__name__)\n\nfrom bots.config import create_api\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger()\n\n\ndef get_friends_not_followers(api):\n\n fnf = []\n logger.info(\"Retrieving my friends not followers (fnf)...\")\n followers = tweepy.Cursor(api.followers).items()\n followers_id = [follower.id for follower in followers]\n\n for friend in tweepy.Cursor(api.friends).items():\n if friend.id not in followers_id: \n fnf.append(friend)\n return fnf\n\n\n@app.route(\"/\")\ndef index():\n\n logger.info(\"Started logging ...\")\n api = create_api()\n fnf = get_friends_not_followers(api)\n\n return render_template(\"index.html\", fnf=fnf, len_fnf=len(fnf))\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"Stats-Bot.py","file_name":"Stats-Bot.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"590397118","text":"from pathlib import Path\n\nfrom aiohttp import web\nimport aiohttp_jinja2\nimport jinja2\nimport magic\n\n@aiohttp_jinja2.template('gallery.html.jinja2')\nasync def handle(request):\n path = request.match_info.get('path', '')\n is_root = path == ''\n my_path = (request.app['root'] / path).resolve()\n try:\n my_path.relative_to(request.app['root'])\n except ValueError as e:\n return web.Response(text='not allowed', status=403)\n gallery_name = my_path.name\n try:\n dir_items = my_path.iterdir()\n dir_items = [item for item in dir_items]\n dir_items.sort(key=lambda i: str(i).casefold())\n except FileNotFoundError as e:\n return web.Response(text='no such directory', status=404)\n dirs = []\n files = []\n if not is_root:\n dirs.append((my_path / '..').relative_to(request.app['root']))\n for item in dir_items:\n rel_item = item.relative_to(request.app['root'])\n if item.is_dir():\n dirs.append(rel_item)\n #else:\n # print(magic.from_file(str(item), mime=True))\n elif magic.from_file(str(item), mime=True) in request.app['imagetypes']:\n files.append({'file': rel_item, 'thumb': rel_item, 'type': 'Image'})\n elif magic.from_file(str(item), mime=True) in request.app['videotypes']:\n files.append({'file': rel_item, 'thumb': None, 'type': 'Video'})\n return {'dirs': dirs, 'files': files, 'gallery_name': gallery_name}\n\nasync def create_app(gallery_root=None):\n app = web.Application()\n app['root'] = Path(gallery_root).absolute() if gallery_root else Path().absolute()\n aiohttp_jinja2.setup(app, loader=jinja2.PackageLoader('spg', 'templates'))\n\n # https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types\n app['imagetypes'] = ['image/apng', 'image/bmp', 'image/gif', 'image/x-icon', 'image/jpeg', 'image/png', 'image/svg+xml', 'image/webp']\n\n app['videotypes'] = ['video/mp4']\n\n app.add_routes([\n web.static('/pics', app['root']),\n ])\n app.add_routes([web.get('/{path:.*}', handle)])\n return app","sub_path":"spg/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"74144885","text":"from telegram.ext import Updater, CommandHandler, MessageHandler, Filters\r\nimport pymysql\r\nimport apiai, json\r\n\r\nupdater = Updater(token='787296993:AAH3m0mVTrcLzMFu5wjaZrn5-LTTUoxrI7U') # Токен API к Telegram\r\ndispatcher = updater.dispatcher\r\ncnx = pymysql.connect(user='wkfencjQr7',\r\n password='RYEA7WmsRb',\r\n host='remotemysql.com',\r\n database='wkfencjQr7')\r\ncursor = cnx.cursor()\r\nquery = \"SELECT code_login FROM student\"\r\ncursor.execute(query)\r\nresult = cursor.fetchall()\r\n# Запис у список всіх користувачів\r\nfinal_result = [list(i) for i in result]\r\nfinal_user = []\r\nfor i in range(len(final_result)):\r\n final_user.append(final_result[i][0])\r\n\r\ndef startCommand(bot, update):\r\n bot.send_message(chat_id=update.message.chat_id,\r\n text='Hello, I`m \\n'\r\n 'Post bot\\n'\r\n 'Drop_of_care Org.\\n'\r\n 'If you dont know how to make\\n'\r\n ' a post you can use /help')\r\n bot.send_message(chat_id=update.message.chat_id, text='But if you dont need help,\\n'\r\n 'Make your profile more cool,\\n'\r\n 'Make a post, dont be like everyone else,\\n'\r\n ' be yourself')\r\n bot.send_message(chat_id=update.message.chat_id, text='Make a post:')\r\n\r\ndef textMessage(bot, update):\r\n login = str(update.message.text)\r\n res1_new = []\r\n res1 = login.split(\"}\")\r\n for val in res1:\r\n val = val.strip()\r\n res1_new.append(val)\r\n\r\n\r\n if res1_new[0] in final_user:\r\n cursor = cnx.cursor()\r\n query = \"SELECT email FROM student where code_login ='%s'\" % res1_new[0]\r\n\r\n cursor.execute(query)\r\n result2 = cursor.fetchall()\r\n s1 = str(result2)\r\n s2 = s1.replace(\"'\", \"\")\r\n s2 = s2.replace(\"(\", \"\")\r\n s2 = s2.replace(\")\", \"\")\r\n s2 = s2.replace(\",\", \"\")\r\n email = s2\r\n cursor = cnx.cursor()\r\n query = \"SELECT name FROM student where code_login ='%s'\" % res1_new[0]\r\n cursor.execute(query)\r\n result2 = cursor.fetchall()\r\n s1 = str(result2)\r\n s3 = s1.replace(\"'\", \"\")\r\n s3 = s3.replace(\"(\", \"\")\r\n s3 = s3.replace(\")\", \"\")\r\n s3 = s3.replace(\",\", \"\")\r\n name = s3\r\n title = res1_new[1]\r\n bot.send_message(chat_id=update.message.chat_id, text=' your post is added to profile ')\r\n text = res1_new[2]\r\n tags = res1_new[3]\r\n\r\n cursor = cnx.cursor()\r\n query = \"INSERT INTO post (id, email, name, title, tags, text) VALUES (NULL,'%s','%s','%s','%s','%s')\" % (\r\n email, name, title, tags, text)\r\n cursor.execute(query)\r\n bot.send_message(chat_id=update.message.chat_id, text='Dear '+name + ' your post is added to profile\\n '\r\n 'Do the same if you want to post smth again😊😊😊 ')\r\n\r\n\r\n else:\r\n bot.send_message(chat_id=update.message.chat_id,\r\n text = 'Invalid')\r\n\r\n#Обработка команд\r\n\r\ndef helpCommand(bot, update):\r\n bot.send_message(chat_id=update.message.chat_id,\r\n text='So, you need help\\n'\r\n 'in writing message \\n'\r\n 'to make a post\\n'\r\n 'This link will help \\n'\r\n 'you to solve this problem\\n'\r\n 'https://telegra.ph/Example-of-sorrectly-written-message-to-Drop-of-Care-bot-04-08')\r\n\r\n\r\n# Хендлеры\r\nstart_command_handler = CommandHandler('start', startCommand)\r\nhelp_command_handler = CommandHandler('help', helpCommand)\r\ntext_message_handler = MessageHandler(Filters.text, textMessage)\r\nWrite_message_handler = MessageHandler(Filters.text, textMessage)\r\n# Добавляем хендлеры в диспетчер\r\ndispatcher.add_handler(start_command_handler)\r\ndispatcher.add_handler(help_command_handler)\r\ndispatcher.add_handler(text_message_handler)\r\ndispatcher.add_handler(Write_message_handler)\r\n\r\n# Начинаем поиск обновлений\r\nupdater.start_polling(clean=True)\r\n# Останавливаем бота, если были нажаты Ctrl + C\r\nupdater.idle()\r\n","sub_path":"DOOOCcC.py","file_name":"DOOOCcC.py","file_ext":"py","file_size_in_byte":4454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"447121442","text":"#Jesse Bruce\n#cpts355 HW5\n#ScopedSimplePostScript\n#closer to working model\n#static scoping actually implemented\n\n# The operand stack\nopstack = []\n\ndef opPop():\n return opstack.pop()\ndef opPush(value):\n if type(value) is str:\n if value[0] is '(':\n opstack.append(value[1:-1])\n return\n opstack.append(value)\n\n# The dictionary stack\ndictstack = []\n\nstatic=1\nnumscopes=0\n\ndef dictPop():\n return dictstack.pop()\ndef dictPush(linkv, dictionary):\n dictstack.append((linkv, dictionary))\ndef define(name, value):\n (link, ddict)=dictPop()\n ddict[name]=value\n dictPush(link, ddict)\ndef getlink(name):\n #find the index of name for link value\n i=0\n dictstack.reverse()\n for (link, gdict) in dictstack:\n if name in gdict:\n dictstack.reverse()\n print(len(dictstack)-i-1)\n return len(dictstack)-i-1\n i=i+1\ndef lookup(name):\n global static\n if static:\n #check current scope\n for curlink in range (-1, len(dictstack)-1):\n (link, ldict) = dictstack[curlink]\n if name in ldict.keys():\n return ldict[name]\n else:\n if curlink == link:\n #inf loop breaker\n break\n else:\n #else access static link\n curlink = link\n else:\n #dynamic scope\n curlink =getlink(name)\n (link, ldict)=dictstack[curlink]\n return ldict[name]\n global numscopes\n numscopes+=1\n return numscopes\n\n# arithmetic operators-- add, sub, mul, div, mod, eq, lt\ndef add():\n var2 = opPop()\n var1 = opPop()\n opPush(var1+var2)\ndef sub():\n var2 = opPop()\n var1 = opPop()\n opPush(var1-var2)\ndef mul():\n var2 = opPop()\n var1 = opPop()\n opPush(var1*var2)\ndef div():\n var2 = opPop()\n var1 = opPop()\n opPush(var1/var2)\ndef mod():\n var2 = opPop()\n var1 = opPop()\n opPush(var1%var2)\ndef eq():\n var2 = opPop()\n var1 = opPop()\n if var1 == var2: return True\n else: return False\ndef lt():\n var2 = opPop()\n var1 = opPop()\n\n# string operators-- length, get, put, getinterval\ndef length():\n var1 = opPop()\n opPush(len(var1))\ndef get():\n index = opPop()\n string = opPop()\n opPush(ord(string[index]))\ndef put():\n char = opPop()\n index = opPop()\n key = opPop()\n if key in dictstack[-1].keys():\n dictstack[-1][key] = dictstack[-1][key][:index]+chr(char)+dictstack[-1][key][index+1:]\ndef getinterval():\n count = opPop()\n index = opPop()\n string = opPop()\n opPush(string[index:index+count])\n\n# stack manipulation and print operators-- dup, exch, pop, roll, copy, clear, stack, count, psDef, psFor\ndef dup():\n var1 = opPop()\n opPush(var1)\n opPush(var1)\ndef exch():\n top = opPop()\n sec = opPop()\n opPush(top)\n opPush(sec)\ndef pop():\n return opPop()\ndef roll():\n rollstack = []\n extrastack = []\n nvals = opPop()\n pos = opPop()\n for i in range(pos):\n rollstack.append(opPop())\n for i in range(pos-nvals):\n extrastack.append(opPop())\n for item in rollstack:\n opPush(item)\n for item in extrastack:\n opPush(item)\ndef copy():\n vals=[]\n nvals = opPop()\n for i in range(nvals):\n vals.append(opPop())\n for i in range(2):\n for val in vals:\n opPush(val)\ndef clear():\n del opstack[:]\ndef stack():\n print(\"==============\")\n for val in opstack[::-1]:\n print(val)\n print(\"==============\")\n if len(dictstack) == 1:\n (link, sdict)=dictstack[0]\n print(\"----\"+str(0)+\"----\"+str(link)+\"----\")\n for (key, val) in sdict.items():\n print(str(key)+\" \"+str(val))\n else:\n for i in range(len(dictstack)-1,-1,-1):\n (link, sdict)=dictstack[i]\n print(\"----\"+str(i)+\"----\"+str(link)+\"----\")\n for (key, val) in sdict.items():\n print(str(key)+\" \"+str(val))\n\n print(\"==============\")\ndef count():\n opPush(len(opstack))\ndef psDef():\n value = opPop()\n name = opPop()\n (link, ddict)=dictPop()\n ddict[name]=value\n dictPush(link, ddict)\ndef psFor():\n code = opPop()\n limit = opPop()\n incre = opPop()\n i = opPop()\n for x in range(i, limit ,incre):\n interpret(code)\n\n# string to code array functions\nimport re\ndef tokenize(s):\n return re.findall(\"/?[a-zA-Z][a-zA-Z0-9_]*|[(][a-zA-Z0-9_\\s!][a-zA-Z0-9_\\s!]*[)]|[-]?[0-9]+|[}{]+|%.*|[^ \\t\\n]\", s)\ndef groupMatching(it):\n res = []\n for c in it:\n if c==')':\n return res\n else:\n # note how we use a recursive call to group the inner\n # matching parenthesis string and append it as a whole\n # to the list we are constructing.\n res.append(groupMatching(it))\n return False\n# function to turn a string of properly nested parentheses\n# into a list of properly nested lists.\ndef group(s):\n if s[0]=='(':\n return groupMatching(iter(s[1:]))\n else: return False\ndef groupCode(lpart):\n if lpart[0] is '{':\n return codeMatching(lpart[1:])\ndef codeMatching(it):\n i = 0\n n = 0\n x = 0\n l=[]\n for i, token in enumerate(it):\n if i > 0 and token == '{':\n n=findMatchCurly(it[i:])\n l.append(codeMatching(it[i+1:n+i]))\n x = i + n + 1\n elif i is 0 or i >= x:\n try:\n l.append(int(token))\n except:\n l.append(token)\n print(\"L: \"+str(l))\n return l\ndef findMatchCurly(l):\n lcurl = 0\n for i, token in enumerate(l):\n if token is '{':\n lcurl+=1\n elif token is '}':\n lcurl-=1\n if lcurl is 0:\n return i\ndef parse(tokens):#returns a code array for interpet\n n = 0\n i=0\n x=0\n code = []\n for i, token in enumerate(tokens):\n if token == '{' and i > x:\n n = findMatchCurly(tokens[i:])\n print(n)\n code.append(groupCode(tokens[i:n+i]))\n x = i+n+1\n elif i == 0 or i >= x:\n try:\n code.append(int(token))\n except:\n code.append(token)\n return code\n\ncodeOptions = {0:'lookup', 1:'add', 2:'sub', 3:'mul', 4:'div', 5:'mod', 6:'len', 7:'get', 8:'put', 9:'getinterval', 10:'dup', 11:'exch', 12:'pop', 13:'roll', 14:'copy', 15:'clear', 16:'stack', 17:'count', 18:'dict', 19:'begin', 20:'end', 21:'def', 22:'for'}\nnonos=[\"'\",',','[',']']\ndef interpret(code): # code is a code array\n for i in range(0,len(code)):\n if code[i] in nonos:\n continue\n if code[i] in codeOptions.values():\n #if code is command, call it\n if code[i] == 'lookup':\n lookup()\n elif code[i] == 'add':\n add()\n elif code[i] == 'sub':\n sub()\n elif code[i] == 'mul':\n mul()\n elif code[i] == 'div':\n div()\n elif code[i] == 'mod':\n mod()\n elif code[i] == 'len':\n length()\n elif code[i] == 'get':\n get()\n elif code[i] == 'put':\n put()\n elif code[i] == 'getinterval':\n getinterval()\n elif code[i] == 'dup':\n dup()\n elif code[i] == 'exch':\n exch()\n elif code[i] == 'pop':\n pop()\n elif code[i] == 'roll':\n roll()\n elif code[i] == 'copy':\n copy()\n elif code[i] == 'clear':\n clear()\n elif code[i] == 'stack':\n stack()\n elif code[i] == 'count':\n count()\n elif code[i] == 'dict':\n psDict()\n elif code[i] == 'begin':\n begin()\n elif code[i] == 'end':\n end()\n elif code[i] == 'def':\n psDef()\n elif code[i] == 'for':\n psFor()\n else:\n #else either push to opstack or lookup\n if type(code[i]) is int:\n opPush(code[i])\n elif code[i][0] == '/':\n opPush(code[i][1::])\n elif code[i][0] == '[' or type(code[i]) is list:\n opPush(code[i])\n elif code[i] == \"None\":\n continue\n else:\n lup = lookup(code[i])\n link=99\n if static:\n link = getlink(code[i])\n dictPush(link, {})\n interpreter(str(lup))\n dictPop()\ndef interpreter(s): # s is a string\n interpret(parse(tokenize(s)))\ndef main():\n global static\n static =1\n dictPush(0, {})\n st=input(\"static or dynamic? \")\n if st[0] == \"s\":\n static=1\n else:\n static=0\n interpreter(\"\"\"/x 4 def\n /g { x stack } def\n /f { /x 7 def g } def\n f\"\"\")\n # interpreter(\"\"\"/m 50 def\n # /n 100 def\n # /egg1 {/m 25 def n} def\n # /chic\n # {/n 1 def\n # /egg2 {n (n in egg2) } def\n # m\n # n\n # egg1\n # egg2\n # stack} def\n # n\n # chic\"\"\")\n\n #\n # interpreter(\"\"\"/m 50 def\n # /n 100 def\n # /egg1 {/m 25 def n (n in egg1) } def\n # /chic\n # {/n 1 def\n # /egg2 {n (n in egg2) } def\n # m (m in chic) n (n in chic)\n # egg1\n # egg2\n # stack} def\n # n (n in main)\n # chic\"\"\")\n\n inp=input(\"SSPS: \")\n interpreter(inp)\n while(inp != \"exit\" and inp != \"quit\" and inp != \"terminate\"):\n inp=input(\"SSPS: \")\n interpreter(inp)\nmain()\n","sub_path":"HW5/HW5.py","file_name":"HW5.py","file_ext":"py","file_size_in_byte":9683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"584202105","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\nJR-100 FSK Loader\n\"\"\"\n\nimport wave\nimport numpy as np\nimport struct\nimport sys\nimport math\nimport re\n\n_verbosity = 0\n\n_config_file = 'fskloader.ini'\n_mark_frequency = 2400.0\n_space_frequency = 1200.0\n_fsk_thresholds = None\n_cp_threshold = 0.15\n_wave_param = {}\n\ndef _read_wave(path):\n \"\"\"\n waveファイルからサンプリングデータを読み込む。\n\n Parameters\n ----------\n path: str\n waveファイルへのパス名\n\n Returns\n -------\n data: numpy.ndarray\n 読み込んだサンプリングデータ\n \"\"\"\n global _fsk_thresholds\n\n if _verbosity >= 1:\n print('Reading WAV file: {}'.format(path))\n \n with wave.open(path) as f:\n param = f.getparams()\n _wave_param['nchannels'] = f.getnchannels()\n _wave_param['sample_width'] = f.getsampwidth()\n _wave_param['sampling_rate'] = f.getframerate()\n data = f.readframes(f.getnframes())\n\n # 不完全な音声ファイルの場合があるので余りを切り捨てる。\n r = len(data) % _wave_param['sample_width']\n data = data[:len(data)-r]\n\n # 各サンプルを-1.0から1.0に正規化する。\n if _wave_param['sample_width'] == 1:\n data = np.frombuffer(data, dtype = 'uint8')\n data = (data.astype('float') - 128) / 128\n elif _wave_param['sample_width'] == 2:\n data = np.frombuffer(data, dtype = 'int16')\n data = data.astype('float') / 32768\n else:\n raise NotImplementedError(\n \"Sample width = {} is not supported)\"\n .format(_wave_param['sample_width']))\n\n # ステレオの場合は左チャンネルを使う。\n if _wave_param['nchannels'] == 2:\n data = data[::2]\n elif _wave_param['nchannels'] != 1:\n raise NotImplementedError(\n \"The number of channels = {} is not supported)\".format(ch))\n\n if not _fsk_thresholds:\n _fsk_thresholds = _decide_thresholds(_wave_param['sampling_rate'],\n _mark_frequency,\n _space_frequency)\n\n if _verbosity >= 2:\n print(' nchannels = {}, sample_width = {}, frame_rate = {}, nframes = {}'\n .format(_wave_param['nchannels'],\n _wave_param['sample_width'],\n _wave_param['sampling_rate'],\n len(data)))\n print(' FSK thresholds = {}'.format(_fsk_thresholds))\n \n return data\n\ndef _comparator(x0, x1, th_h, th_l):\n \"\"\"\n ヒステリシス付きのコンパレータの動作を模擬する。\n\n Parameters\n ----------\n th_h: float\n 立ち上がりエッジのしきい値\n th_l: float\n 立ち下がりエッジのしきい値\n\n Returns\n -------\n value: float\n コンパレータの出力値\n \"\"\"\n if x0 < th_h and x1 >= th_h:\n return 1.0\n elif x0 > th_l and x1 <= th_l:\n return -1.0\n else:\n return x0\n\ndef _write_wave(name, x, rate):\n '''\n サンプリング データをファイルに出力する。\n\n Parameters\n ----------\n name: str\n ファイル名\n x: numpy.ndarray\n サンプリング データ\n rate:\n サンプリング周波数\n '''\n import scipy.io.wavfile as siw\n siw.write(name, rate, x)\n \ndef _shape_wave(x):\n \"\"\"\n サンプルデータを2値化する。\n\n Parameters\n ----------\n x: numpy.ndarray\n 正規化されたサンプリングデータ\n\n Returns\n -------\n x: numpy.ndarray\n 2値化されたサンプリングデータ\n \"\"\"\n global _cp_threshold\n \n if _verbosity >= 1:\n print('Shaping')\n \n # 直流成分を除去する。\n offset = np.mean(x)\n if _verbosity >= 1:\n print(' Elminating DC component: offset = {}'.format(offset))\n x = x - offset\n\n # 波形の絶対値の最大値が1になるよう増幅する。\n a = 1 / max(np.max(x), abs(np.min(x)))\n if _verbosity >= 1:\n print(' Amplifying: a = {}'.format(a))\n x = a * x\n\n # 先頭と末尾の無音部分を除去する。\n pos_head = np.where(abs(x) >= 0.5)\n if _verbosity >= 1:\n print(' Removing silient part: {} - {}'\n .format(pos_head[0][0] / _wave_param['sampling_rate'],\n pos_head[0][-1] / _wave_param['sampling_rate']))\n # x = x[pos_head[0][0]:pos_head[0][-1]+1]\n\n if _verbosity >= 4:\n _write_wave('shaped1.wav', x, _wave_param['sampling_rate'])\n\n # データを+1.0と-1.0に2値化する。\n if _verbosity >= 1:\n print(' Binarizing')\n x = np.append(-1, x) # 先頭にダミー初期値を追加\n for i in range(len(x)-1):\n x[i+1] = _comparator(x[i], x[i+1], _cp_threshold, -_cp_threshold)\n\n if _verbosity >= 4:\n _write_wave('shaped2.wav', x, _wave_param['sampling_rate'])\n\n return x[1:] # ダミーを削除して返す。\n\ndef _decide_thresholds(fs, f1, f0):\n \"\"\"\n FSKで0と1の判定のためのしきい値を決定する。\n\n Parameters\n ----------\n fs: float\n 音声データのサンプリング周波数\n f1: float\n FSKにおけるマーク(1)周波数\n f0: float\n FSKにおけるスペース(0)周波数\n \"\"\"\n pos_f0 = math.floor(fs / f0)\n pos_f1 = math.floor(fs / f1)\n pos_center = (pos_f0 + pos_f1) / 2\n distance = math.floor(pos_center - pos_f1)\n return ((int(math.floor(pos_f1 - distance)),\n int(math.floor(pos_f1 + distance))),\n (int(math.floor(pos_f1 + distance) + 1),\n int(math.floor(pos_f0 + distance))))\n\ndef set_fsk_thresholds(min_1, max_1, min_0, max_0):\n \"\"\"\n FSKで0と1の判定のためのしきい値を設定する。\n\n Parameters\n ----------\n min_1: int\n '1'と判定するための最小幅\n max_1:\n '1'と判定するための最大幅\n min_0: int\n '0'と判定するための最小幅\n max_0:\n '0'と判定するための最大幅\n \"\"\"\n global _fsk_thresholds\n _fsk_thresholds = ((min_1, max_1), (min_0, max_0))\n\ndef set_cp_threshold(value):\n \"\"\"\n コンパレータで立ち上がりと立ち下がりを判定す��ためのしきい値を設定する。\n\n Parameters\n ----------\n value: float\n しきい値\n \"\"\"\n global _cp_thresholds\n _cp_thresholds = value\n \ndef _detector(v):\n \"\"\"\n 波形のフェーズを検出する。\n\n Parameters\n ----------\n v: float\n 正規化されたサンプルデータ\n\n Returns\n -------\n phase: str\n フェーズ\n\n Notes\n -----\n フェーズは以下のいずれかである。\n * 0: 値'0'に対するフェーズ\n * 1: 値'1'に対するフェーズ\n * unknown: それ以外の未知のフェーズ\n \"\"\"\n if _fsk_thresholds[1][0] * 2 <= v <= _fsk_thresholds[1][1] * 2:\n return 0\n elif _fsk_thresholds[0][0] * 2 <= v <= _fsk_thresholds[0][1] * 2:\n return 1\n else:\n return -1\n\ndef _fsk_value(x, i):\n \"\"\"\n FSKで符号化された音声フェーズ列から1つの値を求める。\n\n Parameters\n ----------\n x: bytearray\n フェーズ列\n i: int\n オフセット\n\n Returns\n -------\n value: int\n 復号化された1つの値\n offset: int\n 次のオフセット \n\n Notes\n -----\n valueとoffsetはタプルで返す。\n \"\"\"\n try:\n if _detector(x[i]+x[i+1]) == 0:\n return (0, i + 2)\n elif (_detector(x[i]+x[i+1]) == 1\n and _detector(x[i+2]+x[i+3]) == 1):\n return (1, i + 4)\n else:\n return (255, i + 1)\n except IndexError:\n return (255, i + 1)\n\ndef _dump_histogram(d):\n '''\n ヒストグラムを出力する。\n\n Parameters\n ----------\n d: numpy.ndarray\n 立ち下がりエッジ間の距離のリスト\n '''\n hist, bins = np.histogram(\n abs(d),\n bins=np.arange(abs(d).min(), min(60, abs(d).max()+2), step=1))\n print(' --------------------')\n if _fsk_thresholds[0][0] < abs(d).min():\n print(' ---- start of H ----')\n for i, n in zip(bins, hist):\n if i == _fsk_thresholds[0][0]:\n print(' ---- start of H ----')\n elif i == _fsk_thresholds[1][0]:\n print(' ---- start of L ----')\n \n print(' {:3d}: {}'.format(i, n))\n \n if i == _fsk_thresholds[0][1]:\n print(' ---- end of H ----')\n elif i == _fsk_thresholds[1][1]:\n print(' ---- end of L ----')\n if _fsk_thresholds[1][1] > abs(d).max():\n print(' ---- end of L ----')\n print(' --------------------')\n \ndef _serialize(x):\n \"\"\"\n ビット列を取り出す。\n\n Parameters\n ----------\n x: numpy.ndarray\n 2値化されたサンプリングデータ\n\n Returns\n -------\n bits: bytearray\n ビット列\n \"\"\"\n if _verbosity >= 1:\n print('Serializing')\n\n # 立ち下がりエッジの位置を検出する。\n falling_edge_pos = []\n previous = x[0]\n for i in range(1, len(x)):\n if previous > 0 and x[i] < 0:\n falling_edge_pos.append(i)\n previous = x[i]\n\n # 立ち下がりエッジ間の距離を求める。\n f = np.array(falling_edge_pos)\n d = np.diff(f)\n\n # FSK値1相当のパルス幅が10個連続で現れたらセーブデータの開始とみなす。\n start_of_signal_found = False\n i = 0\n count = 0\n while i < len(d) and not start_of_signal_found:\n if _fsk_thresholds[0][0] <= d[i] <= _fsk_thresholds[0][1]:\n count += 1\n else:\n count = 0\n if count == 10:\n start_of_signal_found = True\n break\n i += 1\n if not start_of_signal_found:\n print(' signal head not found')\n else:\n if _verbosity >= 2:\n print(' signal starts from sample #{}'.format(i))\n\n # 最初のゼロを探す。\n # このゼロの位置を起点に、2個('0'の場合)または4個('1'の場合)の単位で\n # FSKの復号を行う。\n first_zero_found = False\n while i < len(d) and not first_zero_found:\n if _fsk_thresholds[1][0] <= d[i] <= _fsk_thresholds[1][1]:\n first_zero_found = True\n break\n i += 1\n if not first_zero_found:\n print(' first zero not found')\n else:\n if _verbosity >= 2:\n print(' first zero found at sample #{}'.format(i))\n\n if _verbosity >= 2:\n print(' Histogram of the interval betwen falling edges')\n _dump_histogram(d)\n \n bits = bytearray()\n while i < len(d):\n value, new_i = _fsk_value(d, i)\n if value == 0 or value == 1:\n bits.append(value)\n i = new_i\n\n if _verbosity >= 3:\n print(' Bit sequence length = {}'.format(len(bits)))\n print(' Bit sequence contents:')\n print('------------------------')\n for k in range(0, len(bits), 1000):\n print('{} - {}'.format(k, k + 1000 - 1))\n box = bits[k:k+1000]\n print('\\n'.join([''.join([str(box[i])\n if box[i] == 0 or box[i] == 1\n else '.'\n for i in range(len(box))][j:j+100])\n for j in range(0, len(box), 100)]))\n print('----------------------')\n\n return bits\n\ndef _bits_to_byte(b):\n '''\n リトルエンディアンのビット列を整数値に変換する。\n\n Parameters\n ----------\n b: bytearray\n ビット列\n\n Returns\n -------\n value: int\n ビット列に対するバイト値\n '''\n a = [e if e == 0 or e == 1 else 0 for e in b]\n return sum([a[i] * 2**i for i in range(len(a))])\n \ndef _get_byte(b, i):\n \"\"\"\n 音声データのフェーズ列からビット列を取り出す。\n\n Parameters\n ----------\n b: bytearray\n ビット列\n i: int\n オフセット\n\n Returns\n -------\n byte: int\n バイト値\n offset: int\n 次のオフセット\n skip: int\n スキップしたビット数\n\n Notes\n -----\n 返値はbyteとoffsetのタプルである。\n \"\"\"\n if i+10 < len(b):\n start = b[i]\n value = _bits_to_byte(b[i+1:i+9])\n stop1, stop2 = b[i+9], b[i+10]\n if (start, stop1, stop2) == (0, 1, 1):\n return (value, i+11, 0)\n else:\n if _verbosity >= 1:\n print(' invalid separator bits: {} at {}'.format(b[i:i+11], i))\n found = False\n current_i = i\n i += 1\n while not found and i+10 < len(b):\n if (b[i], b[i+9], b[i+10]) == (0, 1, 1):\n found = True\n break\n i += 1\n if found:\n value = _bits_to_byte(b[i+1:i+9])\n return (value, i+11, i - current_i)\n else:\n return (value, i+1, 0)\n else:\n return (255, i+1, 0)\n \ndef _decode(bits):\n \"\"\"\n ビット列を復号化する。\n\n Parameters\n ----------\n bits: bytearray\n FSKデータから得られたビット列\n\n Returns\n -------\n byte_sequence: bytearray\n ビット列から取り出したバイト列 \n \"\"\"\n if _verbosity >= 1:\n print('Decoding')\n\n bit_sequence = np.array(bits)\n header_index = -1\n\n # データ末尾のストップビットが欠落する場合があるため明示的に追加しておく。\n bit_sequence = np.append(bit_sequence, 1)\n\n header_index = -1\n count = 0\n pattern = np.array([0, 1, 1, 1, 1, 1, 1, 1, 1])\n for i in range(len(bit_sequence)):\n if np.all(bit_sequence[i:i+9] == pattern):\n header_index = i\n break\n\n if _verbosity >= 2:\n print(' header start from {}'.format(header_index))\n \n if header_index >= 0:\n count = 0\n i = header_index\n while i < len(bit_sequence) and np.all(bit_sequence[i:i+9] == pattern):\n count += 1\n i += 9\n\n if _verbosity >= 2:\n print(' pattern count = {}'.format(count))\n\n # 0b011111111(9bit)のパターンが10個以上出現したらJR-100が生成するCMTデータとみなす。\n if header_index < 0 or count < 10:\n if _verbosity >= 1:\n print(' JR-100 Header not found')\n return None\n else:\n if _verbosity >= 2:\n print(' JR-100 Header found')\n\n # 最初の0(最初のバイトのスタートビット)の位置を求める。\n i += np.where(bit_sequence[i:] == 0)[0][0]\n \n byte_sequence = bytearray()\n\n # ヘッダ分の読み取り\n if _verbosity >= 1:\n print(' Reading Header from {}'.format(i))\n for _ in range(33):\n v, i, skip = _get_byte(bit_sequence, i)\n if skip > 0:\n print(' skip {} bits, tentative value = 0x{:02x}'.format(skip, v))\n print(' ...{}'.format(byte_sequence[-30:]))\n byte_sequence.append(v)\n\n # プログラムデータ分の読み取り\n if _verbosity >= 1:\n print(' Reading Body from {}'.format(i))\n i = np.where(bit_sequence[i:] == 0)[0][0] + i\n length = (byte_sequence[18] << 8) + byte_sequence[19]\n for _ in range(length + 1):\n v, i, skip = _get_byte(bit_sequence, i)\n if skip > 0:\n print(' skip {} bits, tentative value = 0x{:02x}'.format(skip, v))\n print(' ...{}'.format(byte_sequence[-30:]))\n byte_sequence.append(v)\n\n # チェックサムの検査\n if _verbosity >= 1:\n print(' Checking checksum')\n if np.sum(byte_sequence[0:31]) % 256 != byte_sequence[32]:\n print('Check sum error (header)')\n else:\n if _verbosity >= 2:\n print(' Chedk sum (header) OK')\n\n if np.sum(byte_sequence[33:33+length]) % 256 != byte_sequence[33+length]:\n print('Check sum error (body)')\n else:\n if _verbosity >= 2:\n print(' Chedk sum (body) OK')\n\n return byte_sequence\n\ndef get_param(program):\n \"\"\"\n プログラムのパラメータを取り出す。\n\n Parameter\n ---------\n program: bytearray\n プログラムデータ\n\n Returns\n -------\n param: dict\n プログラムのパラメータ\n\n Notes\n -----\n 以下のパラメータを返す。\n * name: プログラム名\n * start_addr: プログラムの開始アドレス\n * flag: BASICプログラムの場合は0、マシン語の場合は77(0x4d)\n \"\"\"\n name, addr, len, flag = struct.unpack('>16sHHB11x', program[0:32])\n name = name.replace(b'\\00', b'')\n return {'name': name, 'start_addr': addr, 'length': len, 'flag': flag}\n\ndef get_body(program):\n \"\"\"\n プログラム本体を取り出す。\n\n Parameter\n ---------\n program: bytearray\n プログラムデータ\n\n Returns\n -------\n param: bytearray\n プログラム本体\n \"\"\"\n length = get_param(program)['length']\n return program[33:33+length]\n\ndef write_file(program, path):\n \"\"\"\n プログラムをPROG形式のファイルとして書き込む。\n\n Parameters\n ----------\n program: bytearray\n プログラムデータ\n path: str\n 出力するファイルのパス名\n \"\"\"\n param = get_param(program)\n name = param['name']\n addr = int(param['start_addr'])\n flag = 1 if param['flag'] == 0x4d else 0\n body = get_body(program)\n\n data = struct.pack('<4sII{}sIII{}s'.format(len(name), len(body)),\n b'PROG', # 'PROG' (4s)\n 0x0000_0001, # フォーマットバージョン (I)\n len(name), # プログラム名長 (I)\n name, # プログラム名 ({}s)\n addr, # 先頭アドレス (I)\n len(body), # プログラム長 (I)\n flag, # フラグ (I)\n body) # プログラム ({}s)\n\n with open(path, 'wb') as f:\n f.write(data)\n\ndef decode_file(infile):\n \"\"\"\n FSKで符号化されたJR-100プログラムの音声データを復号化する。\n\n Parameter\n ---------\n infile: str\n waveファイルへのパス名\n\n Returns\n -------\n program: bytearray\n 復号化されたプログラム\n \"\"\"\n return _decode(_serialize(_shape_wave(_read_wave(infile))))\n\ndef dump_basic(program):\n \"\"\"\n 読み込んだプログラムをBASICとしてダンプする。\n\n Parameter\n ---------\n program: bytes\n 復号化されたプログラム\n \"\"\"\n body = get_body(program)\n for m in re.finditer(\n b'(?P[^\\xdf][^\\xdf])(?P[^\\x00]*?)\\x00',\n body, flags=re.DOTALL):\n n = struct.unpack('>H', m.group('num'))[0]\n line = ''.join([r'\\x{:02x}'.format(x) if x >= 128 else chr(x)\n for x in m.group('line')])\n print('{} {}'.format(n, line))\n\ndef dump_binary(program):\n \"\"\"\n 読み込んだプログラムをバイナリデータとしてダンプする。\n\n Parameter\n ---------\n program: bytes\n 復号化されたプログラム\n \"\"\"\n param = get_param(program)\n body = get_body(program)\n \n if param['start_addr'] % 16 != 0:\n print('{:04x}: '.format(param['start_addr'] & 0xfff0), end='')\n print(' ' * ((param['start_addr'] & 0xf) * 3), end='')\n\n for offset in range(param['length']):\n addr = param['start_addr'] + offset\n if addr % 16 == 0:\n print('{:04x}: '.format(addr), end='')\n print('{:02x} '.format(body[offset]), end='')\n if addr % 16 == 15:\n print()\n print()\n\ndef dump_program(program):\n \"\"\"\n 読み込んだプログラムのフラグに応じてダンプする。\n\n Parameter\n ---------\n program: bytes\n 復号化されたプログラム\n \"\"\"\n if get_param(program)['flag'] == 0x4d:\n dump_binary(program)\n else:\n dump_basic(program)\n\ndef set_verbosity(level):\n global _verbosity\n _verbosity = level\n\ndef main():\n import argparse\n import os\n import traceback\n import configparser\n from collections import OrderedDict\n \n parser = argparse.ArgumentParser()\n parser.add_argument('input_file',\n help=\"specify an input wave file\")\n parser.add_argument('-o', '--output_file',\n help=\"write to a PROG format file\",\n metavar=\"file\")\n parser.add_argument('-s', '--config_section',\n help=\"configuration section\",\n metavar=\"name\")\n parser.add_argument('--overwrite',\n help=\"overwrite to the existing file\",\n action='store_true')\n parser.add_argument('--fsk_thresholds',\n help=\"specify threshold values for FSK detector\",\n metavar=('min_1', 'max_1', 'min_0', 'max_0'),\n nargs=4, type=int)\n parser.add_argument('--cp_threshold',\n help=\"specify a threshold value for comparator\",\n metavar=('value'),\n type=float)\n parser.add_argument('--dump_auto',\n help=\"Dump this program depending on the type of program\",\n action='store_true')\n parser.add_argument('--dump_basic',\n help=\"Dump this program as a BASIC text\",\n action='store_true')\n parser.add_argument('--dump_binary',\n help=\"Dump this program as a binary data\",\n action='store_true')\n parser.add_argument('-v', '--verbose',\n help=\"enable verbose output\",\n action=\"count\", default=0)\n \n args = parser.parse_args()\n if args.verbose:\n set_verbosity(args.verbose)\n\n config = configparser.ConfigParser()\n sec = OrderedDict()\n if os.path.exists(_config_file):\n config.read('fskloader.ini')\n sec.update(config.defaults())\n if config.has_section(args.config_section):\n sec.update(config[args.config_section])\n\n if args.fsk_thresholds:\n set_fsk_thresholds(\n args.fsk_thresholds[0],\n args.fsk_thresholds[1],\n args.fsk_thresholds[2],\n args.fsk_thresholds[3],\n )\n elif sec.get('fsk_thresholds'):\n s = sec.get('fsk_thresholds')\n set_fsk_thresholds(*[int(x) for x in s.split()])\n\n if args.cp_threshold:\n set_cp_threshold(args.cp_threshold)\n elif sec.get('cp_threshold'):\n set_cp_threshold(float(sec.get('cp_threshold')))\n\n _do_dump = (args.dump_auto\n or args.dump_basic\n or args.dump_binary)\n\n try:\n # プログラム読み込み前に上書きチェックを行う。\n if (args.output_file\n and os.path.isfile(args.output_file)\n and not args.overwrite):\n raise FileExistsError(\"File exists: {}\".format(args.output_file))\n program = decode_file(args.input_file)\n if not program:\n raise Exception(\"Invalid JR-100 FSK format\")\n if args.verbose >= 1:\n print('Decoding Successed: {}'.format(get_param(program)['name']))\n \n if args.output_file:\n write_file(program, args.output_file)\n \n if _do_dump:\n param = get_param(program)\n if args.dump_basic:\n dump_basic(program)\n elif args.dump_binary:\n dump_binary(program)\n else:\n dump_program(program)\n except Exception as e:\n if _verbosity >= 2:\n print(traceback.format_exc())\n else:\n print(e)\n\nif __name__ == '__main__':\n main()\n","sub_path":"jr100emulib/fskloader.py","file_name":"fskloader.py","file_ext":"py","file_size_in_byte":24132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"428192175","text":"import unittest\nfrom test.TestHelper import TestHelper\nfrom src.parser.web_shop.amazon.AmazonParser import AmazonParser\n\nhelper = TestHelper()\nhtml = helper.read_file('../../../../other_files/amazon_goods.html' )\nparser = AmazonParser(html)\n\nclass TestAmazonParser(unittest.TestCase):\n def test_get_start_page(self):\n all_links_with_word = parser.get_start_page(html, 'all')\n\n self.assertEquals(['http://site.com/1/', 'http://site.com/', 'http://site.com/'], all_links_with_word)\n self.assertNotEquals([], all_links_with_word)\n\n def test_get_goods(self):\n all_links_with_item = parser.get_goods(html, 'all')\n\n self.assertEquals(['http://site.com/1/', 'http://site.com/2/', 'http://site.com/3/'], all_links_with_item)\n self.assertNotEquals([], all_links_with_item)\n\n def test_get_users(self):\n all_links_with_users = parser.get_users(html, 'all')\n\n self.assertEquals(['http://site.com/1/', 'http://site.com/2/', 'http://site.com/3/'], all_links_with_users)\n self.assertNotEquals([], all_links_with_users)\n","sub_path":"test/parser/web_shop/amazon/TestAmazonParser.py","file_name":"TestAmazonParser.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"19125439","text":"import readFile\nimport random\n\ndef topPop(bag, pop, percent=100): #выбор наиболее приспособленных особей\n percent = percent % 100\n sort = {}\n oldpop = sorted(sort, key=sort.__getitem__)\n oldpop.reverse()\n top = int(len(oldpop)*percent/100)\n if top % 2 == 1:\n top -= 1\n h = []\n t = []\n for i in range(0, top):\n h.append(pop[oldpop[i]])\n for i in range(top, len(oldpop)):\n t.append(pop[oldpop[i]])\n return {\"h\" : h, \"t\" : t}\n\ndef fitness(): #приспособленность\n for i in range(0,len(oldpop)):\n val = 0\n vol=0\n w=0\n for j in range(0,len(oldpop[i][0])):\n if oldpop[i][0][j]==1:\n val+=things[j][2]\n w+=things[j][0]\n vol+=things[j][1]\n if w>readFile.weight or vol>readFile.volume:\n val=0\n break\n oldpop[i].append([val])\n\t\t\ndef mutation(): #мутация путем инвентирования всех битов 1 особи\n ind = random.randint(0, len(oldpop)-1)\t\t\t\t\n for x in range(0,len(oldpop[ind])-1):\n if oldpop[ind][x]==0 :\n oldpop[ind][x] = 1\n else:\n oldpop[ind][x] = 0\t\t\n\t\t\ndef selection(): #отбор особей для скрещивания\n sum=0\n par=oldpop.copy()\n for k in range(0,len(oldpop)):\n sum+=oldpop[k][1][0]\n while len(par)>0:\n i = 0\n random.seed()\n r = random.randint(0, round(sum))\n csum=0\n while csum readFile.weight or vol > readFile.volume:\n val = 0\n break\n return val\t\n\t\ndef cr(x, y):\n child=[]\n for i in range(0,len(x)):\n random.seed()\n ind = random.random()\n if (ind<0.5):\n child.append(x[i])\n else:\n child.append(y[i])\n ch=[]\n ch.append(child)\n ch.append([gF(child)])\n newpop.append(ch)\n\n\n\ndef newPop(): #формирование новой популяции\n global oldpop\n spop=sorted(oldpop+newpop,key=lambda x: x[1])\n spop=spop[::-1]\n oldpop=spop[0:200]\n\ndef start(x): #объединяем функции\n global oldpop\n oldpop = []\n global newpop\n newpop = []\n global things\n things = []\n startPop()\n fitness()\n for k in range(0,x):\n selection()\n newPop()\n return oldpop[0]\n\t\t\noldpop=[]\nnewpop=[]\npcount=200\nthings=[]\t\n\t\n\t\nreadFile.read()\nres=start(100)\nprint(res[1],res[0])\n","sub_path":"task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":5237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"146199739","text":"# -*- coding: utf-8 -*-\r\nimport os\r\nimport re\r\nimport datetime\r\nfrom app import app\r\nimport telegram\r\nfrom flask import request, Blueprint\r\nimport requests\r\nenv = os.getenv('SERVER_SOFTWARE')\r\nif env and env.startswith('Google App Engine/'):\r\n import requests_toolbelt.adapters.appengine\r\n requests_toolbelt.adapters.appengine.monkeypatch()\r\n\r\n\r\nLK_BOT = telegram.Bot(token=app.config['LK_BOT_TOKEN'])\r\n\r\n\r\nlk = Blueprint('lk', __name__)\r\n\r\n\r\n\r\n@lk.route('/hook', methods=['POST'])\r\ndef lk_webhook_handler():\r\n # retrieve the message in JSON and then transform it to Telegram object\r\n update = telegram.Update.de_json(request.get_json(force=True), LK_BOT)\r\n\r\n chat_id = update.message.chat.id\r\n\r\n # Telegram understands utf-8, so encode text for unicode compatibility\r\n text = update.message.text.encode('utf-8')\r\n\r\n LK_BOT.sendMessage(chat_id=chat_id,\r\n text=\"Привет, твой chat_id: '{}'\".format(chat_id))\r\n return 'ok'\r\n\r\n\r\n@lk.route('/set_webhook', methods=['GET', 'POST'])\r\ndef lk_set_webhook():\r\n s = LK_BOT.setWebhook('{}/lk/hook'.format(app.config['HOOK_SITE']))\r\n if s:\r\n return \"webhook setup ok\"\r\n else:\r\n return \"webhook setup failed\"\r\n\r\n","sub_path":"FlaskWebProject1/lk_bot.py","file_name":"lk_bot.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"34731989","text":"import numpy as np\nfrom collections import defaultdict\n\nclass Bayes:\n def __init__(self):\n self._feats_count = defaultdict(int)\n self._feats_total = defaultdict(int)\n\n self._goals_count = defaultdict(int)\n self._goals_total = 0\n self._goals = None\n\n self._category_count = 0\n\n def train(self, train_data, train_goals):\n if train_data.ndim != 2:\n raise ValueError(\"Expected data to be two-dimensional\")\n\n if train_goals.ndim != 1:\n raise ValueError(\"Expected goals to be one-dimensional\")\n\n if train_data.shape[0] != train_goals.shape[0]:\n raise ValueError(\"Data row and goal counts do not match\")\n\n if self._category_count == 0:\n self._category_count = train_data.shape[1]\n else:\n if self._category_count != train_data.shape[1]:\n raise ValueError(\"Number of categories in given data does not match existing number\")\n\n for data_row, goal in zip(train_data, train_goals):\n self._goals_count[goal] += 1\n\n for category, data in enumerate(data_row):\n self._feats_count[(data, category, goal)] += 1\n self._feats_total[(category, goal)] += 1\n\n self._goals_total += train_goals.shape[0]\n\n if self._goals is not None:\n self._goals = np.concatenate((self._goals, train_goals))\n else:\n self._goals = train_goals\n\n self._goals = np.unique(self._goals)\n \n def predict(self, samples):\n if self._category_count == 0:\n raise UnboundLocalError(\"No training data to estimate on\")\n\n if samples.ndim != 2:\n raise ValueError(\"Data should be two-dimensional\")\n\n if samples.shape[1] != self._category_count:\n raise ValueError(f\"Feature count in data should be {self._category_count}\")\n\n categories = [0] * (samples.shape[0])\n\n for sample_no, sample_row in enumerate(samples):\n probability_array = np.zeros(self._goals.shape[0])\n\n for index, goal in enumerate(self._goals):\n goal_prob = self._calc_goal_chance(goal)\n \n feats_prob = 1\n for category, sample_val in enumerate(sample_row):\n feats_prob *= self._calc_feat_chance(sample_val, category, goal)\n\n probability_array[index] = goal_prob * feats_prob\n\n max_chance_index = np.argmax(probability_array)\n categories[sample_no] = self._goals[max_chance_index]\n\n return categories\n\n\n\n def _calc_goal_chance(self, goal):\n return self._goals_count[goal] / self._goals_total\n\n def _calc_feat_chance(self, data, category, goal):\n return self._feats_count[(data, category, goal)] / self._feats_total[(category, goal)]\n","sub_path":"classifiers/bayes.py","file_name":"bayes.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"16343038","text":"'''\nGiven a List of words, return the words that can be \ntyped using letters of alphabet on only one row's of American keyboard like the image below.\n\n\nExample:\n\nInput: [\"Hello\", \"Alaska\", \"Dad\", \"Peace\"]\nOutput: [\"Alaska\", \"Dad\"]\n \n\nNote:\n\nYou may use one character in the keyboard more than once.\nYou may assume the input string will only contain letters of alphabet.\n'''\n\ndef find_word_rows(words):\n levels = ['qwertyuiopQWERTYUIOP',\n 'asdfghjklASDFGHJKL',\n 'zxcvbnmZXCVBNM']\n\n result = []\n for word in words:\n for level in levels:\n found = True\n for char in word:\n if char not in level:\n found = False\n break\n if found: \n result.append(word)\n break\n \n\n return result\n\ndef find_words_v2(words):\n line1, line2, line3 = set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')\n ret = []\n for word in words:\n w = set(word.lower())\n if w <= line1 or w <= line2 or w <= line3:\n ret.append(word)\n return ret","sub_path":"algorithms/hashtables/keyboard_row.py","file_name":"keyboard_row.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"90202011","text":"import requests\n\nSHARDS = ['ea', 'na', 'sg', 'eu', 'sa', 'cn']\nMODE_JA = {\n 'casual': 'カジュアル',\n 'ranked': 'ランク',\n 'casual_aral': '大乱闘',\n 'blitz_pvp_ranked': '電撃',\n 'blitz_rounds_pvp_casual': 'ガチンコ',\n 'private': 'プラベカジュ',\n 'private_party_draft_match': 'プラベドラフト',\n 'private_party_aral_match': 'プラベ大乱闘',\n 'private_party_blitz_match': 'プラベ電撃',\n 'private_party_blitz_rounds_match': 'プラベガチンコ',\n '5v5_pvp_casual': '5V5カジュ',\n}\n\n\nclass VainAPI:\n ''' vainglory api '''\n\n def __init__(self):\n with open('secrets/vain-api', 'r') as f:\n self.apikey = f.read().rstrip()\n\n def request(self, url, params):\n headers = {\n 'Authorization': self.apikey,\n 'X-TITLE-ID': 'semc-vainglory',\n 'Accept': 'application/vnd.api+json',\n # 'Accept-Encoding': 'gzip',\n }\n return requests.get(url, headers=headers, params=params).json()\n\n def single_player(self, reg, ign):\n url = f'https://api.dc01.gamelockerapp.com/shards/{reg}/players'\n params = {\n 'filter[playerNames]': [ign],\n }\n res = self.request(url, params)\n if res.get('errors', ''):\n wrapped = res\n else:\n _attributes = res['data'][0]['attributes']\n wrapped = {\n 'id': res['data'][0]['id'],\n 'time': _attributes['createdAt'],\n 'shrd': _attributes['shardId'],\n 'name': _attributes['name'],\n 'elo8': _attributes['stats']['elo_earned_season_8'],\n 'wstr': _attributes['stats']['winStreak'],\n 'lstr': _attributes['stats']['lossStreak'],\n 'wins': _attributes['stats']['wins'],\n 'tier': _attributes['stats']['skillTier'],\n 'rnkp': _attributes['stats']['rankPoints']['ranked'],\n 'blzp': _attributes['stats']['rankPoints']['blitz'],\n }\n return wrapped\n\n def matches(self, reg, ign):\n url = f'https://api.dc01.gamelockerapp.com/shards/{reg}/matches'\n params = {\n 'filter[playerNames]': [ign],\n 'sort': '-createdAt',\n }\n res = self.request(url, params)\n\n # ================\n # Reshape the data\n # ================\n\n if res.get('errors', ''):\n matches = res\n else:\n\n # matches is one time only\n _matches = {i['id']: [i['attributes']['duration'],\n i['attributes']['gameMode'],\n i['attributes']['patchVersion'],\n i['relationships']['rosters']['data']]\n for i in res['data']}\n _rosters = {i['id']: [i['attributes']['stats']['heroKills'],\n i['attributes']['stats']['side'],\n i['attributes']['stats']['turretKills'],\n i['attributes']['stats']['turretsRemaining'],\n i['relationships']['participants']['data']]\n for i in res['included'] if i['type'] == 'roster'}\n # participants is to be saved\n _participants = {i['id']: [i['attributes']['actor'],\n i['attributes']['shardId'],\n i['attributes']['stats']['kills'],\n i['attributes']['stats']['deaths'],\n i['attributes']['stats']['assists'],\n i['attributes']['stats']['gold'],\n i['attributes']['stats']['farm'],\n i['attributes']['stats']['items'],\n i['attributes']['stats']['skillTier'],\n i['attributes']['stats']['winner'],\n i['relationships']['player']['data']['id']]\n for i in res['included'] if i['type'] == 'participant'}\n participants = {k: {'actor': v[0],\n 'shard': v[1],\n 'kills': v[2],\n 'deaths': v[3],\n 'assists': v[4],\n # KDA\n 'kda': (v[2] + v[4]) / (v[3] + 1),\n 'gold': int(v[5]),\n 'farm': int(v[6]),\n 'items': v[7],\n 'tier': v[8],\n 'won': v[9],\n 'player_id': v[10]}\n for k, v in _participants.items()}\n rosters = {k: {'team_kill_score': v[0],\n 'side': v[1].replace('/', '-'),\n 'turret_kill': v[2],\n 'turret_remain': v[3],\n 'participants': [participants[data['id']] for data in v[4]]}\n for k, v in _rosters.items()}\n matches = [{'duration': v[0],\n 'mode': v[1],\n 'version': v[2],\n 'rosters': [rosters[r['id']] for r in v[3]],\n }\n for v in _matches.values()]\n # for m in matches:\n # m['participants'] = {k: v for k, v in participants.items()\n # if k in [i for r in m['rosters']\n # for i in r['participants']]}\n return matches\n\n def player_matches(self, reg, ign):\n url = f'https://api.dc01.gamelockerapp.com/shards/{reg}/matches'\n params = {\n 'filter[playerNames]': [ign],\n 'sort': '-createdAt',\n }\n res = self.request(url, params)\n\n # ================\n # Reshape the data\n # ================\n\n if res.get('errors', ''):\n result = res\n else:\n\n # matches is one time only\n _matches = {i['id']: [i['attributes']['duration'],\n i['attributes']['gameMode'],\n i['attributes']['patchVersion'],\n i['relationships']['rosters']['data']]\n for i in res['data']}\n _rosters = {i['id']: [i['attributes']['stats']['heroKills'],\n i['attributes']['stats']['side'],\n i['attributes']['stats']['turretKills'],\n i['attributes']['stats']['turretsRemaining'],\n i['relationships']['participants']['data']]\n for i in res['included'] if i['type'] == 'roster'}\n # participants is to be saved\n _participants = {i['id']: [i['attributes']['actor'],\n i['attributes']['shardId'],\n i['attributes']['stats']['kills'],\n i['attributes']['stats']['deaths'],\n i['attributes']['stats']['assists'],\n i['attributes']['stats']['gold'],\n i['attributes']['stats']['farm'],\n i['attributes']['stats']['items'],\n i['attributes']['stats']['skillTier'],\n i['attributes']['stats']['winner'],\n i['relationships']['player']['data']['id']]\n for i in res['included'] if i['type'] == 'participant'}\n players = {\n i['id']: {\n 'name': i['attributes']['name'],\n 'shard': i['attributes']['shardId'],\n 'guild': i['attributes']['stats']['guildTag'],\n 'elo': i['attributes']['stats']['rankPoints']['ranked'],\n 'tier': i['attributes']['stats']['skillTier'],\n 'wins': i['attributes']['stats']['wins'],\n }\n for i in res['included'] if i['type'] == 'player'}\n participants = {k: {'actor': v[0],\n 'shard': v[1],\n 'kills': v[2],\n 'deaths': v[3],\n 'assists': v[4],\n # KDA\n 'kda': (v[2] + v[4]) / (v[3] + 1),\n 'gold': int(v[5]),\n 'farm': int(v[6]),\n 'items': v[7][::-1][:6][::-1],\n 'tier': v[8],\n 'won': v[9],\n 'player_id': v[10]}\n for k, v in _participants.items()}\n rosters = {k: {'team_kill_score': v[0],\n 'side': v[1].replace('/', '-'),\n 'turret_kill': v[2],\n 'turret_remain': v[3],\n 'participants': [participants[data['id']] for data in v[4]]}\n for k, v in _rosters.items()}\n matches = [{'duration': v[0],\n 'mode': MODE_JA.get(v[1], v[1]),\n 'version': v[2],\n 'rosters': [rosters[r['id']] for r in v[3]],\n }\n for v in _matches.values()]\n result = {'matches': matches,\n 'players': players}\n return result\n\n def _request_without_region(self, ign, method):\n for r in SHARDS:\n res = method(r, ign)\n if res is not dict:\n break\n elif res.get('errors', ''):\n # もしエラーがあれば。\n continue\n else:\n break\n return res\n\n def single_player_without_region(self, ign):\n return self._request_without_region(ign, self.single_player)\n\n def matches_without_region(self, ign):\n return self._request_without_region(ign, self.matches)\n\n def player_matches_wo_region(self, ign):\n return self._request_without_region(ign, self.player_matches)\n\n\n# ================\n# Utilities\n# ================\ndef itemname_to_cssreadable(name):\n return name.replace(' ', '-').replace(\"'\", \"\").lower()\n\n\ndef particularplayer_from_singlematch(match, player_id):\n for r in match['rosters']:\n for p in r['participants']:\n if p['player_id'] == player_id:\n return p\n","sub_path":"mymetrics/vain_api.py","file_name":"vain_api.py","file_ext":"py","file_size_in_byte":11156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"246170489","text":"import logging\nimport os\nfrom multiprocessing.pool import ThreadPool\n\nimport cv2\n\nfrom lib.aug.dataset_augmenter import IDataAugmenter\nfrom lib.dataset.image import Image\nfrom lib.dataset.pascal_voc.pascal_voc_file import PascalVOCFile\nfrom lib.dataset.sample import Sample\nfrom lib.list_utils import flatten\nfrom lib.util import os_utils\n\nlogger = logging.getLogger()\n\n\nclass DataAugmenter(IDataAugmenter):\n def __init__(self, dataset, output_path, max_parallel_augs=50):\n self.__output_path = output_path\n os_utils.create_path(output_path)\n self.__dataset = dataset\n self.max_parallel_augs = max_parallel_augs\n\n def augment(self, samples, aug_strategy, aug_count=10):\n with ThreadPool(self.max_parallel_augs) as pool:\n return flatten(\n pool.starmap_async(\n self.sample_augment,\n [(aug_strategy, s, s_num, aug_count) for s_num, s in enumerate(samples, start=1) if\n s.bounding_boxes is not None and len(s.bounding_boxes) > 0]\n ).get()\n )\n\n def sample_augment(self, aug_strategy, sample, sample_num, aug_count):\n max_pool = self.max_parallel_augs if aug_count > self.max_parallel_augs else aug_count\n\n logger.info(f'>>> {sample_num} sample <<< - File: {sample.image.filename()}...')\n\n with ThreadPool(max_pool) as pool:\n return pool.starmap_async(\n self.sample_augment_time,\n [(aug_strategy, sample, index) for index in range(0, aug_count)]\n ).get()\n\n def sample_augment_time(self, aug_strategy, sample, index):\n input_image_path = f'{self.__dataset.path}/{sample.image.filename()}'\n\n if not os.path.exists(input_image_path):\n raise Exception(f'Not found {input_image_path} image path!')\n\n aug_image_path = self.destiny_path(sample.image, index)\n aug_xml_path = os.path.splitext(aug_image_path)[0] + '.xml'\n if os.path.exists(aug_image_path) and os.path.exists(aug_xml_path):\n logger.info(f'Already exist {os.path.basename(aug_image_path)} augmented sample...')\n return PascalVOCFile.load(aug_xml_path)\n\n original_raw_image = cv2.imread(input_image_path)\n\n aug_raw_image, aug_bboxes = aug_strategy.augment(\n original_raw_image,\n sample.bounding_boxes\n )\n\n aug_sample = self.__create_sample(sample.image, aug_raw_image, aug_bboxes, index)\n\n cv2.imwrite(aug_sample.image.path, aug_raw_image)\n PascalVOCFile.write(aug_sample)\n\n return aug_sample\n\n def __create_sample(self, img, aug_raw_image, aug_bboxes, index):\n image = Image(\n self.destiny_path(img, index),\n height=aug_raw_image.shape[0],\n width=aug_raw_image.shape[1],\n depth=img.depth\n )\n return Sample(image, aug_bboxes)\n\n def destiny_path(self, img, index):\n parts = img.filename().split('.')\n return f'{self.__output_path}/{parts[0]}{index}.{parts[1]}'\n","sub_path":"lib/aug/impl/data_augmenter.py","file_name":"data_augmenter.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"522591183","text":"import numpy as np\nimport math\nfrom helpers_conv import *\nfrom helpers_fc import *\nfrom helpers1 import solve_fc, solve_conv\n\ndef random_mini_batches(X, Y, mini_batch_size = 64, seed = 0):\n \"\"\"\n Creates a list of random minibatches from (X, Y)\n \n Arguments:\n X -- input data, of shape (input size, number of examples) (m, Hi, Wi, Ci)\n Y -- true \"label\" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples) (m, n_y)\n mini_batch_size - size of the mini-batches, integer\n seed -- this is only for the purpose of grading, so that you're \"random minibatches are the same as ours.\n \n Returns:\n mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)\n \"\"\"\n \n m = X.shape[0] # number of training examples\n mini_batches = []\n np.random.seed(seed)\n \n # Step 1: Shuffle (X, Y)\n permutation = list(np.random.permutation(m))\n shuffled_X = X[permutation,:,:,:]\n shuffled_Y = Y[permutation,:]\n\n # Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.\n num_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning\n for k in range(0, num_complete_minibatches):\n mini_batch_X = shuffled_X[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:,:,:]\n mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:]\n mini_batch = (mini_batch_X, mini_batch_Y)\n mini_batches.append(mini_batch)\n \n # Handling the end case (last mini-batch < mini_batch_size)\n if m % mini_batch_size != 0:\n mini_batch_X = shuffled_X[num_complete_minibatches * mini_batch_size : m,:,:,:]\n mini_batch_Y = shuffled_Y[num_complete_minibatches * mini_batch_size : m,:]\n mini_batch = (mini_batch_X, mini_batch_Y)\n mini_batches.append(mini_batch)\n \n return mini_batches\n\ndef cross_entropy_loss(AL, Y):\n \n \"\"\"\n Implement the cost function\n \n Arguments:\n a3 -- post-activation, output of forward propagation size of [num_of_atributes x num_of_examples ]\n Y -- \"true\" labels vector, same shape as a3\n \n Returns:\n cost - value of the cost function\n \"\"\"\n m = Y.shape[1]\n #mnozenje = np.multiply(Y, np.log(AL))\n #negsum = -np.sum(mnozenje)\n #final = negsum / m\n return 1./m * -1 * np.sum(Y * (AL + (-np.max(AL) - np.log(np.sum(np.exp(AL-np.max(AL)))))))\n\ndef predict(X, y, parameters, layers_dims_conv, channels, nc):\n \"\"\" \n X -- train/test data of shape (#examples x dim(image))\n y -- train/test data of shape (#examples x 1)\n parameters -- parameters of the trained model \n Returns:\n p -- predictions for the given dataset X of shape (#examples x 1) \n \"\"\" \n m = X.shape[0]\n hparameters1 = {\"pad\" : 2, \"stride\": 3}\n hparameters2 = {\"stride\" : 2, \"f\": 2}\n hparameters3 = {\"pad\" : 1, \"stride\": 3}\n hparameters4 = {\"stride\" : 2, \"f\": 2} \n \n parameters_conv = solve_conv(parameters, layers_dims_conv, channels, nc) \n # Forward propagation conv \n P2, cache_pool2, cache_pool1, cache_conv1, cache_conv2, c1, c2 = Convolutional_Forward(X, parameters_conv, hparameters1, hparameters2, hparameters3, hparameters4)\n \n # Forward propagation FC\n FC1 = P2.reshape(P2.shape[0], -1).T\n \n # Get parameters for FC network, parameters_fc\n parameters_fc = solve_fc(parameters, layers_dims_conv) \n # Forward propagation FC\n A3_fc, cache_fc = L_model_forward(FC1, parameters_fc)\n \n a, b = A3_fc.shape\n p = np.zeros((a, b)) \n # convert probas to 0/1 predictions\n tmp = np.argmax(A3_fc, axis=0)\n for i in range(0, b):\n p[tmp[i],i] = 1\n p = p.T\n print(\"Accuracy: \" + str(np.mean((p[:,:] == y[:,:])))) \n return p","sub_path":"jupyterNotebook_additionalFiles_pictures/helpers2.py","file_name":"helpers2.py","file_ext":"py","file_size_in_byte":3817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"421611432","text":"# Parentheses Trees (geez)\n# by Roy Gustafson\n\n# from https://www.reddit.com/r/dailyprogrammer/comments/5l42dx/20161230_challenge_297_hard_parentheses_trees/\n\n# data structure\nclass Tree(object):\n def __init__(self):\n self.parent = None\n self.left = None\n self.right = None\n self.data = None\n\ndef addLeft(self):\n self.left = newL = Tree()\n newL.parent = self\n return newL\ndef addRight(self):\n self.right = newR = Tree()\n newR.parent = self\n return newR\n\n# iterators\nopened = 0\nclosed = 0\n\nroot = Tree()\ncurr = addLeft(root)\n\n# input\ndata = input('Enter data: ')\nbuffer = ''\n\nfor c in data:\n if c == '(':\n print('found: (') # edge case, first level\n curr.data = buffer\n if curr.left == None:\n print('adding left')\n curr = addLeft(curr)\n else:\n print('left full. adding right')\n curr = addRight(curr)\n elif c == ')':\n print('found: )')\n curr.data = buffer\n curr = curr.parent\n else:\n print('found: char')\n buffer += c\n \n\n# output\nx = 0\n\ndef preorder( self, level ):\n if self != None:\n print( level * '\\t' + self.data )\n level += 1\n preorder( self.left, level )\n preorder( self.right, level )\n level -= 1\n\npreorder( root, x ) # not running\n","sub_path":"ParentheTrees.py","file_name":"ParentheTrees.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"133307519","text":"#import os\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello_world():\n import pdb; pdb.set_trace()\n i = 0\n i = i + 4\n visited = i\n return 'Hello World!'+str(visited)\n\nif __name__ == '__main__':\n #host = os.getenv('IP', '0.0.0.0')\n #port = int9os.getenv('PORT', 5000))\n app.debug = True\n app.run()","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"383752752","text":"from keras.models import load_model\nfrom src.data.types import ShapeType\nimport cv2\nimport numpy as np\n\n\nclass NetworkClassifier:\n \"\"\"\n Neural network classifier.\n \"\"\"\n\n prediction_threshold = 0.95\n\n def __init__(self, model_dir, flatten):\n \"\"\"\n Classifier constructor.\n\n :param model_dir: Neural network model directory.\n :type model_dir: str\n :param flatten: Specifies whether input image should be flattened (for a model that recognizes 1D vectors)\n or kept as a 2D image (for a model that recognizes 2D images).\n :type flatten: bool\n \"\"\"\n self.model = load_model(model_dir)\n self.flatten = flatten\n\n def classify(self, region, verbose=False):\n \"\"\"\n Performs classification on a single input image using a neural network.\n The input region image should be thresholded (only 1 bit per pixel allowed).\n The input region image should contain one black shape on a white background.\n\n :param region: The region being classified.\n :type region: src.data.types.Region\n :param verbose: Specifies whether the classified image should be shown in a separate window.\n :type verbose: bool\n :return: Type of shape classified on the input image.\n :rtype: ShapeType\n \"\"\"\n image = region.image\n if verbose:\n cv2.imshow(\"\", image * 255)\n\n # flatten the image\n if self.flatten:\n image = image.reshape(1, np.prod(image.shape))\n else:\n image = image.reshape(1, image.shape[0], image.shape[1], 1)\n\n # feed image into model\n prediction = self.model.predict(image)[0].tolist()\n\n # verify the prediction\n if max(prediction) > self.prediction_threshold:\n if prediction[0] == max(prediction):\n return ShapeType.CIRCLE\n if prediction[1] == max(prediction):\n return ShapeType.SQUARE\n if prediction[2] == max(prediction):\n return ShapeType.STAR\n if prediction[3] == max(prediction):\n return ShapeType.TRIANGLE\n else:\n return None\n","sub_path":"shapes/src/classifiers/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"229506076","text":"# -*- coding: utf-8 -*-\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\nimport matplotlib.pyplot as plt\nimport time\nimport cv2\nimport io\nimport numpy as np\n\nclass Camera:\n def __init__(self):\n self.camera = PiCamera()\n self.camera.resolution = (640, 480)\n self.camera.framerate = 32\n self.camera.vflip = True\n time.sleep(2)\n\n def getFrameArray(self):\n stream = io.BytesIO()\n self.camera.capture(stream, format=\"jpeg\", use_video_port=True)\n frameArray = np.array(stream.getvalue())\n #~ frameArray = np.fromstring(stream.getvalue(), dtype = np.uint8)\n return frameArray\n \n def getFrame(self):\n frameArray = self.getFrameArray()\n frame = cv2.imdecode(frameArray, 1)\n return frame\n \nif __name__ == \"__main__\":\n camera = Camera()\n frame = camera.getFrame()\n plt.imsave(\"frame.jpeg\", frame)\n\n","sub_path":"control/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"503929978","text":"from sys import stdin as I\n\ndef check_text(_str):\n # print(f\"_str : {_str}\")\n sl = len(_str)\n # print(f\"len(_str) : {len(_str)}\")\n\n if sl <= 1:\n return True\n\n if _str[0].lower() != _str[-1].lower():\n return False\n\n return check_text(_str[1:(sl - 1)])\n\nif __name__ == '__main__':\n I = open(\"./prac_3.txt\")\n text = I.readline()\n text.lower()\n # print(type(text))\n if check_text(text):\n print(f\"{text}는 회문 입니다.\")\n else:\n print(f\"{text}는 회문이 아닙니다.\")","sub_path":"20171483_한태규_Puzzlie10/prac_3.py","file_name":"prac_3.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"46487835","text":"import ListNode\n#主要是要考虑\ndef findKthToTail(listHead,k):\n # 为空时的情况,求倒数第k个的情况\n if listHead == None or k <= 0:\n return None\n head = listHead\n for i in range(0,k-1):\n # 当k大于链表长度的情况\n if head.next:\n head = head.next\n else:\n return None\n\n kthTail = listHead\n while head.next:\n head = head.next\n kthTail = kthTail.next\n\n return kthTail\n\n\n","sub_path":"code-offer/no22findKthToTail.py","file_name":"no22findKthToTail.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"540572582","text":"\"\"\"Count prime numbers in a range between 1 and a given number.\n\nCount prime numbers with an iterative algorithm optimized by storing found\nprimes in a dictionary.\n\nUsage\n-----\n\n $ python3 primes_memo.py num\n\nnum - an upper limit for a range to look for prime numbers in.\n\"\"\"\n\nfrom math import sqrt\nimport sys\n\n\nprimes = {} # a global dict to store prime numbers\n\n\ndef is_prime(num):\n \"\"\"Checks if the number is prime.\"\"\"\n if num == 1:\n return False\n\n if num == 2:\n return True\n\n if num % 2 == 0:\n return False\n\n limit = int(sqrt(num)) + 1\n for i in range(1, limit):\n try:\n if primes[i] > limit:\n break\n if num % primes[i] == 0:\n return False\n except KeyError:\n break\n return True\n\n\ndef get_primes_count(num):\n \"\"\"Iteratively counts prime numbers in a range between 1 and num.\"\"\"\n if num == 1:\n return 0\n\n count = 0\n primes[0] = 2\n\n for i in range(3, num + 1, 2):\n if is_prime(i):\n count += 1\n primes[count] = i\n return count + 1\n\n\ndef main():\n if len(sys.argv) > 1:\n num = int(sys.argv[1])\n else:\n sys.exit()\n\n output = get_primes_count(num)\n print(output)\n\n\nif __name__ == '__main__':\n main()\n\n # unit tests for is_prime\n # assert not is_prime(1)\n # assert is_prime(3)\n # assert not is_prime(8)\n\n # unit tests for get_primes_count\n # assert get_primes_count(1) == 0\n # assert get_primes_count(10) == 4\n # assert get_primes_count(100) == 25\n","sub_path":"number_theoretic_algorithms/primes/primes_memo.py","file_name":"primes_memo.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"63581843","text":"from twisted.conch.telnet import TelnetTransport, TelnetProtocol\nfrom twisted.internet import protocol, task, reactor, endpoints\nfrom twisted.internet.protocol import ServerFactory\nfrom twisted.application.internet import TCPServer\nfrom twisted.application.service import Application\n\nimport json\nimport sys\nimport configparser\nimport os\nimport argparse\n\nimport twisted.scripts.twistd as t\nfrom pytradfri import Gateway\nfrom pytradfri.api.libcoap_api import APIFactory\n\nversion = \"0.8.1\"\nverbose = False\ndryRun = False\n\nhostConfig = {}\n\nINIFILE = \"{0}/devices.ini\".format(os.path.dirname(os.path.realpath(__file__)))\ndeviceDefaults = {\"Dimmable\": True, \"HasWB\": True, \"HasRGB\": False}\n\ndeviceConfig = configparser.ConfigParser()\n\nif os.path.exists(INIFILE):\n deviceConfig.read(INIFILE)\n\ncurrentError = False\n\nCONFIGFILE = \"{0}/config.json\".format(os.path.dirname(os.path.realpath(__file__)))\n\nif os.path.isfile(CONFIGFILE):\n\n with open(CONFIGFILE) as json_data_file:\n hostConfig = json.load(json_data_file)\nelse:\n print (\"Fatal: No config.json found\")\n exit()\n\ndef error(f):\n global currentError\n print (f.getErrorMessage())\n currentError = True\n\ndef verbosePrint(txt):\n if verbose:\n print(txt)\n\ndef stringToBool(boolString):\n if boolString == \"True\":\n return True\n elif boolString == \"False\":\n return False\n else:\n return None\n\nclass CoapAdapter(TelnetProtocol):\n api = \"\"\n gateway = \"\"\n\n\n def __init__(self, factory):\n self.factory = factory\n\n def connectionMade(self):\n answer = {}\n print(\"Connected from \" + str(self.transport.getPeer()))\n self.factory.clients.append(self)\n\n answer[\"action\"] = \"clientConnect\"\n answer[\"status\"] = \"Ok\"\n answer[\"version\"] = version\n\n self.transport.write(json.dumps(answer).encode(encoding='utf_8'))\n\n def dataReceived(self, data):\n verbosePrint(\"Data received: \" + str(data))\n\n decoded = data.decode(\"utf-8\")\n decoded = '[' + decoded.replace('}{', '},{') + ']'\n \n commands = json.loads(decoded)\n\n for command in commands:\n if command['action']==\"initGateway\":\n # print(\"Setting config\")\n self.factory.initGateway(self, command)\n #self.factory.initGateway(self, command['gateway'], command['key'], command['observe'], command['pollinterval'], command['groups'])\n\n if command['action']==\"getLights\":\n self.factory.sendDeviceList(self)\n\n if command['action']==\"setLevel\":\n self.factory.setLevel(self, command[\"deviceID\"], command[\"level\"])\n\n if command['action']==\"setState\":\n self.factory.setState(self, command[\"deviceID\"], command[\"state\"])\n\n if command['action']==\"setHex\":\n self.factory.setHex(self, command[\"deviceID\"], command['hex'])\n\n # except:\n # print(\"Error: Failed to parse JSON\")\n # print(\"Unexpected error:\", sys.exc_info()[0])\n\n def connectionLost(self, reason):\n print(\"Disconnected\")\n self.factory.clients.remove(self)\n\nclass ikeaGroup():\n deviceID = None\n deviceName = None\n lastState = None\n lastLevel = None\n factory = None\n\n def __init__(self, factory, group):\n self.deviceID = group.id\n self.deviceName = group.name\n self.lastState = group.state\n self.lastLevel = group.dimmer\n self.factory = factory\n\n def hasChanged(self, group):\n # targetGroup = self.factory.api(self.factory.gateway.get_group(int(self.deviceID)))\n\n curState = group.state\n curLevel = group.dimmer\n\n if (curState == self.lastState) and (curLevel == self.lastLevel):\n return False\n else:\n self.lastState = curState\n self.lastLevel = curLevel\n return True\n \n def sendState(self, client):\n devices = []\n answer = {}\n \n devices.append({\"DeviceID\": self.deviceID, \"Name\": self.deviceName, \"State\": self.lastState, \"Level\": self.lastLevel})\n\n answer[\"action\"] = \"deviceUpdate\"\n answer[\"status\"] = \"Ok\"\n answer[\"result\"] = devices\n\n verbosePrint(answer)\n try:\n client.transport.write(json.dumps(answer).encode(encoding='utf_8'))\n except Exception as e:\n print(\"Error sending group state\")\n\nclass ikeaLight():\n\n whiteTemps = {\"cold\":\"f5faf6\", \"normal\":\"f1e0b5\", \"warm\":\"efd275\"}\n\n deviceID = None\n deviceName = None\n lastState = None\n lastLevel = None\n lastWB = None\n modelNumber = None\n\n device = None\n factory = None\n\n def __init__(self, factory, device):\n self.device = device\n self.deviceID = device.id\n self.deviceName = device.name\n self.modelNumber = device.device_info.model_number\n self.lastState = device.light_control.lights[0].state\n self.lastLevel = device.light_control.lights[0].dimmer\n self.lastWB = device.light_control.lights[0].hex_color\n self.factory = factory\n \n\n def hasChanged(self, device):\n curState = device.light_control.lights[0].state\n curLevel = device.light_control.lights[0].dimmer\n curWB = device.light_control.lights[0].hex_color\n\n if (curState == self.lastState) and (curLevel == self.lastLevel) and (curWB == self.lastWB):\n return False\n else:\n self.lastState = curState\n self.lastLevel = curLevel\n self.lastWB = curWB\n return True\n\n def sendState(self, client):\n devices = []\n answer = {}\n \n targetLevel = self.lastLevel\n if targetLevel == None:\n targetLevel = 0\n\n devices.append({\"DeviceID\": self.deviceID, \"Name\": self.deviceName, \"State\": self.lastState, \"Level\": targetLevel, \"Hex\": self.lastWB})\n\n answer[\"action\"] = \"deviceUpdate\"\n answer[\"status\"] = \"Ok\"\n answer[\"result\"] = devices\n\n verbosePrint(answer)\n try:\n client.transport.write(json.dumps(answer).encode(encoding='utf_8'))\n except Exception as e:\n print(\"Error sending light state\")\n\nclass ikeaSocket():\n deviceID = None\n deviceName = None\n lastState = None\n modelNumber = None\n\n device = None\n factory = None\n\n def __init__(self, factory, device):\n self.deviceID = device.id\n self.deviceName = device.name\n self.modelNumber = device.device_info.model_number\n self.lastState = device.socket_control.sockets[0].state\n self.device = device\n self.factory = factory\n\n def setState(self, client, state):\n answer = {}\n answer[\"action\"] = \"setState\"\n answer[\"status\"] = \"Ok\"\n\n self.lastState = state\n\n targetDevice = self.factory.api(self.factory.gateway.get_device(int(self.deviceID)))\n setStateCommand = targetDevice.socket_control.set_state(state)\n \n try:\n self.factory.api(setStateCommand)\n except Exception as e:\n verbosePrint(\"Failed to set state for socked with ID: {0}\".format(self.deviceID))\n answer[\"status\"]=\"Failed\"\n\n if client != None:\n client.transport.write(json.dumps(answer).encode(encoding='utf_8'))\n self.sendState(client)\n\n def sendState(self, client):\n devices = []\n answer = {}\n\n devices.append({\"DeviceID\": self.deviceID, \"Name\": self.deviceName, \"State\": self.lastState})\n\n answer[\"action\"] = \"deviceUpdate\"\n answer[\"status\"] = \"Ok\"\n answer[\"result\"] = devices\n\n verbosePrint(answer)\n\n if client != None:\n try:\n client.transport.write(json.dumps(answer).encode(encoding='utf_8'))\n except Exception as e:\n verbosePrint(\"Error sending socket state\")\n\n def hasChanged(self, device):\n # NOTE: Device is a pytradfri-device-object\n curState = device.socket_control.sockets[0].state\n\n if curState != self.lastState:\n self.lastState = curState\n return True\n else:\n return False\n\nclass AdaptorFactory(ServerFactory):\n\n ikeaLights = {}\n ikeaGroups = {}\n ikeaSockets = {}\n\n devices = None\n groups = None\n\n observe = False\n groups = False\n\n def __init__(self):\n self.clients = []\n self.gateway = None\n self.api = None\n self.devices = None\n self.lights = None\n self.groups = None\n\n self.lighStatus = {}\n self.lc = task.LoopingCall(self.announce)\n\n if dryRun:\n self.initGateway(None, None)\n self.sendDeviceList(None)\n self.setState(None, \"65548\", False)\n\n def logout(self):\n # print(\"Logout\")\n reactor.stop()\n\n def buildProtocol(self, addr):\n return CoapAdapter(self)\n\n def announce(self):\n try:\n self.devices = self.api(self.api(self.gateway.get_devices()))\n if self.groups:\n self.groups = self.api(self.api(self.gateway.get_groups()))\n\n for dev in self.devices:\n if dev.has_light_control:\n if self.ikeaLights[dev.id].hasChanged(dev):\n for client in self.clients:\n self.ikeaLights[dev.id].sendState(client)\n\n if dev.has_socket_control:\n if self.ikeaSockets[dev.id].hasChanged(dev):\n for client in self.clients:\n self.ikeaSockets[dev.id].sendState(client)\n\n if self.groups:\n for group in self.groups:\n if self.ikeaGroups[group.id].hasChanged(group):\n for client in self.clients:\n self.ikeaGroups[group.id].sendState(client)\n except Exception as e: \n print(\"Error in annouce: {0}:{1}\".format(e, e.message))\n\n #def initGateway(self, client, ip, key, observe, interval, groups):\n def initGateway(self, client, command):\n verbosePrint(\"Initializing gateway\")\n connectedToGW = False\n\n if command != None:\n if command['observe']==\"True\":\n self.observe = True\n else:\n self.observe = False\n\n if command['groups']==\"True\":\n self.groups = True\n else:\n self.groups = False\n\n #try:\n api_factory = APIFactory(hostConfig[\"Gateway\"], hostConfig['Identity'], hostConfig['Passkey'])\n \n self.api = api_factory.request\n self.gateway = Gateway()\n \n connectedToGW = True\n #except:\n # connectedToGW = False\n\n if connectedToGW:\n self.devices = self.api(self.api(self.gateway.get_devices()))\n #self.devices = self.api(self.api(self.gateway.get_devices()))\n if self.groups:\n self.groups = self.api(self.api(self.gateway.get_groups()))\n \n try:\n for dev in self.devices:\n if dev.has_light_control:\n verbosePrint(\"Adding light with ID: {0}\".format(dev.id))\n self.ikeaLights[dev.id] = ikeaLight(factory=self, device=dev)\n if dev.has_socket_control:\n verbosePrint(\"Adding socket with ID: {0}\".format(dev.id))\n self.ikeaSockets[dev.id] = ikeaSocket(factory=self, device=dev)\n except Exception as e:\n print(\"Unable to iterate devices\")\n\n if self.groups:\n try:\n for group in self.groups:\n self.ikeaGroups[group.id] = ikeaGroup(factory=self, group=group)\n except Exception as e:\n print(\"Unable to iterate groups\")\n\n if self.observe:\n if not self.lc.running:\n self.lc.start(int(command['pollinterval']))\n else:\n if self.lc.running:\n self.lc.stop()\n self.announce()\n\n if client != None:\n client.transport.write(json.dumps({\"action\":\"initGateway\", \"status\": \"Ok\"}).encode(encoding='utf_8'))\n else:\n if client != None:\n client.transport.write(json.dumps({\"action\":\"initGateway\", \"status\": \"Failed\", \"error\": \"Connection timed out\"}).encode(encoding='utf_8'))\n\n def sendDeviceList(self, client):\n devices = []\n answer = {}\n configChanged = False\n\n # Lights\n for key, aDevice in self.ikeaLights.items():\n # print (aDevice.modelNumber)\n if not aDevice.modelNumber in deviceConfig:\n verbosePrint(\"Device settings not found for {0}. Creating defaults!\".format(aDevice.modelNumber))\n deviceConfig[aDevice.modelNumber] = deviceDefaults\n configChanged = True\n\n \n devices.append({\"DeviceID\": aDevice.deviceID, \"Name\": aDevice.deviceName, \"Type\": \"Light\", \"Dimmable\": stringToBool(deviceConfig[aDevice.modelNumber]['dimmable']), \"HasWB\": stringToBool(deviceConfig[aDevice.modelNumber]['haswb']), \"HasRGB\": stringToBool(deviceConfig[aDevice.modelNumber]['hasrgb'])})\n\n # Outlets\n for key, aDevice in self.ikeaSockets.items():\n devices.append({\"DeviceID\": aDevice.deviceID, \"Name\": aDevice.deviceName, \"Type\": \"Outlet\"})\n\n if self.groups:\n for key, aGroup in self.ikeaGroups.items():\n #print (aGroup)\n devices.append({\"DeviceID\": aGroup.deviceID, \"Name\": \"Group - \"+aGroup.deviceName, \"Type\": \"Group\", \"Dimmable\": True, \"HasWB\": False})\n\n if configChanged:\n with open(INIFILE, \"w\") as configfile:\n deviceConfig.write(configfile)\n\n answer[\"action\"] = \"getLights\"\n answer[\"status\"] = \"Ok\"\n answer[\"result\"] = devices\n\n verbosePrint(json.dumps(answer))\n \n if client != None:\n client.transport.write(json.dumps(answer).encode(encoding='utf_8'))\n\n for aDev in self.ikeaLights:\n self.ikeaLights[aDev].sendState(client)\n\n for aSocket in self.ikeaSockets:\n self.ikeaSockets[aSocket].sendState(client)\n\n if self.groups:\n for aGroup in self.ikeaGroups:\n self.ikeaGroups[aGroup].sendState(client)\n\n def setLevel(self, client, deviceID, level):\n answer = {}\n answer[\"action\"] = \"setLevel\"\n answer[\"status\"] = \"Ok\"\n\n setLevelCommand = None\n targetDevice = None\n\n deviceID=int(deviceID)\n target = None\n\n if deviceID in self.ikeaLights.keys():\n targetDeviceCommand = self.gateway.get_device(deviceID)\n targetDevice = self.api(targetDeviceCommand)\n setLevelCommand = targetDevice.light_control.set_dimmer(level)\n target = self.ikeaLights[deviceID]\n # Set\n self.api(setLevelCommand)\n\n if self.groups:\n if deviceID in self.ikeaGroups.keys():\n # First set level\n targetDevice=self.api(self.gateway.get_group(int(deviceID)))\n setLevelCommand = targetDevice.set_dimmer(level)\n target = self.ikeaGroups[deviceID]\n self.api(setLevelCommand)\n\n # Then switch the group on\n \n setStateCommand = targetDevice.set_state(True)\n target = self.ikeaGroups[deviceID]\n self.api(setStateCommand)\n \n client.transport.write(json.dumps(answer).encode(encoding='utf_8'))\n \n self.announce()\n\n def setState(self, client, deviceID, state):\n answer = {}\n answer[\"action\"] = \"setState\"\n answer[\"status\"] = \"Ok\"\n\n setStateCommand = None\n target = None\n targetDevice = None\n deviceID = int(deviceID)\n\n if state == \"On\":\n state = True\n\n if state == \"Off\":\n state = False\n\n # Device is a light\n if deviceID in self.ikeaLights.keys():\n targetDevice = self.api(self.gateway.get_device(int(deviceID)))\n setStateCommand = targetDevice.light_control.set_state(state)\n target = self.ikeaLights[deviceID]\n\n # Device is as outled\n if deviceID in self.ikeaSockets.keys():\n self.ikeaSockets[deviceID].setState(client, state)\n return\n\n # Device is a group\n if self.groups:\n if deviceID in self.ikeaGroups.keys():\n targetDevice = self.api(self.gateway.get_group(int(deviceID)))\n setStateCommand = targetDevice.set_state(state)\n target = self.ikeaGroups[deviceID]\n\n try:\n self.api(setStateCommand)\n except Exception as e:\n print(\"Failed to set state\")\n answer[\"status\"]=\"Failed\"\n \n client.transport.write(json.dumps(answer).encode(encoding='utf_8'))\n\n self.announce()\n\n def setHex(self, client, deviceID, hex):\n answer = {}\n answer[\"action\"] = \"setHex\"\n answer[\"status\"] = \"Ok\"\n\n deviceID = int(deviceID)\n\n if deviceID in self.ikeaLights.keys():\n targetDevice = self.api(self.gateway.get_device(int(deviceID)))\n setStateCommand = targetDevice.light_control.set_hex_color(hex)\n\n self.api(setStateCommand)\n client.transport.write(json.dumps(answer).encode(encoding='utf_8'))\n\n self.announce()\n\n \nif __name__ == \"__main__\":\n print (\"IKEA-tradfri COAP-adaptor version {0} started (command line)!\".format(version))\n verbose = True\n \n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dryrun\", action=\"store_true\")\n\n args = parser.parse_args()\n\n if args.dryrun:\n dryRun = True\n \n endpoints.serverFromString(reactor, \"tcp:1234\").listen(AdaptorFactory()).addErrback(error)\n \n if not currentError:\n reactor.run()\n \nelse:\n factory = AdaptorFactory()\n service = TCPServer(1234, factory)\n application = Application(\"IKEA Tradfri Adaptor\")\n service.setServiceParent(application)\n","sub_path":"tradfri.tac","file_name":"tradfri.tac","file_ext":"tac","file_size_in_byte":18294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"285431426","text":"# FOR EACH HDA IN FOLDER PLACE THEM IN HOUDINI FOR QA of lib\n# THIS CREATES THE PYTHON CODE TO THEN BE PASTED INTO SHELL\nOBJ_start = '''OBJ_start = hou.node(\"/obj/ALL_HDA\")'''\nprint(OBJ_start)\nPYquotes = \"\"\"'\"\"\"\nHDA_path = \"H:/MODELS/HOUDINI/00_OTL_DIGITALASSET/Z/otls\"\n\nNODE_create_start = \"\"\" = OBJ_start.createNode('\"\"\"\nNODE_create_name = \"EXAMPLE\"\nNODE_create_mid = \"\"\"', \"\"\"\nNODE_create_end = ''')'''\n\n#NODE_param_start = '''.setParms({'sopoutput':'''\n#NODE_param_end = '''})'''\n\nimport os\n\ndirectory = HDA_path\nfor filename in os.listdir(directory):\n if filename.endswith(\".hda\") :\n filenameonly = filename.replace('.hda', '')\n\n NODE_create_name = filenameonly\n NODE_name = filenameonly\n #PARAM_name = NODE_EXPORT_start + PATH_name + NODE_EXPORT_end\n\n PYNODE_create_final = NODE_name + NODE_create_start + NODE_create_name + NODE_create_mid + PYquotes + NODE_name + PYquotes + NODE_create_end\n #PYNODE_param_final = NODE_name + PYNODE_param_start + PYquotes + PARAM_name + PYquotes + NODE_param_end\n print(PYNODE_create_final)\n print(\"time.sleep(1)\")","sub_path":"otls/00_ALL_HDA_PLACE.py","file_name":"00_ALL_HDA_PLACE.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"268680923","text":"import numpy as np\nfrom .distance import latlon2distance\nfrom .transform import uv2vrvt_rt, uv2vrvt_xy\nfrom .fourier import interp_xy_closure\nfrom . import pseudo_coord\n\n\n__all__ = [\n 'inertial_stability_xy',\n 'inertial_stability_rt'\n]\n\n\ndef inertial_stability_xy(u, v, f, lon, lat, clon, clat, radius=None, thetas=None, dxdy=None):\n \"\"\"\n Calculate (cyclinic) inertial stability at x-y (longtitude-latitude) coordinate.\n \n Inertial stability is defined as\n I^2 = (f + 2*Vt/r) * (f + 1/r * d(r*Vt)/dr)\n where `f` is coriolis parameter, `Vt` is tangential wind speed, `r` is radius.\n The returned variable is sqrt(I^2).\n \n Parameter:\n ---------\n u, v : array, shape = (nz, ny, nx)\n Zonal wind and meridional wind at x-y coordinate.\n f : scalar or array, shape = (ny, nx)\n Coriolis parameter\n lon, lat : array, shape = (ny, nx)\n Longtitude and latitude\n clon, clat : scalar\n TC center coordinate\n radius : 1d array, shape = (nradius,). Optional\n Radial coordinate (used to calculate the radial gradient)\n thetas : 1d array, shape = (ntheta,). Optional\n The angles (radians) of each sampled points on the circle.\n See `circular.interp_circle`\n Default is np.arange(*np.deg2rad([0, 360, 1])), the whole circle.\n dxdy: 2-elements tuple, (dx, dy). Optional\n Spatial resolution. \n Default is None, and it would automatically derive dx and dy besed on `lon`\n and `lat`.\n \n Return:\n ------\n I : array, shape = (nz, ny, nx)\n Inertial stability.\n \"\"\"\n if thetas is None:\n thetas = np.arange(*np.deg2rad([0, 360, 1]))\n \n if radius is None:\n if dxdy is None:\n dx = latlon2distance(lon[:,1:], lat[:,1:], lon[:,:-1], lat[:,:-1]).mean()\n dy = latlon2distance(lon[1:,:], lat[1:,:], lon[:-1,:], lat[:-1,:]).mean()\n dr = max(dx, dy)\n else:\n dr = max(dxdy)\n \n n = 5\n slc = (slice(n, -n), slice(n, -n))\n dist_x = latlon2distance(clon, lat[slc], lon[slc], lat[slc])\n dist_y = latlon2distance(lon[slc], clat, lon[slc], lat[slc])\n maxdist = min(dist_x.max(), dist_y.max())\n radius = np.arange(0, maxdist, dr)\n \n nz, ny, nx = u.shape\n nradius = radius.size\n ntheta = thetas.size\n\n # calculate vt at radius-theta coordinate, shape = (nz, nradius, ntheta)\n _, vt = uv2vrvt_rt(u, v, lon, lat, clon, clat, radius, thetas, dxdy)\n \n # radial gradient: central difference for interior points, and one-side difference for edge points\n drvt_dr = np.empty((nz, nradius, ntheta))\n rvt = radius[None,:,None] * vt\n drvt_dr[:,1:-1,:] = (rvt[:,2:,:] - rvt[:,:-2,:]) / (radius[2:] - radius[:-2])[None,:,None]\n drvt_dr[:,0,:] = (rvt[:,1,:] - rvt[:,0,:]) / (radius[1] - radius[0])\n drvt_dr[:,-1,:] = (rvt[:,-1,:] - rvt[:,-2,:]) / (radius[-1] - radius[-2])\n \n # interpolate to x-y coordinate\n res = np.empty((nz, ny, nx))\n X, Y = pseudo_coord.lonlat2xy(lon, lat, clon, clat) # (ny, nx)\n func = interp_xy_closure(radius, thetas, X, Y, center=(0, 0))\n for ilev in range(nz):\n res[ilev,:,:] = func(drvt_dr[ilev,:,:])\n drvt_dr = res\n \n # vt at x-y coordinate\n _, vt = uv2vrvt_xy(u, v, lon, lat, clon, clat) # (nz, ny, nx)\n \n # finally\n dist_lon = latlon2distance(clon, lat, lon, lat) # (ny, nx)\n dist_lat = latlon2distance(lon, clat, lon, lat)\n r = 1000 * np.sqrt(X**2 + Y**2) # km -> m\n r[np.isclose(r, 0)] = np.nan\n\n I2 = (f + 2*vt/r) * (f + drvt_dr/r)\n I = np.sqrt(np.abs(I2))\n return I\n\n\ndef inertial_stability_rt(vt, f, radius, thetas):\n \"\"\"\n Calculate (cyclinic) inertial stability at cylindrical (radius-theta) coordinate.\n \n Inertial stability is defined as\n I^2 = (f + 2*Vt/r) * (f + 1/r * d(r*Vt)/dr)\n where `f` is coriolis parameter, `Vt` is tangential wind speed, `r` is radius.\n \n Parameter:\n ---------\n vt : array, shape = (nz, nradius, ntheta)\n Tangential wind speed at cylindrical coordinate\n f : scalar or array, shape = (nradius, ntheta)\n Coriolis parameter\n radius : 1d array, shape = (nradius,)\n Radial coordinate of `vt` and `f`\n thetas : 1d array, shape = (ntheta,)\n Azimuth coordinate of `vt` and f`\n \n Return:\n ------\n I : array, shape = (nz, nradius, ntheta)\n Inertial stability\n \"\"\"\n nz, nradius, ntheta = vt.shape\n \n # radial gradient: central difference for interior points, and one-side difference for edge points\n drvt_dr = np.empty((nz, nradius, ntheta))\n rvt = radius[None,:,None] * vt\n drvt_dr[:,1:-1,:] = (rvt[:,2:,:] - rvt[:,:-2,:]) / (radius[2:] - radius[:-2])[None,:,None]\n drvt_dr[:,0,:] = (rvt[:,1,:] - rvt[:,0,:]) / (radius[1] - radius[0])\n drvt_dr[:,-1,:] = (rvt[:,-1,:] - rvt[:,-2,:]) / (radius[-1] - radius[-2])\n \n r = radius[None,:,None].astype(float)\n r[np.isclose(r, 0)] = np.nan\n I2 = (f + 2*vt/r) * (f + drvt_dr/r)\n I = np.sqrt(np.abs(I2))\n return I","sub_path":"hurricane_tools/specialvar.py","file_name":"specialvar.py","file_ext":"py","file_size_in_byte":5107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"517996033","text":"from flask import Flask,render_template,request\n#from flask import session\n#from datetime import timedelta\nimport sqlite3\nbank = Flask(__name__)\n#bank.secret_key = \"#oihriefjipejfie09802832hefhijfijjouhoi\"\n\"\"\"@bank.before_request\ndef before_request():\n session.permanent = True\n bank.permanent_session_lifetime=timedelta(minutes=1)\"\"\"\n'''db = sqlite3.connect('bank.db')\nc = db.cursor()\nc.execute('create table user(name varchar(150), email varchar(150) not null primary key, password varchar(150), cpassword varchar(150))')\nc.execute('create table contact(name varchar(150), email varchar(150) not null primary key, msg varchar(150))')\nc.execute('create table account(id integer primary key autoincrement, name varchar(150), dob date, adhar varchar(15), phone varchar(150), uname varchar(150), password varchar(150), amount double)')\ndb.commit() ''' \n@bank.route('/')\ndef index():\n return render_template('home.html')\n@bank.route('/login1/')\ndef login():\n return render_template('login1.html')\n@bank.route('/form/')\ndef signin():\n return render_template('form.html')\n@bank.route('/afterbanking/', methods=['GET','POST'])\ndef afterbanking():\n if request.method=='POST':\n email=request.form.get('email')\n pswd=request.form.get('pswd')\n \n\n try:\n db = sqlite3.connect('bank.db')\n except Exception as e:\n return f'{e}'\n else:\n c = db.cursor()\n c.execute('select * from user where email=\"{}\"'.format(email))\n data = c.fetchone()\n if data:\n if pswd==data[2]:\n #session['email']=email\n msg = email\n return render_template('banking.html',error=msg)\n else:\n msg='Password is wrong'\n return render_template('login1.html',error=msg)\n else:\n msg = 'Email does not exsist'\n return render_template('login1.html',error=msg)\n@bank.route('/contact/')\ndef contact():\n return render_template('contact.html')\n@bank.route('/withdrawl/')\ndef withdrawl():\n return render_template('withdrawl.html')\n@bank.route('/deposit/')\ndef deposit():\n return render_template('deposit.html')\n@bank.route('/enquiry/')\ndef enquiry():\n return render_template('enquiry.html')\n@bank.route('/account/')\ndef account():\n return render_template('account.html')\n@bank.route('/detail/')\ndef detail():\n return render_template('detail.html')\n@bank.route('/aftersign/',methods=['GET','POST'])\ndef aftersign():\n if request.method=='POST':\n name=request.form.get('name')\n email=request.form.get('email')\n pswd=request.form.get('pswd')\n cpswd=request.form.get('cpswd')\n #return ' {} {} {} {}'.format(name,email,pswd,cpswd)\n try:\n db = sqlite3.connect('bank.db')\n except Exception as e:\n return f'{e}'\n else:\n c=db.cursor()\n c.execute('select email from user where email=\"{}\"'.format(email))\n data=c.fetchone()\n if data:\n msg = 'This email is already exist'\n return render_template('form.html',error=msg)\n else:\n if pswd==cpswd:\n cmd=\"insert into user values('{}','{}','{}','{}')\".format(name,email,pswd,cpswd)\n c.execute(cmd)\n db.commit()\n msg='you can login'\n return render_template('login1.html',error=msg)\n else:\n msg = 'Please confirm your password'\n return render_template('form.html',error=msg)\n else:\n msg = 'Invalid method'\n return render_template('form.html',error=msg)\n@bank.route('/aftercontact/',methods=['GET','POST'])\ndef aftercontact():\n if request.method=='POST':\n name=request.form.get('name')\n email=request.form.get('email')\n msg=request.form.get('msg')\n \n try:\n db = sqlite3.connect('bank.db')\n except Exception as e:\n return f'{e}'\n else:\n c=db.cursor()\n c.execute('insert into contact values(\"{}\",\"{}\",\"{}\")'.format(name,email,msg))\n db.commit()\n msg = 'Your message has been sent'\n #session['name'] = name\n return render_template('see.html',error=msg,errors=name)\n@bank.route('/contact/')\ndef hey():\n return render_template('contact.html')\n\n@bank.route('/afteropen/',methods=['GET','POST'])\ndef afteropen():\n if request.method=='POST':\n name=request.form.get('name')\n dob=request.form.get('dob')\n adhar=request.form.get('adhar')\n phone=request.form.get('phone')\n uname=request.form.get('uname')\n password=request.form.get('password')\n #return ' {} {} {} {} {} {}'.format(name,dob,adhar,phone,uname,password)\n try:\n db = sqlite3.connect('bank.db')\n except Exception as e:\n return f'{e}'\n else:\n c = db.cursor()\n c.execute('insert into account(name,dob,adhar,phone,uname,password) values(\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\")'.format(name,dob,adhar,phone,uname,password))\n db.commit()\n msg = 'done'\n return render_template('account.html',error=msg)\n \n else:\n msg = 'Invalid method'\n return render_template('account.html',error=msg)\n@bank.route('/afterdeposit/',methods=['GET','POST'])\ndef afterdeposit():\n if request.method=='POST':\n acnumber = request.form.get('acnumber')\n uname = request.form.get('uname')\n amount=request.form.get('amount')\n try:\n db = sqlite3.connect('bank.db')\n except Exception as e:\n return f'{e}'\n else:\n c=db.cursor()\n c.execute('select * from account where uname=\"{}\"'.format(uname))\n data = c.fetchone()\n if data:\n c.execute('update account set amount=\"{}\" where id=\"{}\"'.format(amount,acnumber))\n db.commit()\n return 'done'\n else:\n return \"data not found\"\n else:\n msg='Invalid method'\n return render_template('deposit.html',error=msg)\n@bank.route('/afterenquiry/',methods=['GET','POST'])\ndef afterenquiry():\n if request.method=='POST':\n uname=request.form.get('uname')\n pswd=request.form.get('pswd')\n try:\n db = sqlite3.connect('bank.db')\n except Exception as e:\n return f'{e}'\n else:\n c=db.cursor()\n c.execute('select * from account where uname=\"{}\"'.format(uname))\n data = c.fetchone()\n return render_template('page.html',error=data)\n else:\n msg='Invalid method'\n return render_template('enquiry.html',error=msg)\n@bank.route('/afterdetail/',methods=['GET','POST'])\ndef afterdetail():\n if request.method=='POST':\n uname = request.form.get('uname')\n pswd = request.form.get('pswd')\n newadhar=request.form.get('newadhar')\n newphone=request.form.get('newphone')\n newuname=request.form.get('newuname')\n newpswd=request.form.get('newpswd')\n try:\n db = sqlite3.connect('bank.db')\n except Exception as e:\n return f'{e}'\n else:\n c=db.cursor()\n c.execute('select * from account where uname=\"{}\"'.format(uname))\n data = c.fetchone()\n if data:\n c.execute('update account set uname=\"{}\",phone=\"{}\",adhar=\"{}\",password=\"{}\" where uname=\"{}\"'.format(newuname,newphone,newadhar,newpswd,uname))\n db.commit()\n return 'done'\n else:\n return \"data not found\"\n else:\n msg='Invalid method'\n return render_template('detail.html',error=msg)\n@bank.route('/afterwithdraw/',methods=['GET','POST'])\ndef afterwithdraw():\n if request.method=='POST':\n username=request.form.get('username')\n pswd = request.form.get('pswd')\n amount = request.form.get('amount')\n try:\n db = sqlite3.connect('bank.db')\n except Exception as e:\n return f'{e}'\n else:\n c=db.cursor()\n c.execute('select * from account where uname = \"{}\"'.format(username))\n data = c.fetchone()\n if data:\n balance = data[7]\n balance = balance-float(amount)\n #return f'{balance}'\n c.execute('update account set amount = \"{}\" where uname=\"{}\"'.format(balance,username))\n db.commit()\n msg = 'done'\n return msg\n else:\n return f'data not found'\n else:\n msg = 'Invalid method'\n return render_template('withdrawl.html',error=msg)\nbank.run(host='localhost',port=80,debug=True)","sub_path":"flaskbank/bank.py","file_name":"bank.py","file_ext":"py","file_size_in_byte":8958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"94927508","text":"import torch\nimport torch.optim\nimport math\nfrom torch.optim.optimizer import Optimizer\nfrom fairseq.optim import LegacyFairseqOptimizer, register_optimizer\n\n@register_optimizer(\"acmo\")\nclass FairseqACMo(LegacyFairseqOptimizer):\n def __init__(self, args, params):\n super().__init__(args)\n self._optimizer = Acutum_Original(params, **self.optimizer_config)\n\n @staticmethod\n def add_args(parser):\n \"\"\"Add optimizer-specific arguments to the parser.\"\"\"\n # fmt: off\n parser.add_argument('--acmo-betas', default='(0.9, 0.999)', metavar='B',\n help='betas for ACMo optimizer')\n parser.add_argument('--acmo-eps', type=float, default=1e-8, metavar='D',\n help='epsilon for ACMo optimizer')\n parser.add_argument('--weight-decay', '--wd', default=0.0, type=float, metavar='WD',\n help='weight decay')\n # fmt: on\n\n @property\n def optimizer_config(self):\n \"\"\"\n Return a kwarg dictionary that will be used to override optimizer\n args stored in checkpoints. This allows us to load a checkpoint and\n resume training using a different set of optimizer args, e.g., with a\n different learning rate.\n \"\"\"\n return {\n \"lr\": self.args.lr[0],\n \"betas\": eval(self.args.acmo_betas),\n \"eps\": self.args.acmo_eps,\n \"weight_decay\": self.args.weight_decay,\n }\n\n\nclass Acutum_Original(Optimizer):\n\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,\n weight_decay=0):\n if not 0.0 <= lr:\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\n if not 0.0 <= eps:\n raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n defaults = dict(lr=lr, betas=betas, eps=eps,\n weight_decay=weight_decay)\n super(Acutum_Original, self).__init__(params, defaults)\n\n def __setstate__(self, state):\n super(Acutum_Original, self).__setstate__(state)\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n grad_host = None\n moment_host = None\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError('Autum does not support sparse gradients, please consider SparseAdam instead')\n state = self.state[p]\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n state['exp_avg'] = torch.zeros_like(p.data)\n exp_avg= state['exp_avg']\n\n if grad_host is None:\n grad_host = grad.view(-1)\n else:\n grad_host = torch.cat((grad_host, grad.view(-1)), dim=-1)\n\n \n if moment_host is None:\n moment_host = exp_avg.view(-1)\n else:\n moment_host = torch.cat((moment_host, exp_avg.view(-1)), dim=-1)\n \n grad_norm = torch.norm(grad_host)\n moment_norm = torch.norm(moment_host)\n\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError('Autum does not support sparse gradients, please consider SparseAdam instead')\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p.data)\n\n exp_avg= state['exp_avg']\n beta1, beta2 = group['betas']\n state['step'] += 1\n\n if group['weight_decay'] != 0:\n grad.add_(group['weight_decay'], p.data)\n\n # make gradient and momentum sharp\n # grad_norm = torch.norm(grad.reshape(-1, ))\n # moment_norm = torch.norm(exp_avg.reshape(-1, ))\n\n exp_avg.mul_(grad_norm.div(moment_norm.add(group['eps']))).add_(grad).mul_(0.9)\n step_size = group['lr']\n\n p.data.add_(exp_avg.mul(-step_size))\n\n return loss","sub_path":"pytorch_nmt/acmo/acmo.py","file_name":"acmo.py","file_ext":"py","file_size_in_byte":5014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"98717410","text":"import os, sys\n\n\nwith open('법정동코드 전체자료.txt', 'r') as read_file:\n lines = read_file.readlines()\n\n\n\nresult = dict()\nfor line in lines:\n words = line.split()\n result[words[0][0:5]] = 'true'\n\nwith open('output.txt', 'w') as w_file:\n for key in result.keys():\n w_file.write(key+'\\n')","sub_path":"tool/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"303357264","text":"#!/usr/bin/env python\n\nimport rospy as ros;\nfrom std_msgs.msg import Int8;\nfrom geometry_msgs.msg import Twist;\nimport time;\nimport sys;\n\nros.init_node('ZumoMoveForward', anonymous=True);\npub = ros.Publisher('/zumo/1/cmd_vel', Twist, queue_size=10);\n\ndef moveForward(msg):\n\tvelMsg = Twist();\n\tvelMsg.linear.x = 1;\n\tvelMsg.linear.y = 0;\n\tvelMsg.linear.z = 0;\n\tvelMsg.angular.x = 0;\n\tvelMsg.angular.y = 0;\n\tvelMsg.angular.z = 0;\n\tpub.publish(velMsg);\n\ttime.sleep(0.1);\n\nros.Subscriber('/zumo/prox_front_left', Int8, moveForward);\nros.spin();\n\t\n","sub_path":"src/sit310_lab6/scripts/ZumoMoveForward.py","file_name":"ZumoMoveForward.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"334740993","text":"from typing import List\n\n\nclass Solution:\n def countBits(self, num: int) -> List[int]:\n res = []\n for n in range(num + 1):\n res.append(self.countOnes(n))\n return res\n\n def countOnes(self, n):\n if n == 1:\n return 1\n ones = 0\n while n > 1:\n if n % 2 == 1:\n ones += 1\n n = n // 2\n ones = ones + 1 if n == 1 else ones\n return ones\n\n def countBitsV2(self, num: int) -> List[int]:\n res = [0] * (num + 1)\n offset = 1\n res[0] = 0\n for i in range(1, num + 1):\n if offset * 2 == i:\n offset *= 2\n res[i] = res[i - offset] + 1\n\n return res\n\n\ns = Solution()\ntests = [\n (2, [0, 1, 1]),\n (5, [0, 1, 1, 2, 1, 2]),\n (0, [0]),\n]\n\nfor i, (x, y) in enumerate(tests):\n out = s.countBits(x)\n assert y == out, 'Test {}: Expect: {}, got {}'.format(i, y, out)\n\nprint('Example cases passed!')\n","sub_path":"0300-0399/0338/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"255371711","text":"#!/usr/bin/env python\n#\n# Copyright 2007 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport os\nimport re\nimport random\nimport hashlib\nimport hmac\nimport string\nimport json\nimport logging\nimport time\n\n\nimport webapp2\nimport jinja2\n\nfrom google.appengine.ext import db\nfrom google.appengine.api import urlfetch\n\n\n# Commands to access the directory where the files html, js are.\n\ntemplate_dir = os.path.join(os.path.dirname(__file__))\njinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),\n autoescape = True)\n\n\ndef render_str(template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\nclass BaseHandler(webapp2.RequestHandler):\n def render(self, template, **kw):\n self.response.out.write(render_str(template, **kw))\n\n def write(self, *a, **kw):\n self.response.out.write(*a, **kw)\n\n def set_cookie(self, name, val):\n self.response.headers.add_header('Set-Cookie',\n '%s=%s; Path=/' % (name, val))\n\n\n#### Funciones \n\ndef data_payload(url, obj, offset, count):\n return str(str(url) + '/' + str(obj) + '?'+ 'offset='+ str(offset) + '&count=' + str(count))\n\ndef connexion_obj_data(url):\n\turl1 = data_payload(url, 'adi/data.json', 0, 16)\n\tres = urlfetch.fetch(url1)\n\tadi_list = json.loads(res.content) \n\treturn {x: adi_list[x] for x in range(0, 16)}\n\ndef metadata_request(url, offset, count):\n\turl = data_payload(url, 'adi/metadata.json', offset, count)\n\tres = urlfetch.fetch(url)\n\treturn json.loads(res.content)\n\ndef info_request(url):\n ip_OK = False\n obj = 'module/info.json'\n url = str(url + '/' + obj)\n res = urlfetch.fetch(url)\n if res:\n ip_OK = True\n return json.loads(res.content) # no olvidar anadir una verificacion !\n\n\n#### Update section \n\ndef data_payload_update(url, a, b):\n\treturn str(url + '?' + 'inst='+ a + '&value=' + b)\n\ndef request_update_mod(target, instance, value):\n if len(value) == 1:\n val = '0' + value + '000000'\n if len(value) == 2:\n val = value + '000000'\n if len(value) == 7:\n val = '0' + value\n if len(value) == 8:\n val = value\n url = data_payload_update(target + '/adi/update.json', instance, val)\n res = urlfetch.fetch(url)\n return json.loads(res.content)\n\n\n\n###### \n\n\nclass MainDisplay(BaseHandler):\n the_url = ''\n def get(self):\n self.the_url = self.request.get('url')\n k = info_request(self.the_url)\n self.render('index2.html', over_outcome = k, dirr = self.the_url )\n\n def post(self):\n inst = self.request.get('inst')\n val = self.request.get('val')\n result_error = request_update_mod(self.request.get('url'), inst, val) # send update request to device, get error\n k = info_request(self.request.get('url'))\n \n # display\n self.render('index2.html', \n up_outcome = result_error['result'], last_request = 'Instance:' + inst + \" \" + 'Value:' + val, \n dirr = self.request.get('url'), over_outcome = k)\n\n \n\nclass FirstDisplay(BaseHandler):\n URL = ''\n def get(self):\n self.render('index1.html')\n\n def post(self):\n IP = self.request.get('ip')\n port = self.request.get('port')\n self.URL = str('http://' + IP + ':' + port)\n self.set_cookie('connex_url', str(self.URL)) #create the cookie\n self.redirect('/update?url=' + self.URL)\n\n\n\nclass Result(BaseHandler):\n def get(self):\n cookieValue = self.request.cookies.get('connex_url')\n list_name = metadata_request(cookieValue, 0, 16)\n list_value = connexion_obj_data(cookieValue)\n k = {x: [list_name[x][\"instance\"], list_name[x][\"name\"], list_name[x][\"datatype\"],list_name[x][\"access\"], list_value[x]] for x in range (0, 16)}\n self.render('resultspage.html', ADI_dict = k)\n\n\n\n\n\napp = webapp2.WSGIApplication([\n ('/', FirstDisplay),\n ('/result', Result),\n ('/update', MainDisplay)], \n debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"275661566","text":"from sig import Yimg, width_img, heigth_img, nb_channels\nimport csv\nimport pickle\nimport re\nfrom datetime import timezone, datetime\nfrom dateutil.parser import parse\nfrom calendar import timegm\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nimport numpy as np\nimport pandas as pd\n\nfrom os import listdir\nfrom os.path import isfile, join\n\n\ndef loadData(filename):\n\n data_original = pd.read_csv(filename)\n\n openp = data_original.ix[:, 'Open'].tolist()\n highp = data_original.ix[:, 'High'].tolist()\n lowp = data_original.ix[:, 'Low'].tolist()\n closep = data_original.ix[:, 'Close'].tolist()\n volumep = data_original.ix[:, 'Volume'].tolist()\n dates = data_original.ix[:, 'Local time'].tolist()\n\n data = np.column_stack((openp, highp, lowp, closep, volumep))\n\n return np.transpose(data)\n\n\ndef stringSplitByNumbers(x):\n r = re.compile('(\\d+)')\n l = r.split(x)\n return [int(y) if y.isdigit() else y for y in l]\n\n\ndef load_data_from_imgs(dir ,y_file):\n files = [f for f in listdir(dir) if isfile(join(dir, f)) and '.pkl' not in f]\n if len(files) < 2:\n print('Run create_dataset.py first!')\n exit(1)\n files.sort(key=stringSplitByNumbers)\n X = np.empty((len(files), heigth_img, width_img, nb_channels))\n counter = 0\n\n with tqdm(total=len(files)) as pbar:\n for f in files:\n pbar.update(1)\n img = mpimg.imread(dir+f)\n img = 1.0*(img > 0)\n X[counter] = img[:, :, 0:3]\n counter+=1\n\n with open(Yimg, 'rb') as fid:\n Y = pickle.load(fid)\n\n return X, Y\n\n\ndef load_data_from_pkl(dir, y_file, x_file):\n with open(y_file, 'rb') as fid:\n Y = pickle.load(fid)\n with open(x_file, 'rb') as fid:\n X = pickle.load(fid)\n\n return X, Y\n","sub_path":"loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"2237335","text":"from flask import Flask, render_template, request\r\nfrom flask_wtf import FlaskForm\r\nfrom wtforms import TextField\r\nfrom wtforms.validators import InputRequired\r\nfrom alchemy import db\r\nfrom alchemy import Package\r\nimport time\r\napp = Flask(__name__)\r\napp.secret_key = 'random string'\r\n\r\nclass FieldForm(FlaskForm):#All the form in this class with FlaskForm as constructor\r\n fnms = TextField('fnms', validators=[InputRequired('Provide Sender Name')])\r\n fnmr = TextField('fnmr', validators=[InputRequired('Provide Receiver Name')])\r\n address = TextField('address', validators=[InputRequired('Address is Required')])\r\n city = TextField('city', validators=[InputRequired('City Required')])\r\n pc = TextField('pc', validators=[InputRequired('Postal code Required')])\r\nclass idForm(FlaskForm):\r\n id = TextField('id', validators=[InputRequired('Id Required')])\r\nclass RadioForm(FlaskForm):\r\n radioform = TextField('radioform', validators=[InputRequired('Field Is Required')])\r\n\r\n\r\n@app.route('/',methods = ['POST', 'GET'])\r\ndef home():\t\r\n\treturn render_template('Home.html')\r\n \r\n@app.route('/NewPackage',methods = ['POST', 'GET'])\r\ndef newpackage():\r\n\tform = FieldForm()#form variable \r\n\tmsg=None\r\n\r\n\tif request.method=='POST':\r\n\t\tif form.validate_on_submit():\r\n\t\t\tnew_package=Package(sender_name=request.form['fnms'],rec_name=request.form['fnmr'],city=request.form['city'],address=request.form['address'],tk=request.form['pc'],rdate=time.strftime('%d/%m/%Y'))\r\n\t\t\tdb.session.add(new_package)\r\n\t\t\tdb.session.commit()\r\n\t\t\tmsg='You successfully added a new entry'\r\n\treturn render_template('NewPackage.html',msg=msg, form=form)#define form\r\n\t\r\n@app.route('/PackageSend',methods = ['POST', 'GET'])\r\ndef packagesend():\r\n\tform = idForm()#form variable \r\n\tmsg=None\r\n\tif request.method=='POST':\r\n\t\tif form.validate_on_submit():\r\n\t\t\tupdate_this=Package.query.filter_by(id=request.form['id']).first()\r\n\t\t\tif update_this:\r\n\t\t\t\tif update_this.sdate==None:\r\n\t\t\t\t\tupdate_this.sdate=time.strftime('%d/%m/%Y')\r\n\t\t\t\t\tdb.session.commit()\r\n\t\t\t\t\tmsg='Sent Date added to entry'\r\n\t\t\t\telse:\r\n\t\t\t\t\tmsg='Package already sent'\r\n\t\t\telse:\r\n\t\t\t\tmsg='Entry does not exist'\r\n\treturn render_template('PackageSend.html',msg=msg, form=form)#define form\r\n\r\n@app.route('/Inventory',methods = ['POST', 'GET'])\r\ndef inventory():\r\n\tform = RadioForm()#form variable \r\n\tlist=None\r\n\tif request.method=='POST':\r\n\t\tif request.form[\"action\"]==\"Submit\":\r\n\t\t\tif request.form['radio']==\"0\":\r\n\t\t\t\tlist=Package.query.all()\r\n\t\t\telif request.form['radio']==\"1\":\r\n\t\t\t\tif form.validate_on_submit():\r\n\t\t\t\t\tlist=Package.query.filter_by(sender_name=request.form['radioform'])\r\n\t\t\telif request.form['radio']==\"2\":\r\n\t\t\t\tif form.validate_on_submit():\r\n\t\t\t\t\tlist=Package.query.filter_by(rec_name=request.form['radioform'])\r\n\t\t\telif request.form['radio']==\"3\":\r\n\t\t\t\tif form.validate_on_submit():\r\n\t\t\t\t\tlist=Package.query.filter_by(id=request.form['radioform'])\r\n\t\telse:\r\n\t\t\tfor f in request.form.getlist('row'):\r\n\t\t\t\tPackage.query.filter_by(id=f).delete()\r\n\t\t\t\tdb.session.commit()\r\n\t\t\t\tlist=Package.query.all()\r\n\treturn render_template('Inventory.html',list=list,form=form)#define form\t\r\n\r\n\t\r\nif __name__ == '__main__':\r\n app.run(debug = True)\r\n \r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"176375738","text":"import requests\nfrom datetime import datetime\n\nBASE_URL = 'http://localhost:8080/'\n\nMENU_OPTIONS = [\n 'NEW GAME',\n 'RANKING',\n 'EXIT'\n]\n\ndef get_list_of_the_best_players():\n return requests.get(url = BASE_URL + '/rank/sorted').json()\n\ndef save_game__to_database(login: str, points: int):\n payload = {'login': login,\n 'date': datetime.now(),\n 'points': points }\n\n return requests.post(url = BASE_URL + '/rank', data = payload)\n\ndef print_menu(current_position_index: int):\n options = MENU_OPTIONS[:]\n options[current_position_index] = MENU_OPTIONS[current_position_index] + ' <--'\n\n [print(x) for x in options]\n\n\n\nif __name__ == \"__main__\":\n print_menu(0)","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"487432448","text":"#!/usr/bin/env python\nimport random\nimport torch\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nimport models\nimport envs\n\n\ndef set_random_seeds(train_env, test_env, seed=0xc0ffee):\n \"\"\"\n Set random seeds for reproducibility.\n \"\"\"\n train_env.seed(seed)\n test_env.seed(seed)\n random.seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.manual_seed(seed)\n\ndef get_best_action(net, obs):\n \"\"\"\n Return best action for given observation according to the neural network.\n Best action has lower \"Q\" value since it estimates cumulative cost.\n \"\"\"\n obs_left = torch.cat([torch.FloatTensor(obs), torch.FloatTensor([0])], 0)\n obs_right = torch.cat([torch.FloatTensor(obs), torch.FloatTensor([1])], 0)\n q_left = net(obs_left)\n q_right = net(obs_right)\n action = 1 if q_left >= q_right else 0\n\n return action\n\ndef generate_rollout(env, net=None):\n \"\"\"\n Generate rollout using given neural network. If a network is not given,\n generate random rollout instead.\n \"\"\"\n rollout = []\n obs = env.reset()\n done = False\n while not done:\n action = get_best_action(net, obs) if net else env.action_space.sample()\n next_obs, cost, done, _ = env.step(action)\n rollout.append((obs, action, cost, next_obs, done))\n obs = next_obs\n\n return rollout\n\ndef train(net, optimizer, rollout, gamma=0.95):\n \"\"\"\n Train neural network with a given rollout.\n \"\"\"\n state_batch, action_batch, cost_batch, next_state_batch, done_batch = zip(*rollout)\n state_batch = torch.FloatTensor(state_batch)\n action_batch = torch.FloatTensor(action_batch)\n cost_batch = torch.FloatTensor(cost_batch)\n next_state_batch = torch.FloatTensor(next_state_batch)\n done_batch = torch.FloatTensor(done_batch)\n\n state_action_batch = torch.cat([state_batch, action_batch.unsqueeze(1)], 1)\n predicted_q_values = net(state_action_batch).squeeze()\n\n # Compute min_a Q(s', a)\n q_next_state_left_batch = net(torch.cat([next_state_batch, torch.zeros(len(rollout), 1)], 1)).squeeze()\n q_next_state_right_batch = net(torch.cat([next_state_batch, torch.ones(len(rollout), 1)], 1)).squeeze()\n q_next_state_batch = torch.min(q_next_state_left_batch, q_next_state_right_batch)\n\n with torch.no_grad():\n target_q_values = cost_batch + gamma * q_next_state_batch * (torch.FloatTensor(1) - done_batch)\n\n loss = F.mse_loss(predicted_q_values, target_q_values)\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\ndef hint_to_goal(net, optimizer, factor=100):\n \"\"\"\n Use hint-to-goal heuristic to clamp network output.\n \"\"\"\n for _ in range(factor):\n state_action_pair = torch.FloatTensor([[random.random() * 0.1 - 0.05,\n random.random() - 0.5,\n random.random() * 0.6 - 0.3,\n random.random() - 0.5,\n random.randint(0, 1)]])\n predicted_q_value = net(state_action_pair).squeeze()\n loss = F.mse_loss(predicted_q_value, torch.zeros(1))\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\ndef test(env, net, episodes=1000):\n steps = 0\n nb_success = 0\n for _ in range(episodes):\n obs = env.reset()\n done = False\n\n while not done:\n action = get_best_action(net, obs)\n obs, _, done, info = env.step(action)\n steps += 1\n\n nb_success += 1 if info['success'] else 0\n\n print('Average Number of Steps: ', float(steps) / episodes)\n print('Success rate: ', float(nb_success) / episodes)\n\ndef main():\n train_env = envs.make_cartpole(100)\n test_env = envs.make_cartpole(3000)\n set_random_seeds(train_env, test_env)\n\n net = models.Net()\n optimizer = optim.Rprop(net.parameters())\n # TODO Initialize weights randomly within [-0.5, 0.5]\n\n for epoch in range(500):\n rollout = generate_rollout(train_env, net)\n if epoch % 10 == 9:\n print('Epoch {:4d} | Steps: {:3d}'.format(epoch + 1, len(rollout)))\n train(net, optimizer, rollout)\n hint_to_goal(net, optimizer)\n # test(test_env, net)\n\n train_env.close()\n test_env.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"nfq.py","file_name":"nfq.py","file_ext":"py","file_size_in_byte":4362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"505407906","text":"import os\nimport cv2\nimport heapq\nimport operator\nfrom bitarray import bitarray\n\n\ndef read_file(file_name):\n file = open(file_name, 'r')\n return file.read()\n\n\ndef read_binary_file(file_name):\n content = ''\n with open(file_name, 'rb') as file:\n temp = list(file.read())\n content = ''.join([chr(x) for x in temp])\n return content\n\n\ndef analyze_content(content):\n dictionary = {}\n for char in content:\n cardinality = dictionary.get(char, 0)\n dictionary.update({char: cardinality + 1})\n\n return dictionary\n\n\ndef sort_dictionary_items(dictionary):\n return dict(sorted(dictionary.items(), key=operator.itemgetter(1), reverse=True))\n\n\ndef int2bits(i, fill=8):\n return bin(i)[2:].zfill(fill)\n\n\nclass BasicLZW:\n def __init__(self, content, characters):\n self.content = content\n self.characters_dictionary = characters\n\n def create(self):\n dictionary_with_codes = {}\n for index, key in enumerate(self.characters_dictionary.keys()):\n dictionary_with_codes.update({key: index + 1})\n\n return dictionary_with_codes\n\n @staticmethod\n def codes_to_bits(codes):\n dict_with_bits_codes = {}\n total_items = len(codes)\n fill = total_items.bit_length()\n for (char, code) in codes.items():\n bits = int2bits(code, fill=fill)\n dict_with_bits_codes.update({char: bits})\n\n return dict_with_bits_codes\n\n def encode(self, codes):\n code = []\n current_key = ''\n basic_key = ''\n last_element_num = len(codes)\n current_bit_length = last_element_num.bit_length()\n\n for letter in self.content:\n current_key += letter\n if current_key in codes:\n basic_key += letter\n else:\n code.append(codes.get(basic_key))\n last_element_num += 1\n\n # Bump bits array - max length used\n if last_element_num.bit_length() > current_bit_length:\n current_bit_length += 1\n for key, value in codes.items():\n codes.update({key: '0' + value})\n\n # Update dictionary\n codes.update({current_key: str(int2bits(last_element_num, fill=current_bit_length))})\n basic_key = letter\n current_key = letter\n\n code.append(codes.get(basic_key))\n return code\n\n @staticmethod\n def decode(codes, encoded_content):\n content = []\n last_key = ''\n index = 0\n last_element_num = len(codes)\n current_bit_length = last_element_num.bit_length()\n max_index = len(encoded_content)\n\n while True:\n bits_code = encoded_content[index:index + current_bit_length].to01()\n index += current_bit_length\n char = codes.get(bits_code)\n\n if char is not None:\n last_element_num += 1\n codes.update({int2bits(last_element_num, fill=current_bit_length): char})\n\n if last_key != '':\n last_key += char[0]\n codes.update({int2bits((last_element_num - 1), fill=current_bit_length): last_key})\n\n if last_element_num.bit_length() > current_bit_length:\n current_bit_length += 1\n temp = {}\n for key, value in codes.items():\n temp.update({'0' + key: value})\n codes = temp\n\n last_key = char\n content.append(char)\n\n if index >= max_index:\n break\n else:\n break\n\n return ''.join(content)\n\n\nclass LZWHuffman:\n def __init__(self, content, characters):\n self.content = content\n self.characters_dictionary = characters\n\n def create(self):\n dictionary_with_codes = {}\n for index, key in enumerate(self.characters_dictionary.keys()):\n dictionary_with_codes.update({key: index + 1})\n\n return dictionary_with_codes\n\n @staticmethod\n def append_counters(codes):\n for key, value in codes.items():\n codes.update({key: [value, 0]})\n return codes\n\n @staticmethod\n def codes_to_bits(codes):\n dict_with_bits_codes = {}\n total_items = len(codes)\n fill = total_items.bit_length()\n for (char, code) in codes.items():\n bits = int2bits(code, fill=fill)\n dict_with_bits_codes.update({char: bits})\n\n return dict_with_bits_codes\n\n def pre_encode(self, codes):\n current_key = ''\n basic_key = ''\n counter = 0\n last_element_num = len(codes)\n current_bit_length = last_element_num.bit_length()\n\n for letter in self.content:\n current_key += letter\n if current_key in codes:\n basic_key += letter\n else:\n [ind, card] = codes.get(basic_key)\n codes.update({basic_key: [ind, card + 1]})\n last_element_num += 1\n counter += 1\n\n # Bump bits array - max length used\n if last_element_num.bit_length() > current_bit_length:\n current_bit_length += 1\n for key, value in codes.items():\n [ind, card] = value\n codes.update({key: ['0' + ind, card]})\n\n # Update dictionary\n codes.update({current_key: [str(int2bits(last_element_num, fill=current_bit_length)), 0]})\n basic_key = letter\n current_key = letter\n\n [ind, card] = codes.get(basic_key)\n codes.update({basic_key: [ind, card+1]})\n counter += 1\n return codes, counter\n\n @staticmethod\n def remove_n_cardinality_items(codes, n=0):\n temp = {}\n for key, item in codes.items():\n [code, cardinality] = item\n if cardinality > n:\n temp.update({key: [code, cardinality]})\n return temp\n\n @staticmethod\n def make_nodes_heap(dictionary):\n heap = []\n for key, value in dictionary.items():\n [_bits, cardinality] = value\n node = Node(key, cardinality)\n heapq.heappush(heap, node)\n return heap\n\n @staticmethod\n def merge_nodes(heap):\n while len(heap) > 1:\n node1 = heapq.heappop(heap)\n node2 = heapq.heappop(heap)\n\n merged = Node(None, node1.freq + node2.freq)\n merged.left = node1\n merged.right = node2\n\n heapq.heappush(heap, merged)\n return heap\n\n def code_helper(self, root, current_code, codes):\n # Return when None\n if not root:\n return\n\n # Required assign character to node (only leaf has)\n if root.char:\n codes[root.char] = current_code\n return\n\n # Recursion\n self.code_helper(root.left, current_code + '0', codes)\n self.code_helper(root.right, current_code + '1', codes)\n\n def make_codes(self, heap):\n current_code = ''\n codes = {}\n root = heapq.heappop(heap)\n\n self.code_helper(root, current_code, codes)\n return codes\n\n def huffman_codes(self, dictionary):\n nodes = self.make_nodes_heap(dictionary)\n heap = self.merge_nodes(nodes)\n codes = self.make_codes(heap)\n return codes\n\n def encode(self, dictionary):\n code = []\n current_key = ''\n basic_key = ''\n\n for letter in self.content:\n current_key += letter\n if current_key in dictionary:\n basic_key += letter\n else:\n code.append(dictionary.get(basic_key))\n basic_key = letter\n current_key = letter\n\n code.append(dictionary.get(basic_key))\n return code\n\n @staticmethod\n def decode(dictionary, content):\n END_CONTENT_CHAR = '^'\n decoded = ''\n current_code = ''\n\n for bit in content.to01():\n current_code += str(bit)\n if current_code in dictionary:\n char = dictionary.get(current_code)\n decoded += char\n current_code = ''\n\n return decoded\n\n\nclass Node:\n def __init__(self, char, card):\n self.char = char\n self.freq = card\n self.left = None\n self.right = None\n\n def __eq__(self, other):\n return self.freq == other.freq\n\n def __lt__(self, other):\n return self.freq < other.freq\n\n def __gt__(self, other):\n return self.freq > other.freq\n\n\ndef load_dictionary(file_name):\n dictionary = {}\n with open(file_name, 'r') as file:\n content = file.read()\n fill = len(content).bit_length()\n for index, char in enumerate(content):\n bits = int2bits(index + 1, fill=fill)\n dictionary.update({bits: char})\n\n return dictionary\n\n\ndef load_huffman_dictionary(file_name):\n dictionary = {}\n with open(file_name, 'r') as file:\n content = file.read()\n slited = content.split('^')\n for index, val in enumerate(slited):\n if index % 2 == 1:\n dictionary.update({val: slited[index - 1]})\n\n return dictionary\n\n\ndef load_content(file_name):\n content = bitarray()\n with open(file_name, 'rb') as file:\n content.fromfile(file)\n return content\n\n\ndef write_list(encoded_content_list, file_name):\n with open(file_name, 'wb') as file:\n bitarray.tofile(bitarray(''.join(encoded_content_list)), file)\n\n\ndef write_dictionary(dictionary, file_name):\n with open(file_name, 'w') as file:\n for key in dictionary.keys():\n file.write(key)\n\n\ndef write_huffman_dictionary(dictionary, file_name):\n with open(file_name, 'w') as file:\n for key, value in dictionary.items():\n file.write(key)\n file.write('^')\n file.write(value)\n file.write('^')\n\n\ndef calculate_size(file_name):\n return os.stat(file_name).st_size\n\n\ndef main():\n # file_name = '../Exercise_3/short_sample.txt'\n file_name = 'wiki_sample.txt'\n # content = read_binary_file('lena.bmp')\n\n ################################\n ####### Lempel–Ziv–Welch #######\n ################################\n content = read_file(file_name)\n characters_dictionary = analyze_content(content)\n sorted_characters_dictionary = sort_dictionary_items(characters_dictionary)\n basic_lzw = BasicLZW(content, sorted_characters_dictionary)\n lzw_basic_code = basic_lzw.create()\n bits_codes = basic_lzw.codes_to_bits(lzw_basic_code)\n write_dictionary(lzw_basic_code, 'lzw_dictionary.txt')\n\n encoded_content = basic_lzw.encode(bits_codes)\n write_list(encoded_content, 'lzw_content.bin')\n encoded = load_content('lzw_content.bin')\n decode_codes = load_dictionary('lzw_dictionary.txt')\n decoded = basic_lzw.decode(decode_codes, encoded)\n\n print('LZW basic format')\n print('\\tBefore =>', calculate_size(file_name), '[bytes]')\n print('\\tAfter =>', calculate_size('lzw_content.bin'), '[bytes]')\n\n #############################\n ####### LZW + Huffman #######\n #############################\n content = read_file(file_name)\n characters_dictionary = analyze_content(content)\n sorted_characters_dictionary = sort_dictionary_items(characters_dictionary)\n lzw_huffman = LZWHuffman(content, sorted_characters_dictionary)\n lzw_basic_code = lzw_huffman.create()\n bits_codes = lzw_huffman.codes_to_bits(lzw_basic_code)\n codes_with_counters = lzw_huffman.append_counters(bits_codes)\n codes_with_cardinality, total_counter = lzw_huffman.pre_encode(codes_with_counters)\n print(codes_with_cardinality)\n codes_clear_cardinality = lzw_huffman.remove_n_cardinality_items(codes_with_cardinality, n=2)\n huffman_codes = lzw_huffman.huffman_codes(codes_with_cardinality)\n encoded = lzw_huffman.encode(huffman_codes)\n write_list(encoded, 'lzw_huffman_content.bin')\n write_huffman_dictionary(huffman_codes, 'lzw_huffman_keys.txt')\n loaded_dictionary = load_huffman_dictionary('lzw_huffman_keys.txt')\n loaded_content = load_content('lzw_huffman_content.bin')\n decoded = lzw_huffman.decode(loaded_dictionary, loaded_content)\n\n print('LZW + Huffman format')\n print('\\tBefore =>', calculate_size(file_name), '[bytes]')\n print('\\tAfter =>', calculate_size('lzw_huffman_content.bin'), '[bytes]')\n print('\\tKeys =>', calculate_size('lzw_huffman_keys.txt'), '[bytes]')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"semestr_6_metody_kompresji_danych/Exercise_6/Exercise_6.py","file_name":"Exercise_6.py","file_ext":"py","file_size_in_byte":12679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"618354756","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport json\nimport os\nimport csv \nimport getopt\nimport sys\nimport argparse\n\n######################################################################\n# Parse all JSON files to construct syndrome to omim ID mapping \n#######################################################################\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Generate summary file')\n parser.add_argument('-c', '--case', help='path to convert file')\n parser.add_argument('-o', '--output', help='path to output file')\n\n args = parser.parse_args()\n # syn_dict = {'name':[omim_id]}\n syn_dict = {}\n case_path = args.case\n for case in os.listdir(case_path):\n print(case)\n file_name = os.path.join(case_path, case)\n case_file = open(file_name)\n case_data = json.load(case_file)\n if 'detected_syndromes' not in case_data:\n continue\n data = case_data['detected_syndromes']\n for syn_data in data:\n name = syn_data['syndrome_name']\n omim = syn_data['omim_id']\n if type(name) == list:\n continue\n if syn_data['has_mask'] == 0:\n continue\n if name in syn_dict and omim == None:\n continue\n omim_out = []\n if type(omim) == int:\n omim_out.append(omim)\n else:\n omim_out = omim\n syn_dict.update({name:omim_out})\n print(len(syn_dict))\n print(syn_dict)\n\n syn_file = open(os.path.join(args.output,'gestalt_syn_to_omim.csv'), 'w')\n syn_writer = csv.writer(syn_file, delimiter='\\t')\n for syn in syn_dict:\n print(syn)\n print(syn_dict[syn])\n syn_writer.writerow([syn, syn_dict[syn]])\n syn_file.close()\n","sub_path":"helper/syndrome_to_gene_dict.py","file_name":"syndrome_to_gene_dict.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"166159599","text":"import csv \n\noutput = \"D:\\\\MyDownloads\\\\fakenews.csv\"\nout = open(output, 'w', newline='')\nwriter = csv.writer(out)\ntry:\n\twith open('D:\\\\MyDownloads\\\\fake.csv', encoding='utf8') as csvfile:\n\t\treadCSV = csv.reader(csvfile, delimiter=',')\n\t\tfor row in readCSV:\n\t\t\twriter.writerow((row[4],row[5],'fake'))\nexcept:\n\tprint(\"Error\")\n\nout.close()","sub_path":"crawler/cleaner.py","file_name":"cleaner.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"297521651","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 4 15:41:01 2017\n\n@author: sabrina.yue.wang\n\"\"\"\nimport sys\nimport os\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom sf import Ui_Dialog\nfrom PyQt5.QtCore import QThread, pyqtSignal, pyqtSlot, QObject\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QInputDialog, QFileDialog, QStatusBar\nimport matplotlib\nmatplotlib.use('Qt5Agg')\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nimport numpy\nimport pickle\nimport math\nimport importlib\nimport os.path\n\ncurrentdir=os.getcwd()\nsys.path.insert(1, '{}/../'.format(currentdir))\nsys.path.insert(1, '{}/../utils/'.format(currentdir))\nsys.path.insert(1, '{}/../plots'.format(currentdir))\nsys.path.insert(1, '{}/../objects'.format(currentdir))\n\nfrom analysis_dust import BEffectsAnalysis\nfrom utils import generate_particle_equilibrium_positions, prepare_modified_b_field\nfrom plots import dustplots\n\nfrom IPython import get_ipython\n\n\nipython = get_ipython()\nipython.magic('load_ext autoreload')\nipython.magic('autoreload 2')\n\n\nclass SpectrumCanvas(FigureCanvas):\n\t'''\n\tProvides ability for displaying figures and animations on gui\n\t'''\n\tdef __init__(self, parent=None, width=7.31, height=4.21, dpi=100):\n\t\tself.fig = Figure(figsize=(width, height), dpi=dpi)\n\t\t\n\t\tFigureCanvas.__init__(self, self.fig)\n\t\tself.setParent(parent)\n\t\tFigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding,\n\t\t\t\t\t\t\t\t QtWidgets.QSizePolicy.Expanding)\n\t\tFigureCanvas.updateGeometry(self)\n\t\n\t\n\n\nclass SFGui(Ui_Dialog): #Setting up/Connecting the gui buttons and connecting them to their associated functions\n\tdef __init__(self, dialog):\n\t\tUi_Dialog.__init__(self)\n\t\tself.setupUi(dialog)\n\t\tself.graph = SpectrumCanvas(self.graphicsView)\n\t\tself.graph.setObjectName(\"graph\")\n\t\tself.error=QtWidgets.QGraphicsScene()\n\t\tself.pushButton.clicked.connect(self.simtime)\n\t\tself.pushButton_2.clicked.connect(self.particlenumber)\n\t\tself.pushButton_2.clicked.connect(self.run)\n\t\tself.time = 0;\n\t\tself.particlenumber = 0;\n \n\tdef addInputTextToListbox(self): #Add user input\n\t\ttxt = self.myTextInput.text()\n\n\tdef simtime(self):\n\t\ttext2,ok2 = QInputDialog.getText(dialog, 'User Input','Enter simulation time in seconds')\n\t\tself.time=float(text2.split()[0])\n\n\tdef particlenumber(self):\n\t\ttext, ok = QInputDialog.getText(dialog, 'User Input','Enter particle number')\n\t\tself.particlenumber = float(text.split()[0])\n\tdef run(self):\n\t\tbeffect1 = BEffectsAnalysis()\n\t\tbeffect1.create_particles(\n\t\t\tnumparticles=10,\n\t\t\tinitpositions=generate_particle_equilibrium_positions()\n\t\t)\n\t\tbeffect1.create_pairs()\n\t\tbeffect1.interact_and_iterate(\n\t\t\titerationsB=100,\n\t\t\tinit_iterations=100,\n\t\t\tmethod='NoGibs',\n\t\t\tmodified_b_field=prepare_modified_b_field()\n\t\t)\n\t\tbeffect1.sort_positions_of_particles()\n\n\t\n\n\n\t\t\n \nif __name__ == '__main__':\n\tapp = QtWidgets.QApplication(sys.argv)\n\tdialog = QtWidgets.QDialog()\n \n\tprog = SFGui(dialog)\n \n\tdialog.show()\n\tsys.exit(app.exec_())\n\t\n\n\t","sub_path":"gui/sfrun.py","file_name":"sfrun.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"384070341","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# \n# launcher.py\n# \n# This file is part of the RoboEarth Cloud Engine framework.\n# \n# This file was originally created for RoboEearth\n# http://www.roboearth.org/\n# \n# The research leading to these results has received funding from\n# the European Union Seventh Framework Programme FP7/2007-2013 under\n# grant agreement no248942 RoboEarth.\n# \n# Copyright 2012 RoboEarth\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# \\author/s: Dominique Hunziker \n# \n# \n\n# ROS specific imports\nimport rospy\n\n# twisted specific imports\nfrom twisted.python import log\n\n# Custom imports\nfrom core.types import cmd as types\nfrom core.manager import NodeManager\nfrom core.command import ControlDistributor, NodeCommand\nfrom comm import definition\nfrom comm import types as msgTypes\nfrom comm.manager import CommManager\nfrom comm.protocol import RCEServerFactory\nfrom remote.message import CommandSerializer, TagSerializer, \\\n CommandProcessor, TagProcessor\n\nfrom settings import ROS_NODE_PORT\n\n\nclass User(object):\n def __init__(self):\n self.nodes = {}\n\nNodeManager._USER_CLS = User\n\n\ndef main(reactor, commID, port):\n f = open('/home/ros/launcher.log', 'w')\n log.startLogging(f)\n \n rospy.init_node('RCE_Launcher')\n \n manager = NodeManager(reactor)\n commManager = CommManager(reactor, commID)\n cmdSerializer = CommandSerializer()\n cmdSerializer.registerCommand([NodeCommand])\n commManager.registerContentSerializers([cmdSerializer,\n TagSerializer()])\n \n distributor = ControlDistributor()\n distributor.addHandler(types.NODE, manager.addNode)\n distributor.addHandler(types.RM_NODE, manager.removeNode)\n commManager.registerMessageProcessors([CommandProcessor(distributor),\n TagProcessor(distributor)])\n \n factory = RCEServerFactory(commManager)\n factory.addApprovedMessageTypes([msgTypes.COMMAND, msgTypes.TAG])\n reactor.listenTCP(port, factory)\n \n def terminate():\n reactor.callFromThread(manager.shutdown)\n reactor.callFromThread(commManager.shutdown)\n reactor.callFromThread(reactor.stop)\n\n rospy.on_shutdown(terminate)\n \n reactor.run(installSignalHandlers=False)\n \n f.close()\n\n\nif __name__ == '__main__':\n from twisted.internet import reactor\n \n main(reactor, definition.NEIGHBOR_ADDR, ROS_NODE_PORT)\n","sub_path":"framework/launcher.py","file_name":"launcher.py","file_ext":"py","file_size_in_byte":3052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"163321686","text":"import logging\nimport sys\nimport argparse,textwrap\n\ndef crisprseq_parseargs():\n \"\"\"\n Parsing mageck arguments.\n \"\"\"\n parser=argparse.ArgumentParser(description='MAGeCK-NEST: performs sgRNA, gene and pathway analysis on CRISPR-Cas9 screening data.')\n # definition of sub commands\n parser.add_argument('-v', '--version',action='version',version='%(prog)s 0.0.1')\n subparser=parser.add_subparsers(help='commands to run mageck',dest='subcmd')\n subm_nest=subparser.add_parser('nest',help='Perform estimation of gene essentiality.')\n\n reqgroup=subm_nest.add_argument_group(title='Required arguments',\n description='')\n reqgroup.add_argument('-k','--count_table',required=True,help='Provide a tab-separated count table. Each line in the table should include sgRNA name (1st column), target gene (2nd column) and read counts in each sample.')\n reqgroup.add_argument('-d','--design_matrix',required=True,help='Provide a design matrix, either a quoted string of the design matrix or a file name. If using quoted string, for instance, \"1,0;1,1\" can be used for 2-sample conditions like 0_day and 4_weeks, and --include-samples should be specified as \"0_day,4_weeks\". If a file is given, the row of the design matrix must match the order of the samples in the count table, or the order of the samples by the --include-samples option.')\n\n iogroup=subm_nest.add_argument_group(title='Optional arguments for input and output',\n description='')\n iogroup.add_argument('-n','--output-prefix',default=None,help='The prefix of the output file(s).')\n iogroup.add_argument('-i', '--include-samples', help='Specify the sample labels if the design matrix is not given by file in the --design-matrix option. Sample labels are separated by \",\", and must match the labels in the count table.')\n iogroup.add_argument('-b', '--beta-labels', help='Specify the labels of the variables (i.e., beta), if the design matrix is not given by file in the --design-matrix option. Should be separated by \",\", and the number of labels must equal to (# columns of design matrix), including baseline labels. Default value: \"bata_0,beta_1,beta_2,...\".')\n\n genegroup=subm_nest.add_argument_group(title='Optional arguments for normalization.',\n description='\"--norm-method control -e non_essential_genes_control\" is recommended, which you have to specify negative control names, such as AAVS1')\n genegroup.add_argument(\"--norm-method\",choices=['none','median','total','control'],default='median',help='Method for normalization, including \"none\" (nonormalization), \"median\" (median normalization, default), \"total\" (normalization by total read counts), \"control\" (normalization by control sgRNAs specified by the --control-sgrna option). Defautl is median.')\n genegroup.add_argument(\"-e\",\"--negative_control\",help=\"The name of negative controls, such as AAVS1.\",default=[])\n genegroup.add_argument('--genes-varmodeling',default=\"2000\",help='The number of genes for mean-variance modeling. Default is 2000.')\n genegroup.add_argument('--adjust-method',choices=['fdr','holm','pounds'],default='fdr',help='Method for sgrna-level p-value adjustment, including false discovery rate (fdr), holm\\'s method (holm), or pounds\\'s method (pounds). Defautl is FDR.')\n\n advancegroup=subm_nest.add_argument_group(title='Optional arguments for PPI incorporation and outliers removal',\n description='')\n advancegroup.add_argument(\"-o\",\"--outliers_removal\",action='store_true',help=\"Speicify whehter you want to remove outliers and recalculate..\")\n advancegroup.add_argument(\"-p\",\"--PPI_prior\",action='store_true',help=\"Specify whether you want to incorporate PPI as prior\")\n advancegroup.add_argument(\"-q\",\"--QC_metric\",action='store_true',help=\"Specify whether you want to derive quality control metrics\")\n\n advancegroup=subm_nest.add_argument_group(title='Example',\n description='mageck_nest nest -n mageck_nest_cell_line_A -i day_0,week_4 -k readcount_table.txt --norm-method control -e AAVS1 -d \"1,0;1,1\" -q')\n #--------------------------------------------------------------------------------\n args=parser.parse_args()\n\n if args.subcmd == None:\n parser.print_help()\n sys.exit(0)\n if args.output_prefix==None:\n args.output_prefix=\"mageck_nest_{}\".format(args.count_table)\n if args.negative_control!=[]:\n args.negative_control=args.negative_control.split(',')\n args.negative_control=[i.upper() for i in args.negative_control]\n\n return args\n\ndef postargs(args):\n '''\n post-processing of argument parsing\n '''\n # configure logging information\n logging.basicConfig(level=10,\n format='%(levelname)-5s @ %(asctime)s.%(msecs)03d: %(message)s ',\n datefmt='%a, %d %b %Y %H:%M:%S',\n # stream=sys.stderr,\n filename=args.output_prefix+'.log',\n filemode='w'\n )\n console = logging.StreamHandler()\n console.setLevel(logging.INFO)\n # set a format which is simpler for console use\n formatter = logging.Formatter('%(levelname)-5s @ %(asctime)s.%(msecs)03d: %(message)s ','%a, %d %b %Y %H:%M:%S')\n console.setFormatter(formatter)\n # add the handler to the root logger\n logging.getLogger('').addHandler(console)\n logging.info('Parameters: '+' '.join(sys.argv))\n\n from mageck_nest.mledesignmat import parse_designmat\n\n try:\n import scipy\n from scipy.stats import nbinom\n except ImportError:\n logging.error('Cannot find scipy (required for mle approach). Please check your scipy installation.')\n sys.exit(-1)\n try:\n import numpy as np\n import numpy.linalg as linalg\n except ImportError:\n logging.error('Cannot find numpy (required for mle approach). Please check your numpy installation.')\n sys.exit(-1)\n # parsing design matrix\n (desmat,sampleid,betalabel)=parse_designmat(args.design_matrix)\n args.design_matrix=desmat\n\n # parsing sample label\n if sampleid ==None:\n # design matrix is provided as a string\n if args.include_samples !=None:\n args.include_samples=args.include_samples.split(',')\n if len(args.include_samples) != desmat.shape[0]:\n logging.error('The number of samples in the --include-samples option do not match rows in design matrix.')\n sys.exit(-1)\n if args.beta_labels!=None:\n args.beta_labels=args.beta_labels.split(',')\n if len(args.beta_labels) != desmat.shape[1]:\n logging.error('The number of labels in the --beta-labels option do not match columns in design matrix.')\n sys.exit(-1)\n else:\n # design matrix is provided as file\n if args.include_samples !=None:\n logging.error('Sample labels are included in the design matrix file '+args.design_matrix+'. The --include-samples option should not be used.')\n sys.exit(0)\n if args.beta_labels!=None:\n logging.error('Beta labels are included in the design matrix file '+args.design_matrix+'. The --beta-labels option should not be used.')\n sys.exit(0)\n args.include_samples=sampleid\n args.beta_labels=betalabel\n if len(args.include_samples) != desmat.shape[0]:\n logging.error('The number of samples in the --include-samples option do not match rows in design matrix.')\n sys.exit(-1)\n if len(args.beta_labels) != desmat.shape[1]:\n logging.error('The number of labels in the --beta-labels option do not match columns in design matrix.')\n sys.exit(-1)\n # log design matrix and column, row labels\n logging.info('Design matrix:')\n for desmat_1line in str(desmat).split('\\n'):\n logging.info(desmat_1line)\n if args.beta_labels != None:\n logging.info('Beta labels:'+','.join(args.beta_labels))\n if args.include_samples != None:\n logging.info('Included samples:'+','.join(args.include_samples))\n\n return args\n","sub_path":"argParser.py","file_name":"argParser.py","file_ext":"py","file_size_in_byte":7995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"372217939","text":"import torch\r\nfrom torch.nn import functional as F\r\nfrom torch import Tensor\r\n\r\n__all__ = [\"Lovasz_softmax\"]\r\n\r\ndef dice_coeff(input: Tensor, target: Tensor, reduce_batch_first: bool = False, epsilon=1e-6):\r\n # Average of Dice coefficient for all batches, or for a single mask\r\n assert input.size() == target.size()\r\n if input.dim() == 2 and reduce_batch_first:\r\n raise ValueError(f'Dice: asked to reduce batch but got tensor without batch dimension (shape {input.shape})')\r\n\r\n if input.dim() == 2 or reduce_batch_first:\r\n inter = torch.dot(input.contiguous().view(-1), target.contiguous().view(-1))\r\n sets_sum = torch.sum(input) + torch.sum(target)\r\n if sets_sum.item() == 0:\r\n sets_sum = 2 * inter\r\n\r\n return (2 * inter + epsilon) / (sets_sum + epsilon)\r\n else:\r\n # compute and average metric for each batch element\r\n dice = 0\r\n for i in range(input.shape[0]):\r\n dice += dice_coeff(input[i, ...], target[i, ...])\r\n return dice / input.shape[0]\r\n\r\ndef multiclass_dice_coeff(input: Tensor, target: Tensor, reduce_batch_first: bool = False, epsilon=1e-6):\r\n # Average of Dice coefficient for all classes\r\n assert input.size() == target.size()\r\n dice = 0\r\n for channel in range(input.shape[1]):\r\n dice += dice_coeff(input[:, channel, ...], target[:, channel, ...], reduce_batch_first, epsilon)\r\n\r\n return dice / input.shape[1]\r\n\r\n\r\ndef dice_loss(input: Tensor, target: Tensor, multiclass: bool = False):\r\n # Dice loss (objective to minimize) between 0 and 1\r\n assert input.size() == target.size()\r\n fn = multiclass_dice_coeff if multiclass else dice_coeff\r\n return 1 - fn(input, target, reduce_batch_first=True)\r\n\r\ndef lovasz_grad(gt_sorted):\r\n \"\"\"\r\n Computes gradient of the Lovasz extension w.r.t sorted errors\r\n See Alg. 1 in paper\r\n \"\"\"\r\n p = len(gt_sorted)\r\n gts = gt_sorted.sum()\r\n intersection = gts - gt_sorted.float().cumsum(0)\r\n union = gts + (1 - gt_sorted).float().cumsum(0)\r\n jaccard = 1. - intersection / union\r\n if p > 1: # cover 1-pixel case\r\n jaccard[1:p] = jaccard[1:p] - jaccard[0:-1]\r\n return jaccard\r\n\r\nclass Lovasz_softmax(torch.nn.Module):\r\n def __init__(self, reduction='mean'):\r\n super(Lovasz_softmax, self).__init__()\r\n self.reduction = reduction\r\n\r\n def prob_flatten(self, input, target):\r\n assert input.dim() in [4, 5]\r\n num_class = input.size(1)\r\n if input.dim() == 4:\r\n input = input.permute(0, 2, 3, 1).contiguous()\r\n input_flatten = input.view(-1, num_class)\r\n elif input.dim() == 5:\r\n input = input.permute(0, 2, 3, 4, 1).contiguous()\r\n input_flatten = input.view(-1, num_class)\r\n target_flatten = target.view(-1)\r\n return input_flatten, target_flatten\r\n\r\n def lovasz_softmax_flat(self, inputs, targets):\r\n num_classes = inputs.size(1)\r\n losses = []\r\n for c in range(num_classes):\r\n target_c = (targets == c).float()\r\n if num_classes == 1:\r\n input_c = inputs[:, 0]\r\n else:\r\n input_c = inputs[:, c]\r\n loss_c = (torch.autograd.Variable(target_c) - input_c).abs()\r\n loss_c_sorted, loss_index = torch.sort(loss_c, 0, descending=True)\r\n target_c_sorted = target_c[loss_index]\r\n losses.append(torch.dot(loss_c_sorted, torch.autograd.Variable(lovasz_grad(target_c_sorted))))\r\n losses = torch.stack(losses)\r\n\r\n if self.reduction == 'none':\r\n loss = losses\r\n elif self.reduction == 'sum':\r\n loss = losses.sum()\r\n else:\r\n loss = losses.mean()\r\n return loss\r\n\r\n def forward(self, inputs, targets):\r\n inputs_ls, targets_ls = self.prob_flatten(inputs, targets)\r\n losses = self.lovasz_softmax_flat(inputs_ls, targets_ls)\r\n losses_combine= losses + dice_loss(F.softmax(inputs,dim=1).float(),\r\n F.one_hot(targets,2).permute(0,3,1,2).float(),\r\n multiclass=True)\r\n return losses_combine","sub_path":"network/loss_function.py","file_name":"loss_function.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"487003918","text":"from tkinter import * \n\n#dummy function to execute on menu or button click \ndef function1():\n print(\"menu item clicked\")\n\n#create window called Tk\nroot = Tk()\n\n#create menu object from Menu class and add it to root \nmymenu = Menu(root)\n#configure root to mymenu object \nroot.config(menu=mymenu)\n\n#create filemenu \nfilemenu = Menu(mymenu)\nmymenu.add_cascade(label=\"File\", menu=filemenu)\n#add submenus project and save\nfilemenu.add_command(label=\"Project\", command=function1)\nfilemenu.add_command(label=\"save\", command=function1)\n#add seperator\nfilemenu.add_separator()\n# add submenu exit\nfilemenu.add_command(label=\"Exit\", command=function1)\n#add edit main menu \neditmenu = Menu(mymenu)\nmymenu.add_cascade(label=\"edit\", menu=editmenu)\n# add undo sub menu under edit \neditmenu.add_command(label=\"undo\",command=function1)\n\n#create toolbar using frame class and add it to root \ntoolbar = Frame(root, bg=\"light grey\")\n\n#create inser and print button to add to tool bar\ninsertbutton = Button(toolbar, text=\"insert files\", command = function1)\ninsertbutton.pack(side = LEFT,padx=2, pady=3)\n\nprintbutton = Button(toolbar, text=\"print\", command=function1)\nprintbutton.pack(side=LEFT, padx = 2, pady =3)\n\n#add toolbar to window\ntoolbar.pack(side=TOP, fill=X)\n\nstatus = Label(root, text = \"This is the status\", bd = 1, relief=SUNKEN, anchor=W)\n\nstatus.pack(side=BOTTOM, fill=X)\nroot.mainloop()","sub_path":"Sections/section10/statusbar.py","file_name":"statusbar.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"27056053","text":"from cardData import *\n\n\nclass DataBases:\n\n DOUBLE_QUOTE = \"\\\"\"\n SEMI_COLON = \";\"\n SEPARATOR = \", \"\n SINGLE_QUOTE = r\"'\"\n\n @staticmethod\n def enclose(string, enclose_char):\n return enclose_char + string + enclose_char\n\n def value_data_to_insert_sql(self, table, columns, data_sets):\n columns = self.SEPARATOR.join(columns)\n sql = f\"INSERT INTO {table}({columns})\\n VALUES\"\n for data_set in data_sets:\n for data in data_set:\n if isinstance(data, str):\n index = data_set.index(data)\n data = self.enclose(data, self.DOUBLE_QUOTE)\n data_set[index] = data\n data_set = self.SEPARATOR.join(data_set)\n sql += f\"({data_set})\"\n sql += self.SEPARATOR\n sql = sql[:-len(self.SEPARATOR)]\n return sql + self.SEMI_COLON # DON'T FORGET A SEMICOLON!\n\n\nsql_code = DataBases().value_data_to_insert_sql(\"cards\",\n [\"cardName\", \"cardRarity\",\n \"cardCondition\", \"cardGame\",\n \"cardLocation\"],\n vanilla_box)\ntry:\n f = open(\"sqlCode.sql\", \"x\")\n f.close()\nexcept IOError:\n pass\nfinally:\n with open(\"sqlCode.sql\", \"r+\") as f:\n f.write(sql_code)\n\n\nquit()\n","sub_path":"cardDB.py","file_name":"cardDB.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"516635425","text":"\n\nbudget = int(input())\n\nitem = input()\ntotalValue = 0\nwhile item != \"Stop\":\n itemValue = 0\n for letter in item:\n itemValue += ord(letter)\n if itemValue <= budget:\n budget -= itemValue\n print(\"Item successfully purchased!\")\n else:\n print(\"Not enough money!\")\n break\n item = input()\n\nif item == \"Stop\":\n print(f\"Money left: {budget}\")","sub_path":"General/Learning/SoftUni Test/ProgrammingBasics/ChristmasDecoration.py","file_name":"ChristmasDecoration.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"419570525","text":"# Code for caluclating the Henry's Constants for a variety of gas mixutres.\n\nimport ast\nimport copy\nimport csv\nimport glob\nimport itertools\nimport matplotlib\nimport numpy as np\nimport os\nimport re\nimport scipy.stats as ss\nimport yaml\n\nfrom collections import OrderedDict\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\n\nfrom generate_compositions import create_uniform_comp_list\n\nimport time\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\n\n\n\n# ----- General Use -----\ndef yaml_loader(filepath):\n with open(filepath, 'r') as yaml_file:\n data = yaml.load(yaml_file)\n return data\n\n\ndef import_simulated_data(sim_results, sort_by_gas=False, gas_for_sorting=None):\n with open(sim_results) as file:\n reader = csv.DictReader(file, delimiter='\\t')\n reader_list = list(reader)\n keys = reader.fieldnames\n\n for row in reader_list:\n # Isolate Mass Data since currently being assigned to single key\n mass_data_temp = [float(val) for val in row[keys[2]].split(' ')]\n num_gases = len(row)-len(mass_data_temp)-2\n # Reassign Compositions\n for i in range(num_gases):\n row[keys[-num_gases+i]] = row[keys[i+3]]\n # Reassign Masses\n for i in range(num_gases*2+2):\n row[keys[i+2]] = mass_data_temp[i]\n\n if sort_by_gas == True:\n reader_list = sorted(reader_list, key=lambda k: k[gas_for_sorting+'_comp'], reverse=False)\n\n return keys, reader_list\n\n\n\n\n# ----- Calculating Herny's Coefficients -----\ndef plot_adsorbed_masses(all_comps, all_masses, all_errors, gases, figname=None, gas_name=None, mof_name=None):\n plt.clf()\n plt.figure(figsize=(4,3), dpi=600)\n\n for i in range(len(gases)):\n comps = all_comps[i]\n mass = all_masses[i]\n plt.plot(comps, mass, 'o', markersize=2, alpha=0.7)\n\n if mof_name != None:\n plt.title(mof_name)\n plt.xlabel(gases[0]+' Mole Fractions')\n plt.ylabel('Adsorbed Mass')\n plt.legend(gases)\n plt.tight_layout()\n if figname != None:\n plt.savefig(figname)\n plt.close()\n\n\ndef plot_kH_single_gas(comps, mass, error, max_comp, kH, intercept, R2, figname='None', gas_name='None', mof_name='None'):\n\n # Initialize Figure\n plt.clf()\n plt.figure(figsize=(4,3), dpi=600)\n if kH != None:\n fit = np.poly1d([kH, intercept])\n plt.plot(comps, fit(comps), 'r-')\n plt.errorbar(comps, mass, error, marker='o', markersize=3, elinewidth=1, linewidth=0)\n if mof_name != 'None':\n plt.title(mof_name, fontsize=12)\n if gas_name != 'None':\n plt.xlabel(gas+' Mole Fraction', fontsize=10)\n else:\n plt.xlabel('Mole Fraction', fontsize=10)\n plt.xticks(np.linspace(0,0.05,6), fontsize=8)\n plt.ylabel('Adsorbed Mass\\n[mg/g Framework]', fontsize=10)\n plt.yticks(fontsize=8)\n plt.ylim([0.75*(min(mass)-max(error)),1.25*(max(mass)+max(error))])\n plt.tight_layout()\n textstr='\\n'.join(['K_H = '+str(np.round(kH, 2)),'Max. Comp. = '+str(np.round(max_comp, 3))])\n props = dict(boxstyle='round', facecolor='white', alpha=1)\n plt.text(0.3*max(comps), 1.08*max(mass)+max(error), textstr, fontsize=10, bbox=props)\n plt.savefig(figname)\n plt.close()\n\n\ndef plot_kH_air(comps, mass, error, max_comp, kH, intercept, R2, figname='None', gas_name='None', mof_name='None'):\n # Redefine the Fit\n fit = np.poly1d([kH, intercept])\n\n # Initialize Figure\n plt.clf()\n plt.figure(figsize=(4,3), dpi=600)\n plt.plot(comps, fit(comps), 'r-')\n plt.errorbar(comps, mass, error, marker='o', markersize=3, elinewidth=1, linewidth=0)\n if mof_name != 'None':\n plt.title(mof_name, fontsize=12)\n if gas_name != 'None':\n plt.xlabel(gas+' Mole Fraction', fontsize=10)\n else:\n plt.xlabel('Mole Fraction', fontsize=10)\n # plt.xticks(np.linspace(0,0.05,6), fontsize=8)\n plt.ylabel('Adsorbed Mass\\n[mg/g Framework]', fontsize=10)\n plt.yticks(fontsize=8)\n plt.ylim([0,1.5*(max(mass)+max(error))])\n plt.tight_layout()\n textstr='\\n'.join(['K_H = '+str(np.round(kH, 2)),'Max. Comp. = '+str(np.round(max_comp, 3))])\n props = dict(boxstyle='round', facecolor='white', alpha=1)\n plt.text(0.01, 1.4*(max(mass)+max(error)), textstr, fontsize=10, verticalalignment='top', bbox=props)\n plt.savefig(figname)\n plt.close()\n\n\ndef plot_kH_multiple_gases(all_comps, all_masses, all_errors, kH, intercept, figname='None', gas_name='None', mof_name='None'):\n # Define Colors\n cmap_vals = np.linspace(0,1,2)\n colors = [mpl.cm.bwr(x) for x in cmap_vals]\n\n # Initialize Figure\n plt.clf()\n plt.figure(figsize=(4,3), dpi=600)\n\n for i in range(all_comps):\n kH = all_kHs[i]\n comps = all_comps[i]\n mass = all_masses[i]\n error = all_errors[i]\n intercepts = all_intercepts[i]\n\n fit = np.poly1d([kH, intercept])\n plt.plot(comps, fit(comps), 'r-')\n plt.errorbar(comps, mass, error, marker='o', markersize=3, elinewidth=1, linewidth=0, color=colors[0])\n\n # Define labels with respect to Henry's Gas (positionally first).\n if mof_name != 'None':\n plt.title(mof_name, fontsize=12)\n if gas_name != 'None':\n plt.xlabel(gas+' Mole Fraction', fontsize=10)\n else:\n plt.xlabel('Mole Fraction', fontsize=10)\n plt.xticks(np.linspace(0,0.05,6), fontsize=8)\n plt.ylabel('Absolute Loading\\n[mg/g Framework]', fontsize=10)\n plt.yticks(fontsize=8)\n plt.tight_layout()\n plt.savefig(figname)\n plt.close()\n\n\ndef calculate_kH(comps, mass, error, eval_type='R2', r2_min=0.99, rmse_min=0.10, weight='error', flipped=False, i_offset=0, counter=1):\n\n # Make sure data is properly sorted\n indicies = np.argsort(comps)\n comps_sorted = [comps[i] for i in indicies]\n mass_sorted = [mass[i] for i in indicies]\n error_sorted = [error[i] for i in indicies]\n comps = comps_sorted\n mass = mass_sorted\n error = error_sorted\n\n if flipped == True:\n print('Flipped!')\n comps = np.flipud(comps)\n mass = np.flipud(mass)\n error = np.flipud(error)\n\n for i in range(len(comps)-i_offset,-counter,-1):\n\n # Check if enough points for a proper fit\n if i <= 2:\n print('Could not fit to given data!')\n return None, 0, 0, 0, 0, 0\n\n # Create a weighting matrix\n if weight == 'None':\n weights=np.ones(len(error[0:i]))\n elif weight == 'error':\n if 0 not in error[0:i]:\n weights=np.divide(1,error[0:i])\n else:\n weights_temp = [1/val for val in error[0:i] if val != 0]\n if len(weights_temp) != 0:\n weights = np.array([1/val if val != 0 else max(weights_temp) for val in error[0:i]])\n else:\n weights = np.ones(len(error[0:i]))\n elif weight == 'error_squared':\n error_squared = []\n for j in error[0:i]:\n error_squared.extend([j**2])\n if 0 not in error_sqaured:\n weights = np.divide(1,error_squared)\n else:\n weights_temp = [1/val for val in error_squared if val != 0]\n if len(weights_temp) != 0:\n weights = np.array([1/val if val != 0 else max(weights_temp) for val in error_squared])\n else:\n weights = np.ones(len(error_sqaured[0:i]))\n else:\n raise NameError('Invalid Error Type!')\n\n # Fit a Line\n # p, V = np.polyfit(comps[0:i], mass[0:i], 1, cov=True, w=weights)\n p = np.polyfit(comps[0:i], mass[0:i], 1, cov=False, w=weights)\n\n # Calculate R_Squared and RMSE\n fit = np.poly1d(p)\n predicted_vals = fit(comps[0:i])\n residuals = predicted_vals-mass[0:i]\n ybar = np.sum(mass[0:i])/len(mass[0:i])\n ss_res = np.sum(residuals**2)\n ss_tot = np.sum((mass[0:i]-ybar)**2)\n R2 = 1-(ss_res/ss_tot)\n MSE = ss_res/len(mass[0:i])\n RMSE = MSE**(0.5)\n\n max_comp = comps[i-1]\n\n # Check R_Squared and RMSE\n if eval_type == None:\n break\n elif eval_type == 'R2':\n if R2 >= r2_min:\n break\n elif eval_type == 'RMSE':\n if RMSE <= rmse_min*ybar:\n break\n elif eval_type == 'Either':\n if R2 >= r2_min or RMSE <= rmse_min*ybar:\n break\n elif eval_type == 'Both':\n if R2 >= r2_min and RMSE <= rmse_min*ybar:\n break\n else:\n raise NameError('Invalid eval_type!')\n\n return p[0], p[1], max_comp, R2, RMSE, len(comps)-i\n\n\ndef calculate_kH_alt(comps, mass, error, r2_min=0.99, weight='error', flipped=False):\n\n # Make sure data is properly sorted\n indicies = np.argsort(comps)\n comps_sorted = [comps[i] for i in indicies]\n mass_sorted = [mass[i] for i in indicies]\n error_sorted = [error[i] for i in indicies]\n comps = comps_sorted\n mass = mass_sorted\n error = error_sorted\n\n if flipped == True:\n print('Flipped!')\n comps = np.flipud(comps)\n mass = np.flipud(mass)\n error = np.flipud(error)\n\n for i in range(len(comps),-1,-1):\n\n # Check if enough points for a proper fit\n if i <= 2:\n print('Could not fit to given data!')\n return None, 0, 0, 0\n\n # Linear Fit\n if weight == 'None':\n weights=np.ones(len(error[0:i]))\n elif weight == 'error':\n if 0 not in error[0:i]:\n weights=np.divide(1,error[0:i])\n else:\n weights_temp = [1/val for val in error[0:i] if val != 0]\n if len(weights_temp) != 0:\n weights = np.array([1/val if val != 0 else max(weights_temp) for val in error[0:i]])\n else:\n weights = np.ones(len(error[0:i]))\n elif weight == 'error_squared':\n error_squared = []\n for j in error[0:i]:\n error_squared.extend([j**2])\n if 0 not in error_sqaured:\n weights = np.divide(1,error_squared)\n else:\n weights_temp = [1/val for val in error_squared if val != 0]\n if len(weights_temp) != 0:\n weights = np.array([1/val if val != 0 else max(weights_temp) for val in error_squared])\n else:\n weights = np.ones(len(error_sqaured[0:i]))\n else:\n raise NameError('Invalid Error Type!')\n\n x = np.array(comps[0:i])\n x = np.vstack([x, np.ones(len(x))]).T\n y = np.array(mass[0:i])\n\n xw = x*np.sqrt(weights[:,np.newaxis])\n yw = y*np.sqrt(weights)\n a, b, c, d = np.linalg.lstsq(xw, yw, rcond=None)\n\n # Calculate R_Squared\n fit = np.poly1d(a)\n predicted_vals = fit(comps[0:i])\n residuals = predicted_vals-mass[0:i]\n ybar = np.sum(mass[0:i])/len(mass[0:i])\n ss_res = np.sum(residuals**2)\n ss_tot = np.sum((mass[0:i]-ybar)**2)\n R2 = 1-(ss_res/ss_tot)\n\n max_comp = comps[i-1]\n\n # Check R_Squared\n # print('i = '+str(i)+'\\t R^2 = '+str(R2))\n if R2 >= r2_min:\n # print('Number of Points Used: ', len(comps[0:i]))\n # print('R^2 = ', R2)\n # print('Henry Coeff. = ', p[0])\n # print('Intercept (should be 0) = ',p[1])\n max_comp = comps[i-1]\n break\n\n return a[0], a[1], R2, max_comp\n\n\ndef calculate_kH_fixed_intercept(comps, mass, error, eval_type='R2', r2_min=0.99, rmse_min=0.10, weight='error', counter=1):\n\n # Make sure data is properly sorted\n indicies = np.argsort(comps)\n comps_sorted = [comps[i] for i in indicies]\n mass_sorted = [mass[i] for i in indicies]\n error_sorted = [error[i] for i in indicies]\n comps = comps_sorted\n mass = mass_sorted\n error = error_sorted\n\n for i in range(len(comps),-counter,-1):\n\n # Check if out of points\n if i <= 2:\n print('Could not fit to given data!')\n return None, 0, 0, 0, 0\n\n # Linear Fit\n if weight == 'None':\n weights=np.ones(len(error[0:i]))\n elif weight == 'error':\n if 0 not in error[0:i]:\n weights=np.divide(1,error[0:i])\n else:\n weights_temp = [1/val for val in error[0:i] if val != 0]\n if len(weights_temp) != 0:\n weights = np.array([1/val if val != 0 else max(weights_temp) for val in error[0:i]])\n else:\n weights = np.ones(len(error[0:i]))\n elif weight == 'error_squared':\n error_squared = []\n for j in error[0:i]:\n error_squared.extend([j**2])\n if 0 not in error_sqaured:\n weights = np.divide(1,error_squared)\n else:\n weights_temp = [1/val for val in error_squared if val != 0]\n if len(weights_temp) != 0:\n weights = np.array([1/val if val != 0 else max(weights_temp) for val in error_squared])\n else:\n weights = np.ones(len(error_sqaured[0:i]))\n else:\n raise NameError('Invalid Error Type!')\n\n x = np.array(comps[0:i])\n x = x[:,np.newaxis]\n y = np.array(mass[0:i])\n\n xw = x*np.sqrt(weights[:,np.newaxis])\n yw = y*np.sqrt(weights)\n a, b, c, d = np.linalg.lstsq(xw, yw, rcond=None)\n\n # Calculate R_Squared\n fit = np.poly1d([a[0], 0])\n predicted_vals = fit(comps[0:i])\n residuals = predicted_vals-mass[0:i]\n ybar = np.sum(mass[0:i])/len(mass[0:i])\n ss_res = np.sum(residuals**2)\n ss_tot = np.sum((mass[0:i]-ybar)**2)\n R2 = 1-(ss_res/ss_tot)\n MSE = ss_res/len(mass[0:i])\n RMSE = MSE**(0.5)\n\n max_comp = comps[i-1]\n\n # Check R_Squared and RMSE\n if eval_type == 'R2':\n if R2 >= r2_min:\n break\n elif eval_type == 'RMSE':\n if RMSE <= rmse_min*ybar:\n break\n elif eval_type == 'Either':\n if R2 >= r2_min or RMSE <= rmse_min*ybar:\n break\n elif eval_type == 'Both':\n if R2 >= r2_min and RMSE <= rmse_min*ybar:\n break\n else:\n raise NameError('Invalid eval_type!')\n\n return a[0], max_comp, R2, RMSE, len(comps)-i\n\n\ndef analyze_single_ratio(gas, air_ratio, sim_results_path, analysis_results_path, force_intercept_hg=True, weight='error', r2_min=0.99):\n \"\"\"\n Acutally Calculating Henry's Coefficients with Error\n Each air ratio analyzed/plotted separately\n \"\"\"\n\n kH_results = []\n for file in list(glob.glob(sim_results_path+'*/*.csv')):\n # Prepare Dict\n temp_dict = {}\n temp_dict['Gas'] = gas\n temp_dict['Background'] = air_ratio\n\n # Load Results / Extract MOF Name\n keys, dict_data = import_simulated_data(file, gas)\n mof_name = dict_data[0]['MOF']\n temp_dict['MOF'] = mof_name\n\n # Isolate Data for Fitting\n comps = [float(row[gas+'_comp']) for row in dict_data]\n mass = [float(row[gas+'_mass']) for row in dict_data]\n error = [float(row[gas+'_error']) for row in dict_data]\n total_mass = [float(row['total_mass']) for row in dict_data]\n total_error = [float(row['total_mass_error']) for row in dict_data]\n\n # Calculate kH (uncomment desired method)\n figname = analysis_results_path+mof_name+'_kH.png'\n if force_intercept_hg == True:\n kH, R2, max_comp = calculate_kH_fixed_intercept(comps, mass, error, r2_min=r2_min, weight=weight, figname=figname, gas_name=gas, mof_name=mof_name)\n elif force_intercept_hg == False:\n kH, intercept, R2, max_comp = calculate_kH(comps, mass, error, r2_min=r2_min, weight=weight, figname=figname, gas_name=gas, mof_name=mof_name)\n else:\n print('Invalid Intercept Option!')\n\n\n temp_dict['k_H'] = kH[0]\n temp_dict['R^2'] = R2\n temp_dict['Maximum Composition'] = max_comp\n kH_results.extend([temp_dict])\n\n filename = '/Users/brian_day/Desktop/HC_Work/HenrysConstants_Analysis_Results/'+folder+'_henrys_coefficients.csv'\n with open(filename, 'w', newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter='\\t', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n for row in kH_results:\n writer.writerow([row])\n\n\ndef analyze_all_ratios(gas, sim_results_path, analysis_results_path, force_intercept_hg=True, weight='error', hg_eval_type='R2', air_eval_type='Either', r2_min_hg=0.99, r2_min_air=0.99, rmse_min_hg=0.10, rmse_min_air=0.10, consolidate_data=False):\n \"\"\"\n Acutally Calculating Henry's Coefficients with Error\n All Air Ratios Combined into Single Data Set\n \"\"\"\n\n all_files = list(glob.glob(sim_results_path+str(gas)+'*/*/*.csv'))\n # all_files = list(glob.glob(sim_results_path+'*/*.csv'))\n all_files.sort()\n\n kH_results_hg = []\n kH_results_air = []\n for file in all_files[0:50]:\n # Establish counter to use when eliminating datapoints\n counter = 1\n\n # Extract Filename\n filename = file.split('/')[-1]\n\n # Prepare Dict\n temp_dict_hg = {}\n temp_dict_air = {}\n temp_dict_hg['Gas'] = gas\n temp_dict_air['Gas'] = gas\n\n # Load Results / Extract MOF Name\n keys, dict_data = import_simulated_data(file, gas)\n mof_name = dict_data[0]['MOF']\n temp_dict_hg['MOF'] = mof_name\n temp_dict_air['MOF'] = mof_name\n\n # Isolate Data for Fitting\n # Henry's Gas\n comps = [float(row[gas+'_comp']) for row in dict_data]\n mass = [float(row[gas+'_mass']) for row in dict_data]\n error = [float(row[gas+'_error']) for row in dict_data]\n # Nitrogen\n comps_N2 = [float(row['N2_comp']) for row in dict_data]\n mass_N2 = [float(row['N2_mass']) for row in dict_data]\n error_N2 = [float(row['N2_error']) for row in dict_data]\n # Oxygen\n comps_O2 = [float(row['O2_comp']) for row in dict_data]\n mass_O2 = [float(row['O2_mass']) for row in dict_data]\n error_O2 = [float(row['O2_error']) for row in dict_data]\n # Air: Nitrogen + Oxygen\n comps_air = [sum(x) for x in zip(comps_N2, comps_O2)]\n mass_air = [sum(x) for x in zip(mass_N2, mass_O2)]\n error_air = [sum(x) for x in zip(error_N2, error_O2)]\n # Total Mass\n total_mass = [float(row['total_mass']) for row in dict_data]\n total_error = [float(row['total_mass_error']) for row in dict_data]\n\n for file2 in all_files[50::]:\n\n # Check if same MOF\n filename2 = file2.split('/')[-1]\n if filename2 == filename:\n # Update counter\n counter += 1\n\n # Load Results\n keys, dict_data = import_simulated_data(file2, gas)\n\n # Isolate Data for Fitting\n comps_temp = [float(row[gas+'_comp']) for row in dict_data]\n mass_temp = [float(row[gas+'_mass']) for row in dict_data]\n error_temp = [float(row[gas+'_error']) for row in dict_data]\n # Nitrogen\n comps_N2_temp = [float(row['N2_comp']) for row in dict_data]\n mass_N2_temp = [float(row['N2_mass']) for row in dict_data]\n error_N2_temp = [float(row['N2_error']) for row in dict_data]\n # Oxygen\n comps_O2_temp = [float(row['O2_comp']) for row in dict_data]\n mass_O2_temp = [float(row['O2_mass']) for row in dict_data]\n error_O2_temp = [float(row['O2_error']) for row in dict_data]\n # Air: Nitrogen + Oxygen\n comps_air_temp = [sum(x) for x in zip(comps_N2_temp, comps_O2_temp)]\n mass_air_temp = [sum(x) for x in zip(mass_N2_temp, mass_O2_temp)]\n error_air_temp = [sum(x) for x in zip(error_N2_temp, error_O2_temp)]\n # Total Mass\n total_mass_temp = [float(row['total_mass']) for row in dict_data]\n total_error_temp = [float(row['total_mass_error']) for row in dict_data]\n\n # Add Data to Original Data Set\n # Henry's Gas\n comps.extend(comps_temp)\n mass.extend(mass_temp)\n error.extend(error_temp)\n # Nitrogen\n comps_N2.extend(comps_N2_temp)\n mass_N2.extend(mass_N2_temp)\n error_N2.extend(error_N2_temp)\n # Oxygen\n comps_O2.extend(comps_O2_temp)\n mass_O2.extend(mass_O2_temp)\n error_O2.extend(error_O2_temp)\n # Air: Nitrogen + Oxygen\n comps_air.extend(comps_air_temp)\n mass_air.extend(mass_air_temp)\n error_air.extend(error_air_temp)\n # Total Mass\n total_mass.extend(total_mass_temp)\n total_error.extend(total_error_temp)\n\n # Write Raw Air Data (sorted) to a new file for inspection\n if consolidate_data == True:\n indicies = np.argsort(comps)\n comps_sorted = [comps_air[i] for i in indicies]\n mass_sorted = [mass_air[i] for i in indicies]\n error_sorted = [error_air[i] for i in indicies]\n all_data = np.vstack([comps_sorted, mass_sorted, error_sorted]).T\n header = ['Comps', 'Mass', 'Error']\n\n filepath = analysis_results_path+'rawdata/'\n filename = filepath+mof_name+'_airdata.csv'\n\n if os.path.isdir(filepath) != True:\n os.mkdir(filepath)\n\n with open(filename, 'w', newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter='\\t', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n # writer.writerows([comps_sorted])\n # writer.writerows([mass_sorted])\n # writer.writerows([error_sorted])\n writer.writerow(header)\n for row in all_data:\n writer.writerow(row)\n\n # Plot Adsorption Data\n figname = analysis_results_path+mof_name+'_ads_data.png'\n all_comps = [comps, comps, comps]\n all_masses = [mass, mass_air, total_mass]\n all_errors = [error, error_air, total_error]\n gases = [gas, 'Air', 'Total']\n plot_adsorbed_masses(all_comps, all_masses, all_errors, gases, figname=figname, gas_name=gas, mof_name=mof_name)\n\n # Calculate kH - Henry's Gas\n if force_intercept_hg == True:\n kH, max_comp, R2, RMSE, i_offset = calculate_kH_fixed_intercept(comps, mass, error, eval_type=hg_eval_type, r2_min=r2_min_hg, rmse_min=rmse_min_hg, weight=weight, counter=counter)\n intercept = 0\n elif force_intercept_hg == False:\n kH, intercept, max_comp, R2, RMSE, i_offset = calculate_kH(comps, mass, error, eval_type=hg_eval_type, r2_min=r2_min_hg, rmse_min=rmse_min_hg, weight=weight, counter=counter)\n else:\n print('Invalid Intercept Option!')\n\n if kH != None:\n figname = analysis_results_path+mof_name+'_kH.png'\n plot_kH_single_gas(comps, mass, error, max_comp, float(kH), intercept, R2, figname=figname, gas_name=gas, mof_name=mof_name)\n\n temp_dict_hg['k_H'] = kH\n # temp_dict_hg['Intercept'] = intercept\n temp_dict_hg['R^2'] = R2\n temp_dict_hg['RMSE'] = RMSE\n temp_dict_hg['Maximum Composition'] = max_comp\n kH_results_hg.extend([temp_dict_hg])\n\n # Calculate kH - Air Mixture\n if air_eval_type == 'With hg':\n if kH != None:\n kH, intercept, max_comp, R2, RMSE, _ = calculate_kH(comps_air, mass_air, error_air, eval_type=None, r2_min=r2_min_air, rmse_min=rmse_min_air, weight=weight, flipped=True, i_offset=i_offset, counter=counter)\n else:\n kH, intercept, max_comp, R2, RMSE, _ = (None, 0, 0, 0, 0, 0)\n else:\n kH, intercept, max_comp, R2, RMSE, _ = calculate_kH(comps_air, mass_air, error_air, eval_type=air_eval_type, r2_min=r2_min_air, rmse_min=rmse_min_air, weight=weight, flipped=True, counter=counter)\n\n if kH != None:\n # figname = analysis_results_path+mof_name+'_kH_air.png'\n # plot_kH_air(comps_air, mass_air, error_air, max_comp, float(kH), intercept, R2, figname=figname, gas_name=gas, mof_name=mof_name)\n figname = analysis_results_path+mof_name+'_kH_air_on_henry.png'\n plot_kH_single_gas(comps, mass_air, error_air, max_comp, -float(kH), intercept+kH, R2, figname=figname, gas_name=gas, mof_name=mof_name)\n\n temp_dict_air['k_H'] = kH\n if kH != None:\n temp_dict_air['Pure Air Mass'] = kH+intercept\n else:\n temp_dict_air['Pure Air Mass'] = None\n temp_dict_air['R^2'] = R2\n temp_dict_air['RMSE'] = RMSE\n temp_dict_air['Maximum Composition'] = max_comp\n kH_results_air.extend([temp_dict_air])\n\n # Write Henry's Gas csv\n filename = '/Users/brian_day/Desktop/HC_Work/HenrysConstants_Analysis_Results/'+str(gas)+'_AllRatios/_henrys_coefficients_hg.csv'\n with open(filename, 'w', newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter='\\t', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n for row in kH_results_hg:\n writer.writerow([row])\n\n # Write Air csv\n filename = '/Users/brian_day/Desktop/HC_Work/HenrysConstants_Analysis_Results/'+str(gas)+'_AllRatios/_henrys_coefficients_air.csv'\n with open(filename, 'w', newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter='\\t', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n for row in kH_results_air:\n writer.writerow([row])\n\n\ndef read_kH_results(filename):\n with open(filename, newline='') as csvfile:\n output_data = csv.reader(csvfile, delimiter=\"\\t\")\n output_data = list(output_data)\n full_array = []\n for i in range(len(output_data)):\n row = output_data[i][0]\n row = row.replace('nan', '\\'nan\\'')\n row = row.replace('inf', '\\'inf\\'')\n row = row.replace('-\\'inf\\'', '\\'-inf\\'')\n temp_array = []\n temp_row = ast.literal_eval(row)\n # if type(temp_row['R^2']) == str or temp_row['R^2'] < 0:\n # continue\n temp_array.append(temp_row)\n full_array.extend(temp_array)\n return full_array\n\n\ndef plot_all_kH(gas, data, figname):\n colors = mpl.cm.get_cmap('RdBu')\n color0 = colors(0.80)\n color1 = colors(0.20)\n\n comps = []\n khs = []\n for row in data:\n comps.extend([row['Maximum Composition']])\n khs.extend([row['k_H']])\n\n if gas != 'None':\n if gas == 'CO2':\n gas_for_title = '$CO_2$'\n else:\n gas_for_title = '$' + gas[0].upper() + gas[1::] +'$'\n\n plt.clf()\n plt.figure(figsize=(4.5,4.5), dpi=600)\n plt.semilogy(comps,khs,'o', alpha=0.7, color=color0)\n plt.ylim([1e-2,1e8])\n plt.xlim([-0.001,0.051])\n plt.title(gas_for_title+' in Air', fontsize=16)\n plt.xlabel('Maximum Mole Fraction\\n(End of Henry\\'s Regime)', fontsize=16)\n plt.ylabel('Henry\\'s Coefficient\\n[mg/g/mole fraction]',fontsize=16)\n plt.xticks(fontsize=12)\n plt.yticks(fontsize=12)\n plt.tight_layout()\n plt.savefig(figname)\n plt.close()\n","sub_path":"sensor_array/helper/henrys_coefficient_analysis.py","file_name":"henrys_coefficient_analysis.py","file_ext":"py","file_size_in_byte":27576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"506718974","text":"import time\nimport sys\nfrom urllib.request import urlretrieve\nfrom urllib.error import URLError, HTTPError\n\ndef progress(downloaded, block_size, total_size):\n global download_size\n download_size = total_size\n completed = int(downloaded / (total_size//block_size) * 100)\n sys.stdout.write(f\"\\r|{'█' * completed}{' ' * (100-completed)}{completed}%\")\n\ndef download_bar(url,filename):\n start = time.time()\n try:\n urlretrieve(url,filename,progress)\n except URLError:\n sys.stderr.write(\"The URL is invalid.\\n\")\n exit(0)\n except HTTPError as e:\n sys.stderr.write(f\"Error: {e.code} {e.reason}\\n\")\n exit(0)\n except Exception as e:\n sys.stderr.write(\"An error occured\\n\")\n sys.stderr.write(type(e),e)\n exit(0)\n end = time.time()\n sys.stdout.write(\"\\n\")\n time_taken = end - start\n download_speed = round(download_size/(time_taken*1024),2)\n if download_speed >= 1024:\n sys.stdout.write(f\"Downloaded in {(round(time_taken, 2))} s ({download_speed/1024} MB/s)\\n\")\n if download_speed < 1024:\n sys.stdout.write(f\"Downloaded in {(round(time_taken, 2))} s ({download_speed} kB/s)\\n\")\n if download_speed < 1:\n sys.stdout.write(f\"Downloaded in {(round(time_taken, 2))} s ({download_speed*1024} B/s)\\n\")\n","sub_path":"progress.py","file_name":"progress.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"560933367","text":"import os\nimport neat\nimport numpy as np\nimport pandas as pd\n\nn_test = 20\nLOCAL_PATH = os.path.dirname(__file__)\nDATA_PATH = os.path.join(LOCAL_PATH,\"data.csv\")\n\n# read data from csv file\ndata = pd.read_csv(DATA_PATH)\ndata = data.drop(columns=[data.columns[-1]])\nwidht,height = data.shape\nndata = widht\ndims = int(height/2)\n\n# split data in input and output\ninput_columns = data.columns[:dims]\noutput_columns = data.columns[dims:]\n\nX = data[input_columns]\ny = data[output_columns]\n\n# split in train and test data\nX_train = X.head(ndata-n_test).values\ny_train = y.head(ndata-n_test).values\n\nX_test = X.tail(n_test).values\ny_test = y.tail(n_test).values\n\n# neat configuration\nconfig_file = os.path.join(LOCAL_PATH, 'config-feedforward.txt')\nconfig = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,\n neat.DefaultSpeciesSet, neat.DefaultStagnation,\n config_file)\n\n# create the population\np = neat.Population(config)\n\n# reporters\np.add_reporter(neat.StdOutReporter(True))\nstats = neat.StatisticsReporter()\np.add_reporter(stats)\n\ndef error_measure(outp,expt):\n if outp.shape != expt.shape:\n print(\"Dimensions don't match: \",outp.shape,expt.shape)\n exit()\n else:\n dist = outp - expt\n err = np.dot(dist,dist.T)\n \n return err\n\ndef fitness_function(genomes, config):\n\n len_data,dims = X_train.shape\n\n for genome_id, genome in genomes:\n # create nn\n net = neat.nn.FeedForwardNetwork.create(genome,config)\n genome.fitness = dims*len_data\n \n for d in range(len_data):\n output = np.array(net.activate(tuple(X_train[d])))\n genome.fitness -= error_measure(output,y_train[d])\n\nwinner = p.run(fitness_function, 25)\nprint('\\nBest genome:\\n{!s}'.format(winner))\n\nwinner_net = neat.nn.FeedForwardNetwork.create(winner,config)\n\nfor d in range(n_test):\n output = np.array(winner_net.activate(tuple(X_test[d])))\n score = dims - error_measure(output,y_test[d])\n print(\"input: \",X_test[d])\n print(\"expected output: \",y_test[d])\n print(\"output: \", [round(i,2) for i in output])\n print(\"score: \",round(score,2))\n print()\n\n","sub_path":"neat-python/NEAT-NoGate/neat_model.py","file_name":"neat_model.py","file_ext":"py","file_size_in_byte":2226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"128211296","text":"import numpy as np \nimport configparser\n\nimport gym \nfrom gym import wrappers, logger, spaces\nfrom stable_baselines.common.policies import MlpPolicy\nfrom stable_baselines.common import make_vec_env\nfrom stable_baselines import PPO2\n\n# Custom flight controller environment\nfrom gymfc.envs.fc_env import FlightControlEnv\n\n# Gazebo model config file\nAIRCRAFT_CONFIG = \"/data/gymfc-digitaltwin-solo/models/nf1/model.sdf\"\n\n# This is where you set the reward parameters\n# Check compute_reward() for more details\nREWARD_CONFIG = \"gymfc/reward_params.config\"\n\n\n## Attitude Flight Controller Environment ##\n# This environment is for training a drone to maintain a desired \n# angular velocity by directly controlling the 4 motor values. By \n# teaching the drone to reach desired angular velocities, a pilot \n# can then fly the drone in \"Acro\" mode (direct control over roll pitch yaw\n# angular velocities). \n#\n# Inherits from a base Gym environment.\nclass AttitudeFlightControlEnv(FlightControlEnv, gym.Env):\n def __init__(self, max_sim_time=4.5):\n\n # Initialize the base GymFC environment and Gym env\n super(AttitudeFlightControlEnv, self).__init__(aircraft_config=AIRCRAFT_CONFIG)\n\n # Total episode time\n self.max_sim_time = max_sim_time\n\n # Define the action space\n # This is currently defined for DShot ESCs that can receive a \n # continous range of motor signals between 0 and 1\n # The dimension of the action space is dependent on the motor count\n action_space_low = np.array([0] * self.motor_count)\n action_space_high = np.array([1] * self.motor_count)\n self.action_space = spaces.Box(low=action_space_low,\n high=action_space_high, \n dtype=np.float64)\n\n # Define the observation space\n # The observation space is a continuous range between -infinity and +infinity.\n self.observation_space = spaces.Box(low=np.array([-np.inf] * 6),\n high=np.array([np.inf] * 6),\n dtype=np.float64)\n\n # The observation and state will be initially set when reset() is called.\n # The state is a flattened array with sensor measurements in the same order\n # as defined in the model.sdf file. \n self.state = None\n\n # The observation is the angular velocity error and the change in angular velocity error\n # since the last time step\n #\n # error = omega_target - omega_actual\n # delta_error = error - error_prev\n self.observation = None\n\n # The current angular velocity of the UAV (roll, pitch, yaw) in rad/s.\n # This will be used to calculate the observation\n self.omega_actual = None\n\n # The desired angular velocity of the flight controller\n self.omega_target = [0, 0, 0]\n\n # Load reward parameters\n cfg = configparser.ConfigParser()\n cfg.read(REWARD_CONFIG)\n params = cfg[\"PARAMETERS\"]\n\n self.beta = int(params[\"Beta\"]) # Scaling factor for penalizing large changes in control signals\n self.epsilon = float(params[\"Epsilon\"]) # Scaling factor for the desired error gap around omega_target\n self.alpha = int(params[\"Alpha\"]) # Scaling factor for rewarding smaller control signal values\n self.max_penalty = int(params[\"Max_penalty\"]) # To heavily penalize for certain actions and make sure they never happen again\n\n # Debug stuff\n self.episode_count = 0\n self.episode_reward = 0\n self.hit_max_1 = 0\n self.hit_max_2 = 0\n self.max_penalty_count_2 = 0\n self.hit_max_3 = 0\n self.max_penalty_count_3 = 0\n\n # Action: Output from the neural net. \n # The current RL algorithm implementation is from stable_baselines(https://github.com/hill-a/stable-baselines),\n # Which clips and scales the NN output to the action space defined in environment.\n # Therefore, the action can be directly passed to the environment simulation, assuming that\n # the action space has been defined to mirror the expected range of motor control signals (DShot: 0 to 1).\n def step(self, action):\n\n # transform_output() goes here for PPO1 (Will Koch's implementation)\n # action is Gaussian between -1 and 1, clip to [-1,1] and then scale to [0, 1]\n\n # Perform a step in the simulation and receive an updated observation\n self.state = self.step_sim(action)\n self.omega_actual = self.state[0:3]\n\n # Compute the reward for the current time step\n self.reward = self.compute_reward(action)\n\n self.episode_reward += self.reward\n\n self.generate_command()\n\n # Update the observation that is fed into the neural net\n self.update_observation()\n\n # Check if the simulation has completed\n self.dones = self.sim_time >= self.max_sim_time\n \n # Record some info on the simulation step\n self.info = {\"sim_time\": self.sim_time, \"sp\": self.omega_target, \"current_rpy\": self.omega_actual}\n\n self.prev_action = action \n\n return self.observation, self.reward, self.dones, self.info\n \n\n # Reset the environment.\n # Obtains the initial state and calculates the initial observation.\n # Generates the target angular velocity command (omega_target)\n def reset(self):\n\n self.error = 0 # Error between desired omega and actual omega\n self.error_prev = 0 # Omega error at last time step\n self.delta_error = 0 # Change in error since last time step\n self.pulse_command = False # True if pulsing a desired angular velocity \n self.prev_action = 0 # Store the previous agent action\n\n # Get the initial state\n self.state = super().reset()\n self.omega_actual = self.state[0:3]\n\n # Reset reward counts\n self.reward = 0 # Episodic reward\n self.error_reward = 0\n self.signal_flux_reward = 0\n self.small_signal_reward = 0\n self.saturated_output_count = 0\n self.saturated_max_penalty = 0\n self.inactive_output_count = 0\n self.inactive_max_penalty = 0\n\n # Generate a target angular velocity command\n self.generate_command()\n\n # Calculate the initial observation\n self.update_observation()\n\n return self.observation\n \n\n # Update the observation based on the new state.\n def update_observation(self):\n \n # Calculate the error between the desired angular velocity and the current angular velocity\n self.error = self.omega_target - self.omega_actual\n\n # Calculate the change in error since the last time step\n self.delta_error = self.error - self.error_prev\n\n # Update the previous error as the simulation steps forward\n self.error_prev = self.error\n\n # The observation is an array of the error and the change in error\n self.observation = np.array([self.error, self.delta_error]).flatten()\n\n # Generate a desired angular velocity command \n # This is used to calculate the angular velocity error which is sent to the agent.\n def generate_command(self):\n \n # The first 0.5 seconds are set to 0 so agent can learn its idle/hover state\n # With a 1ms sim step, this is equivalent to 500 iterations\n if self.sim_time < 0.5:\n self.omega_target = np.array([0, 0, 0])\n\n # Pulse ON for 2 seconds to teach maintaining a set angular velocity\n elif self.sim_time < 2.5 and not self.pulse_command:\n self.omega_target = self.sample_target_command(mean=np.array([0, 0, 0]), stdev=100)\n self.pulse_command = True\n\n # Keep set angular velocity for duration of pulse\n elif self.sim_time < 2.5:\n pass\n\n # Pulse OFF for 2 seconds to teach deceleration back to idle/hover\n else:\n self.omega_target = np.array([0, 0, 0])\n\n \n # Sample a target command from a normal distribution.\n # The distribution has a mean of 0 deg/s and a standard deviation of\n # 100 deg/s so that aggressive maneuvers are included in the training.\n def sample_target_command(self, mean, stdev):\n return np.random.normal(loc=mean, scale=stdev)\n \n\n # Calculate the reward function.\n def compute_reward(self, action):\n\n reward = 0 # Store the cumulative reward per step\n\n # Calculate the updated error \n error = self.omega_target - self.omega_actual\n \n # Sum of squared error for the current and previous time step\n sum_squared_error = np.sum(np.square(error))\n sum_squared_error_prev = np.sum(np.square(self.error_prev))\n reward += -(sum_squared_error - sum_squared_error_prev)\n self.error_reward += -(sum_squared_error - sum_squared_error_prev)\n\n # Penalize for large control signal fluctuations\n reward -= self.beta * np.max(np.abs(action - self.prev_action))\n self.signal_flux_reward -= self.beta * np.max(np.abs(action - self.prev_action))\n\n # Reward smaller control signal values\n # Only apply this reward if the agent is already able to achieve an error\n # within the specified error band gap. This gap can be scaled with epsilon.\n if np.all(np.abs(error) < self.epsilon * np.abs(self.omega_target)):\n reward += self.alpha * (1 - np.mean(action))\n self.small_signal_reward += self.alpha * (1 - np.mean(action))\n\n ## Right now, the next two don't do anything\n # PPO2 output is already clipped, so it can never be oversaturated\n\n # Penalize for oversaturating any element in the control signal\n # NOTE: This has been modified from the original work to penalize any action being equal to 1.\n # May not be a good reward.\n # if np.sum(np.maximum(action - 1, np.zeros(shape=action.shape))) != 0:\n # reward -= self.max_penalty * np.sum(np.maximum(action - 1, np.zeros(shape=action.shape)))\n # self.hit_max_1 += 1\n \n # if np.sum(np.maximum(action - 1, np.zeros(shape=action.shape))) != 0:\n # reward -= self.max_penalty * np.sum(np.maximum(action - 1, np.zeros(shape=action.shape)))\n # self.hit_max_1 += 1\n\n # Penalize if all control signals have been saturated\n if np.all(action >= 1):\n self.saturated_max_penalty -= self.max_penalty\n reward -= self.max_penalty\n self.saturated_output_count += 1\n\n \n # Penalize if agent does nothing (action = 0) and there is an omega_target other than 0. \n if np.count_nonzero(action) < 2 and np.any(self.omega_target):\n self.inactive_max_penalty -= self.max_penalty\n reward -= self.max_penalty\n self.inactive_output_count += 1\n \n\n return reward\n","sub_path":"gymfc/envs/gym_env.py","file_name":"gym_env.py","file_ext":"py","file_size_in_byte":10966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"634756962","text":"import os\nimport sys\nimport getopt\nimport operations\nimport shutil\nfrom db import *\nimport ig_template\nimport os\nimport subprocess\nimport string\n\nclass operation(operations.operation):\n \"Build a navigation dataset\"\n def __init__(self):\n operations.operation.__init__(self,\"generate_navigate\",False)\n self.add_argument(\"help\",None,None,\"show help message\")\n self.add_argument(\"root\",\"str\",None,\"root path\")\n self.add_argument(\"template\",\"str\",None,\"template name\")\n self.add_argument(\"size\",\"int\",10000,\"verbose level\")\n self.add_argument(\"source\",\"str\",\".\",\"source path\")\n self.add_argument(\"target\",\"str\",\"query\",\"target path\")\n self.add_argument(\"vertex\",\"str\",None,\"vertex name\")\n self.add_argument(\"dist\",\"str\",\"uniform\",\"query distribution: uniform , gauss,mu,sigma\")\n self.add_argument(\"verbose\",\"int\",0,\"verbose level\")\n self.add_argument(\"dfs\",None,None,\"Use Depth first search\")\n self.add_argument(\"depth\",\"int\",\"5\",\"Navigation Depth\")\n self.add_argument(\"results\",\"int\",\"100\",\"Max number of results.\")\n pass\n\n def __run__(self,template,source,target,size,verbose,dist,vertex):\n ig_template.Data.Options.source = source\n ig_template.Data.Options.target_file = target\n parser = ig_template.Schema.Parser(template,None)\n if dist == \"uniform\":\n parser.setUniformDistribution()\n elif dist == \"gauss\":\n if len(dist) != 3:\n self.error(\"When using gauss distribution, you must specify gauss,mu,sigma\")\n return False\n if (float(dist[1]) < 0) or (float(dist[1]) > 1) or (float(dist[2]) < 0) or (float(dist[2]) > 1):\n self.error(\"When using gauss distribution, values of mu,sigma must be between 0 and 1.\")\n return False\n parser.setGaussDistribution(float(dist[1]),float(dist[2]))\n pass\n parser.setVerboseLevel(verbose)\n parser.generateQuery(vertex,size)\n ig_template.Data.Options.CloseAllFiles()\n return True\n \n def operate(self):\n if operations.operation.operate(self):\n rootPath = self.getSingleOption(\"root\")\n template = self.getSingleOption(\"template\")\n size = self.getSingleOption(\"size\")\n source = self.getSingleOption(\"source\")\n target = self.getSingleOption(\"target\")\n dist = self.getSingleOption(\"dist\")\n vertex = self.getOption(\"vertex\")\n if rootPath == None:\n self.error(\"Root path is not given.\")\n return False\n if template == None:\n self.error(\"Template is not given.\")\n return False\n if not template.endswith(\".xml\"):\n template = template + \".xml\"\n pass\n if (not vertex) or len(vertex) == 0:\n self.error(\"Vertex is not given.\")\n return False\n template = os.path.join(rootPath,\"templates\",template)\n if not os.path.exists(template):\n self.error(\"Unable to find template file {0}.\".format(template))\n return False\n return self.__run__(template,source,target,size,self.verbose,dist,vertex)\n return True\n","sub_path":"src/generate_navigation_operation.py","file_name":"generate_navigation_operation.py","file_ext":"py","file_size_in_byte":3327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"604008028","text":"import ujson\nfrom app.crawler.utils.ext.country import isoCountries\nfrom app.crawler.world.csse import CSSEApi\n\n\nasync def globalStatus(cache, loop):\n if not await cache.exists('global'):\n ads = CSSEApi()\n data = await ads.apiProcess()\n global_ = {\n \"global\": data\n }\n _global = await loop.run_in_threadpool(\n lambda: ujson.dumps(global_, ensure_ascii=False, escape_forward_slashes=False, sort_keys=True).encode('utf-8'))\n await cache.set('global', _global, expire=3600)\n return global_[\"global\"]\n else:\n global_ = await cache.get('global')\n _global = await loop.run_in_threadpool(lambda: ujson.loads(global_))\n return _global[\"global\"]\n\n\nasync def CountryCodeConverter(source):\n for index in isoCountries:\n if index[\"ccode\"].lower() == source.lower():\n return index[\"cname\"].lower()\n\n\nasync def CountrySelect(country: str):\n data = CSSEApi()\n source = await data.apiProcess()\n for index in source:\n if index['country'].lower() == await CountryCodeConverter(source=country):\n return index\n\n\nasync def GlobalCoronaSearch(cache, loop, country):\n if not await cache.exists(country.lower()):\n data = await CountrySelect(country=country)\n jsonObject = {\n country.lower(): data\n }\n _result = await loop.run_in_threadpool(lambda: ujson.dumps(jsonObject, ensure_ascii=False, escape_forward_slashes=False, sort_keys=True).encode('utf-8'))\n await cache.set(country.lower(), _result, expire=3600)\n return jsonObject[country.lower()]\n else:\n result_ = await cache.get(country.lower())\n _result = await loop.run_in_threadpool(lambda: ujson.loads(result_))\n return _result[country.lower()]\n\n\n\n","sub_path":"app/ext/route/world/globalStatus.py","file_name":"globalStatus.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"341471324","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on \n\n@author: Bottini Gianfausto @Pi school\n\"\"\"\n\nimport pandas as pd\nimport gensim\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.decomposition import PCA\nimport glob\nfrom gensim import models\nimport string\nimport numpy as np\nimport json\nfrom stop_words import get_stop_words\nimport re\nfrom sklearn import preprocessing\nfrom sklearn.cluster import DBSCAN\nfrom scipy.stats import mode\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nimport plotly\n#plotly.tools.set_credentials_file(username='faffids', api_key='fk1d3sbNzj81AECxuWlO')\nimport math\nimport plotly.offline as offline\noffline.init_notebook_mode(connected=True)\nfrom gensim.models import translation_matrix\nfrom gensim.models import KeyedVectors\n\n\npd.set_option('display.max_colwidth', 100)\n#matrix is the vector space created during the previous script\n#\"matrix_user_vector_facounnier_200\" is the name of the csv file loaded into pandas dataframe\nmatrix = pd.read_csv('i18n_matrix_user_vector.csv',sep='\\t',index_col=0)\n#it is the word2vec dictionary , the .bin file can be downloaded (as for the following file) or trained with gensim\nfile_where_dictionary_is_stored = \"/home/ubuntu/mynotebooks/fr_w2v_keyed_senzaht\"\n#french dictionary as KeyedVectors (check gensim library)\nfr_dictionary = KeyedVectors.load(file_where_dictionary_is_stored)\n#en_dictionary = KeyedVectors.load('/home/ubuntu/mynotebooks/en_w2v_keyed')\n#loaded_transm = translation_matrix.TranslationMatrix.load('/home/ubuntu/mynotebooks/translation_matrix_2')\n\ndimensions = len(fr_dictionary['ok'])\ndimensions_string_1 = str(dimensions-1)\n\n\n#function input: the matrix vector space of users \n#function output: the same matrix adding a last row , the marketing topic plus its vector\n\n\ndef addwords(matrix,word):\n newmatrix = matrix.copy()\n newmatrix.loc[word] = fr_dictionary[word]\n \n return newmatrix\n\n\n#function input: the marketing campaign topic in a single french word\n#function output: a column sorted by the similarity of users to that topic\n\ndef results(topic_fr):\n txt_analysis = addwords(matrix,topic_fr )\n txt_similarity = pd.DataFrame(cosine_similarity(txt_analysis) , columns= txt_analysis.index , index = txt_analysis.index)[topic_fr]\n return txt_similarity.sort_values(ascending=False).iloc[1:]\n\n\n\n#function input: 1 column dataframe with ids as index and topic closeness measure as unique feature\n#function output: a dataframe completed with number other kind of features taking back jsons informations (total likes , likes per day , followers)\n\n\ndef finaldataframe(df_similarity):\n likes = []\n followers = []\n delta = []\n for index, row in df_similarity.iterrows():\n \n index = str(index)\n #change path with respect to where user jsons are stored\n file = \"/home/ubuntu/mynotebooks/dati_utenti/dati_utenti/\"+index+\".json\"\n \n try:\n data = json.load(open(file))\n \n nfollowers = len(data[index][\"followers\"])\n followers.append(nfollowers)\n delta_max = data[index][\"items\"][\"0\"][1]\n delta_min = np.inf\n total_likes = 0\n for post in data[index][\"items\"]:\n nlikes = data[index][\"items\"][post][2]\n \n try:\n total_likes += nlikes\n except:\n total_likes += 0\n timestamp = data[index][\"items\"][post][1]\n \n try:\n if timestamp <= delta_min:\n delta_min = timestamp\n except:\n pass\n likes.append(total_likes)\n try: \n delta.append(delta_max-delta_min)\n except:\n delta.append(None)\n except:\n likes.append(None)\n followers.append(None)\n delta.append(None)\n\n \n df_similarity['likes'] = likes\n df_similarity['followers'] = followers\n df_similarity['delta'] = delta\n df_similarity['deltadays'] = df_similarity['delta']/86400.0\n df_similarity['likesperday'] = df_similarity['likes'] / df_similarity['deltadays']\n \n return df_similarity\n\n\n\n#function input: the previous dataframe having ids as index and closeness measure , likes , followers , likes per day as features and 4 kind of quantiles \n#q1 : topic closeness\n#q2 : likes\n#q3 : followers\n#q4 : likes per day\n#function output: skimming process , rows having a value less than the fixed quantile over the entire list are deleted , even if just one of the 4 feature does not pass the exam\n\n#obviously quantiles are not fixed\n\ndef select (df_,q1 , q2 , q3 ,q4):\n \n a_ = df_[['final_measure','likes','followers','likesperday']]\n lower_quantile1, upper_quantile1 = a_.final_measure.quantile([q1, .99])\n lower_quantile2, upper_quantile2 = a_.likes.quantile([q2, .99])\n lower_quantile3, upper_quantile3 = a_.followers.quantile([q3, .99])\n lower_quantile4, upper_quantile4 = a_.likesperday.quantile([q4, .99])\n\n a_ = a_.loc[(a_.final_measure > lower_quantile1)& (a_.likes > lower_quantile2) & (a_.followers > lower_quantile3) & (a_.likesperday > lower_quantile4)]\n \n return a_\n\n\n#function input: vector space matrix (it is needed to have the users 200 dimensions vectors) , the dataframe of selected users \n#function output: a dataframe with standard features plus the X and Y coming from the projection from 200 dimensions to 2\n\ndef pcaxy(dfpca,df_plot):\n pca = PCA(n_components=2)\n pca.fit(dfpca)\n PCA(copy=True, n_components=2, whiten=False)\n X = pd.DataFrame(pca.transform(dfpca) ,index = dfpca.index , columns = ['x','y'])\n users = df_plot.index\n pd.concat([df_plot,X.loc[users]], axis=1)\n \n\n return pd.concat([df_plot,X.loc[users]], axis=1)\n\n\n\n#function input: dataframe with features like : URL , topic closeness , lokes , followers , likes per day , x , y\n#function output: plotly interactive map\n\ndef finalplot(df_plot):\n\n hover_text = []\n bubble_size = []\n \n for index, row in df_plot.iterrows():\n\n hover_text.append(('instagram URL: {url}
'+\n 'instagram ID: {id}
'+\n 'final measure: {measure}
'+\n 'likes: {likes}
'+\n 'followers: {flw}
'+\n 'likesperday: {lpd}
').format(url = row['url'],\n id=index,\n measure=row['final_measure'],\n likes=row['likes'],\n flw=row['followers'],\n lpd=row['likesperday']\n ))\n bubble_size.append(math.sqrt(row['followers']*row['likes']*row['likesperday'])/10000)\n\n df_plot['text'] = hover_text\n df_plot['size'] = bubble_size\n\n data = go.Scatter(\n x = df_plot['x'],\n y = df_plot['y'],\n text = df_plot['text'],\n mode = 'markers',\n marker = {\n\n \"color\" : df_plot['final_measure'],\n \"size\" : df_plot['size'],\n \"showscale\" : True\n }\n\n\n\n )\n \n\n data = ([data])\n fig = go.Figure(data=data)\n\n \n offline.iplot(fig)\n return\n\n \ndef make_clickable(val):\n return '{}'.format(val,val)\n\n\n\n#function input: any dataframe having IDs as index\n#function output: a dataframe with users pictaram website (pictarame is instagram with ID instead of screennames)\ndef addurl(dataframe):\n dataframe['url'] = f'http://instagram.com/web/friendships/'+dataframe.index.astype(str) + '/follow/'\n return dataframe\n\n\nimport seaborn as sns\ncm = sns.light_palette(\"green\", as_cmap=True)\n\ndef beautifuldf(df):\n df = df.style.background_gradient(cmap=cm)\\\n .format({'url': make_clickable})\\\n .set_properties(**{'text-align': 'left'})\n return df\n\n#function input: marketing campaign topic in a single word\n#function output: final map plus final dataframe of candidates\n#you can increase or decrease quantiles with respect to the search purposes\ndef launch_campaign_about(word):\n M = addwords(matrix , word)\n \n df_similarity = pd.DataFrame(results(topic_fr=word))\n a = finaldataframe(df_similarity)\n a.columns.values[0] = 'final_measure'\n q = select(a , 0.9, 0.3 , 0.3 ,0.3 ).sort_values('final_measure' , ascending=False).head(100).round({'final_measure': 2, 'likesperday': 0})\n finalplot(addurl(pcaxy(M.loc[:, '1':dimensions_string_1],q)))\n return beautifuldf(addurl(q).head(10))","sub_path":"modules_for_demo_i18n.py","file_name":"modules_for_demo_i18n.py","file_ext":"py","file_size_in_byte":8738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"22411953","text":"from bitcasa import BitcasaClient, BitcasaFolder, BitcasaFile\nfrom bitcasa.exception import BitcasaException\nimport time, os, sys, traceback, threading\nimport utils\nfrom logger import logger as log\nfrom threads import RunThreaded\nfrom unidecode import unidecode\nfrom collections import deque\n\nclass FileDownload(object):\n def __init__(self, filename, filepath, filesize, fullpath, filedir):\n self.filename = filename\n self.filepath = filepath\n self.filesize = filesize\n self.fullpath = fullpath\n self.filedir = filedir\n self.thread = None\n\n def start(self, thread_num, parent):\n item = {\n \"filename\": self.filename,\n \"filepath\": self.filepath,\n \"filesize\": self.filesize,\n \"fullpath\": self.fullpath,\n \"filedir\": self.filedir\n }\n log.debug(\"Starting file download %s\", self.filename)\n thread = RunThreaded(item, thread_num, parent)\n thread.start()\n self.thread = thread\n\n def pause(self):\n thread.pause()\n\n def resume(self):\n thread.resume()\n\nclass DownloadThreaded(threading.Thread):\n def __init__(self, parent):\n threading.Thread.__init__(self, name=\"Downloader\")\n self.parent = parent\n\n def run(self):\n log.debug(\"Starting Downloader\")\n while not self.parent.done and not self.parent.end:\n if len(self.parent.todownload) > 0:\n next_thread = self.parent.getNextThread()\n while next_thread is None and not self.parent.end:\n log.debug(\"Downloader waiting for thread space. %s left to process\", len(self.parent.todownload))\n time.sleep(5)\n next_thread = self.parent.getNextThread()\n if not self.parent.end:\n download = self.parent.todownload.popleft()\n log.debug(\"Downloader processing %s\", download.filename)\n download.start(next_thread, self.parent)\n self.parent.threads[next_thread] = download\n else:\n log.debug(\"Got exit signal. Not creating any more threads\")\n break\n else:\n time.sleep(10)\n\n if self.parent.end:\n log.info(\"Stopping Downloader\")\n else:\n log.info(\"Downloader shutting down\")\n\nclass QueueThreaded(threading.Thread):\n def __init__(self, qid, parent):\n threading.Thread.__init__(self, name=\"Queuer \"+qid)\n self.parent = parent\n self.qid = qid\n\n def run(self):\n log.debug(\"Starting Queuer\")\n while not self.parent.done and not self.parent.end and self.parent.moreToQueue():\n if len(self.parent.folders_queue) and self.parent.folders_lock is None:\n self.parent.queuers[int(self.qid)-1][\"processing\"] = True\n self.parent.folder_lock = self.qid\n folder = self.parent.folders_queue.popleft()\n log.debug(\"Grabbing folder %s\", folder[\"folder\"].name)\n self.parent.folder_lock = None\n try:\n self.parent.folder_list(folder[\"folder\"], folder[\"path\"], folder[\"depth\"])\n except KeyboardInterrupt:\n log.warn(\"Received end signal\")\n self.parent.end = True\n break\n else:\n time.sleep(1)\n\n self.parent.queuers[int(self.qid)-1][\"processing\"] = False\n time.sleep(5)\n else:\n if len(self.parent.folders_queue) > 1:\n time.sleep(1)\n else:\n time.sleep(int(self.qid))\n\n if self.parent.end:\n self.parent.queuers[int(self.qid)-1][\"processing\"] = False\n log.info(\"Stopping Queuer\")\n elif self.parent.done:\n log.info(\"Queuer shutting down\")\n else:\n log.info(\"Queuer shutting down. All folders processed\")\n\n\nclass BitcasaDownload(object):\n def getNextThread(self):\n for thread_num in xrange(len(self.threads)):\n if self.threads[thread_num] is None:\n return thread_num\n return None\n def getActiveThreads(self):\n activeThreads = []\n for thread in self.threads:\n if thread and thread.thread:\n activeThreads.append(thread.thread)\n for queue_thread in self.queuers:\n if queue_thread[\"processing\"]:\n activeThreads.append(queue_thread[\"thread\"])\n return activeThreads\n\n def moreToQueue(self):\n if len(self.folders_queue) > 0:\n return True\n for queue_thread in self.queuers:\n if queue_thread[\"processing\"]:\n return True\n\n return False\n\n def folder_list(self, fold, path, depth):\n if self.end:\n log.debug(\"Received end signal. Stopping folder list\")\n return\n if path:\n log.info(path)\n fulldest = os.path.join(self.dest, path)\n remainingtries = 3\n #Create temp dir and dest dir if needed\n while remainingtries > 0:\n try:\n if fulldest:\n try:\n os.makedirs(fulldest)\n except (OSError, IOError):\n if not os.path.isdir(fulldest):\n raise\n except:\n remainingtries -= 1\n log.exception(\"Couldn't create folder %s\",fulldest)\n if remainingtries > 0:\n log.error(\"Will retry to create folder %s more times\", remainingtries)\n time.sleep(2)\n else:\n self.writeErrorDir(fold.name, fulldest, fold.path, traceback.format_exc())\n return\n else:\n remainingtries = 0\n\n log.debug(fulldest)\n remainingtries = 3\n apiratecount = 0\n while remainingtries > 0 and not self.end:\n if self.end:\n log.info(\"Program received exit signal\")\n return\n try:\n folderitems = fold.items\n except BitcasaException as e:\n if self.end:\n log.info(\"Program received exit signal\")\n return\n remainingtries -= 1\n if e.code in [9006, 503, 429]:\n apiratecount += 1\n remainingtries += 1\n log.warn(\"API rate limit reached. Will retry\")\n else:\n log.warn(\"Failed to get folder contents %s. Will retry %s more times\", e.code, remainingtries)\n\n if remainingtries > 0:\n try:\n time.sleep(10 * apiratecount)\n except KeyboardInterrupt:\n self.end = True\n log.info(\"Program received exit signal\")\n return\n else:\n log.error(\"Error downloading at folder %s\", path)\n return\n except KeyboardInterrupt:\n self.end = True\n log.info(\"Program received exit signal\")\n return\n else:\n remainingtries = 0\n\n for item in folderitems:\n if self.end:\n log.info(\"Program received exit signal\")\n return\n remainingtries = 3\n while remainingtries > 0:\n try:\n if self.end:\n return\n nm = item.name\n try:\n nm = unidecode(nm)\n nm = nm.encode('utf-8')\n nm = \"\".join(i for i in nm if i not in \"\\/:*?<>|%\\\"\")\n nm = nm.strip()\n except:\n log.warn(\"Error encoding to utf-8. Will parse anyway\")\n\n pt = item.path\n filesize = None\n tfd = os.path.join(fulldest, nm)\n fexists = False\n if isinstance(item, BitcasaFile):\n filesize = item.size\n try:\n # it is possible that an error here could tell us\n # downloading later won't be possible but there are \n # too many errno's to try and catch that right now\n fexists = os.path.getsize(tfd) >= filesize\n except OSError:\n pass\n\n if filesize is not None and not fexists:\n filedownload = FileDownload(nm, pt, filesize, tfd, fulldest)\n log.debug(\"Queuing file download for %s\", nm)\n self.todownload.append(filedownload)\n elif isinstance(item, BitcasaFolder):\n if (self.depth == None or self.depth > depth) and self.rec:\n folder = {\n \"folder\": item,\n \"path\": os.path.join(path, nm),\n \"depth\": (depth+1)\n }\n log.debug(\"Queuing folder listing for %s\", nm)\n self.folders_queue.append(folder)\n elif fexists:\n self.writeSkipped(tfd, pt, nm)\n elif self.end:\n log.debug(\"Got exit signal. Discontinue recurse\")\n return\n except KeyboardInterrupt:\n self.end = True\n log.info(\"Program received exit signal\")\n except: #Hopefully this won't get called\n self.writeError(nm, tfd, pt, traceback.format_exc())\n else:\n remainingtries = 0\n\n def __init__(self, args):\n log.debug(\"src: %s\", args.src)\n log.debug(\"dst: %s\", args.dst)\n log.debug(\"at: %s\", args.token)\n log.debug(\"tmp: %s\", args.temp)\n log.debug(\"logdir: %s\", args.logdir)\n log.debug(\"rec: %s\", args.rec)\n log.debug(\"depth: %s\", args.depth)\n log.debug(\"mt: %s\", args.threads)\n log.debug(\"p: %s\", args.progress)\n #destination directory\n self.dest = args.dst\n #temp directory\n self.tmp = args.temp\n self.successfiles = os.path.join(args.logdir, \"successfiles.txt\")\n self.errorfiles = os.path.join(args.logdir, \"errorfiles.txt\")\n self.skippedfiles = os.path.join(args.logdir, \"skippedfiles.txt\")\n #bittcasa base64 encdoded path\n self.basefolder = args.src\n #Access token\n self.accesstoken = args.token\n if args.threads is None:\n log.info(\"Using default max threads value of 5\")\n args.threads = 5\n #Recursion\n self.rec = args.rec\n #Recursion max depth\n self.depth = args.depth\n #Test only\n self.test = args.test\n #Log dir\n self.logdir = args.logdir\n #log progress\n self.progress = args.progress\n\n #Initialize\n self.threads = [None] * args.threads\n self.end = False\n self.st = time.time()\n self.bytestotal = 0\n self.todownload = deque()\n self.folders_queue = deque()\n self.folders_lock = None\n self.downloader = None\n self.queuers = []\n self.done = False\n self.downloadtime = 0\n self.copytime = 0\n\n def process(self):\n bitc = BitcasaClient(utils.CLIENTID, utils.CLIENTSECRET, \"https://rose-llc.com/bitcasafilelist/\", self.accesstoken)\n log.debug(\"Getting base folder\")\n base = None\n remainingtries = 3\n if self.test:\n remainingtries = 1\n apiratecount = 0\n while base is None and remainingtries > 0:\n try:\n base = bitc.get_folder(self.basefolder)\n except BitcasaException as e:\n remainingtries -= 1\n if e.code == 9006:\n apiratecount += 1\n remainingtries += 1\n log.warn(\"API rate limit reached. Will retry\")\n else:\n log.warn(\"Couldn't get base folder %s. Will retry %s more times\", e.code, remainingtries)\n\n if remainingtries > 0:\n try:\n time.sleep(10 * apiratecount)\n except KeyboardInterrupt:\n log.info(\"Got exit signal. Goodbye\")\n return\n else:\n log.error(\"Error could not retreive base folder\")\n return\n log.debug(\"Got base folder\")\n if self.test:\n log.info(\"Nothing downloaded because this is a test\")\n return\n try:\n with open(self.successfiles, 'w+') as myfile:\n myfile.write(\"File path\\n\")\n myfile.write(time.strftime(\"%Y-%m-%d %H:%M:%S\") + \" Start\\n\")\n\n with open(self.errorfiles, 'w+') as myfile:\n myfile.write(\"Type||File path||Base64 Path\\n\")\n myfile.write(time.strftime(\"%Y-%m-%d %H:%M:%S\") + \" Start\\n\")\n\n with open(self.skippedfiles, 'w+') as myfile:\n myfile.write(\"File path||Base64 Path\\n\")\n myfile.write(time.strftime(\"%Y-%m-%d %H:%M:%S\") + \" Start\\n\")\n except:\n log.exception(\"Error. Could not initialize logging files. Ending\")\n return\n log.debug(\"Queuing base folder\")\n folder = {\n \"folder\": base,\n \"path\": \"\",\n \"depth\": 0\n }\n self.folders_queue.append(folder)\n log.debug(\"Starting Queuers and Downloader\")\n self.downloader = DownloadThreaded(self)\n self.downloader.start()\n for qid in xrange(len(self.threads)):\n qid+=1\n queue_thread = QueueThreaded(str(qid), self)\n self.queuers.append({\"thread\":queue_thread, \"processing\":False, \"qid\":qid})\n queue_thread.start()\n # Give the queuers time to catch up\n try:\n time.sleep(10)\n\n #wait for threads to finish downoading\n active = self.getActiveThreads()\n while len(active) > 0 or len(self.folders_queue) > 0 or len(self.todownload) >0:\n for thread in active:\n if thread and thread.isAlive():\n thread.join(5)\n if len(active) == 0:\n time.sleep(5)\n active = self.getActiveThreads()\n\n self.done = True\n for queue_thread in self.queuers:\n if queue_thread[\"thread\"].isAlive():\n queue_thread[\"thread\"].join(5)\n\n except KeyboardInterrupt:\n error = True\n while error:\n try:\n self.end = True\n log.info(\"Program received exit signal\")\n active = self.getActiveThreads()\n for thread in active:\n if thread and thread.isAlive():\n log.info(\"Waiting for download thread %s to shutdown\", thread.name)\n thread.join(1)\n for queue_thread in self.queuers:\n if queue_thread[\"thread\"].isAlive():\n log.info(\"Wating for queuer to shutdown %s\", queue_thread[\"qid\"])\n queue_thread[\"thread\"].join(1)\n if self.downloader.isAlive():\n log.info(\"Waiting for Downloader to shutdown\")\n self.downloader.join(1)\n except KeyboardInterrupt:\n pass\n else:\n error = False\n #Log final speed and statistics\n speed = utils.get_speed(self.bytestotal, self.downloadtime)\n copyspeed = utils.get_speed(self.bytestotal, self.copytime)\n runspeed = utils.get_speed(self.bytestotal, (time.time() - self.st))\n log.info(\"Total download time: %s\", utils.convert_time(self.downloadtime))\n log.info(\"Total run time: %s\", utils.convert_time(time.time() - self.st))\n if self.tmp:\n log.info(\"Total copy time: %s\", utils.convert_time(self.copytime))\n log.info(\"Download speed: %s at %s\", utils.convert_size(self.bytestotal), speed)\n log.info(\"Run speed: %s at %s\", utils.convert_size(self.bytestotal), runspeed)\n if self.tmp:\n log.info(\"Copy speed: %s at %s\", utils.convert_size(self.bytestotal), copyspeed)\n\n def writeSuccess(self, filept):\n try:\n with open(self.successfiles, 'a') as myfile:\n myfile.write(\"%s\\n\" % filept)\n except:\n log.exception(\"Error. Could not write to %s. Ending\", self.successfiles)\n self.end = True\n\n def writeSkipped(self, tfd, pt, nm):\n log.debug(\"%s already exists. Skipping\", nm)\n try:\n with open(self.skippedfiles, 'a') as myfile:\n myfile.write(\"%s||%s\\n\" % (tfd, pt))\n except:\n log.exception(\"Error. Could not write to %s. Ending\", self.skippedfiles)\n self.end = True\n\n def writeError(self, nm, tfd, pt, e):\n log.error(\"Error processing file %s\\n%s\", nm, e)\n try:\n with open(self.errorfiles, 'a') as myfile:\n myfile.write(\"File||%s||%s\\n\" % (tfd, pt))\n except:\n log.exception(\"Error. Could not write to %s. Ending\", self.errorfiles)\n self.end = True\n\n def writeErrorDir(self, nm, tfd, pt, e):\n log.error(\"Error processing folder %s\\n%s\", nm, e)\n try:\n with open(self.errorfiles, 'a') as myfile:\n myfile.write(\"Folder||%s||%s\\n\" % (tfd, pt))\n except:\n log.exception(\"Error. Could not write to %s. Ending\", self.errorfiles)\n self.end = True\ndef main():\n args = utils.get_args()\n log.debug(\"Initializing Bitcasa\")\n bitc = BitcasaDownload(args)\n bitc.process()\n log.info(\"Done\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/getfiles.py","file_name":"getfiles.py","file_ext":"py","file_size_in_byte":18426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"380388182","text":"from sympy import (plot, pi, sin, cos, Symbol, Integral, summation, sqrt, log,\n oo, LambertW, I)\nfrom sympy.plotting.plot import matplotlib\nfrom sympy.utilities.pytest import skip\nfrom tempfile import NamedTemporaryFile\nimport warnings\n\ndef tmp_file(name=''):\n return NamedTemporaryFile(suffix='.png').name\n\ndef plot_and_save(name):\n x = Symbol('x')\n y = Symbol('y')\n z = Symbol('z')\n\n ###\n # Examples from the 'introduction' notebook\n ###\n\n p = plot(x, show=False)\n p = plot(x*sin(x),x*cos(x), show=False)\n p.extend(p)\n p[0].line_color = lambda a : a\n p[1].line_color='b'\n p.title = 'Big title'\n p.xlabel = 'the x axis'\n p[1].label = 'straight line'\n p.legend = True\n p.aspect_ratio = (1,1)\n p.xlim = (-15,20)\n p.save(tmp_file('%s_basic_options_and_colors.png' % name))\n\n p.extend(plot(x+1, show=False))\n p.append(plot((x+3,),(x**2,), show=False)[1])\n p.save(tmp_file('%s_plot_extend_append.png' % name))\n\n p[2] = x**2, (x, -2, 3)\n p.save(tmp_file('%s_plot_setitem.png' % name))\n\n p = plot(sin(x),(x,-2*pi,4*pi), show=False)\n p.save(tmp_file('%s_line_explicit.png' % name))\n\n p = plot(sin(x),(-2*pi,4*pi), show=False)\n p.save(tmp_file('%s_line_implicit_var.png' % name))\n\n p = plot(sin(x), show=False)\n p.save(tmp_file('%s_line_default_range.png' % name))\n\n p = plot((x,), (x*sin(x), x*cos(x)), show=False)\n p.save(tmp_file('%s_two_curves.png' % name))\n\n p = plot(sin(x),cos(x),x, show=False)\n p.save(tmp_file('%s_3d_line.png' % name))\n\n p = plot(x*y, show=False)\n p.save(tmp_file('%s_surface.png' % name))\n\n p = plot(x*sin(z),x*cos(z),z, show=False)\n p.save(tmp_file('%s_parametric_surface.png' % name))\n\n ###\n # Examples from the 'colors' notebook\n ###\n\n p = plot(sin(x), show=False)\n p[0].line_color = lambda a : a\n p.save(tmp_file('%s_colors_line_arity1.png' % name))\n\n p[0].line_color = lambda a, b : b\n p.save(tmp_file('%s_colors_line_arity2.png' % name))\n\n p = plot(x*sin(x), x*cos(x), (0,10), show=False)\n p[0].line_color = lambda a : a\n p.save(tmp_file('%s_colors_param_line_arity1.png' % name))\n\n p[0].line_color = lambda a, b : a\n p.save(tmp_file('%s_colors_param_line_arity2a.png' % name))\n\n p[0].line_color = lambda a, b : b\n p.save(tmp_file('%s_colors_param_line_arity2b.png' % name))\n\n p = plot(sin(x)+0.1*sin(x)*cos(7*x),\n cos(x)+0.1*cos(x)*cos(7*x),\n 0.1*sin(7*x),\n (0, 2*pi),\n show=False)\n p[0].line_color = lambda a : sin(4*a)\n p.save(tmp_file('%s_colors_3d_line_arity1.png' % name))\n p[0].line_color = lambda a, b : b\n p.save(tmp_file('%s_colors_3d_line_arity2.png' % name))\n p[0].line_color = lambda a, b, c : c\n p.save(tmp_file('%s_colors_3d_line_arity3.png' % name))\n\n p = plot(sin(x)*y, (0,6*pi), show=False)\n p[0].surface_color = lambda a : a\n p.save(tmp_file('%s_colors_surface_arity1.png' % name))\n p[0].surface_color = lambda a, b : b\n p.save(tmp_file('%s_colors_surface_arity2.png' % name))\n p[0].surface_color = lambda a, b, c : c\n p.save(tmp_file('%s_colors_surface_arity3a.png' % name))\n p[0].surface_color = lambda a, b, c : sqrt((a-3*pi)**2+b**2)\n p.save(tmp_file('%s_colors_surface_arity3b.png' % name))\n\n p = plot(x*cos(4*y), x*sin(4*y), y,\n (-1, 1), (-1, 1), show=False)\n p[0].surface_color = lambda a : a\n p.save(tmp_file('%s_colors_param_surf_arity1.png' % name))\n p[0].surface_color = lambda a, b : a*b\n p.save(tmp_file('%s_colors_param_surf_arity2.png' % name))\n p[0].surface_color = lambda a, b, c : sqrt(a**2+b**2+c**2)\n p.save(tmp_file('%s_colors_param_surf_arity3.png' % name))\n\n ###\n # Examples from the 'advanced' notebook\n ###\n\n i = Integral(log((sin(x)**2+1)*sqrt(x**2+1)),(x,0,y))\n p = plot(i,(1,5), show=False)\n p.save(tmp_file('%s_advanced_integral.png' % name))\n\n s = summation(1/x**y,(x,1,oo))\n p = plot(s, (2,10), show=False)\n p.save(tmp_file('%s_advanced_inf_sum.png' % name))\n\n p = plot(summation(1/x,(x,1,y)), (2,10), show=False)\n p[0].only_integers = True\n p[0].steps = True\n p.save(tmp_file('%s_advanced_fin_sum.png' % name))\n\n\n ###\n # Test expressions that can not be translated to np and generate complex\n # results.\n ###\n\n\n plot(sin(x)+I*cos(x), show=False).save(tmp_file())\n plot(sqrt(sqrt(-x)), show=False).save(tmp_file())\n plot(LambertW(x), show=False).save(tmp_file())\n plot(sqrt(LambertW(x)), show=False).save(tmp_file())\n\n\n ###\n # Test all valid input args for plot()\n ###\n\n # 2D line with all possible inputs\n plot(x , show=False).save(tmp_file())\n plot(x, (x, ), show=False).save(tmp_file())\n plot(x, ( -10, 10), show=False).save(tmp_file())\n plot(x, (x, -10, 10), show=False).save(tmp_file())\n\n # two 2D lines\n plot((x, ), (x+1, (x, -10, 10)), show=False).save(tmp_file())\n plot((x, (x, )), (x+1, (x, -10, 10)), show=False).save(tmp_file())\n plot((x, ( -10, 10)), (x+1, (x, -10, 10)), show=False).save(tmp_file())\n plot((x, (x, -10, 10)), (x+1, (x, -10, 10)), show=False).save(tmp_file())\n plot([x, x+1], show=False).save(tmp_file())\n plot([x, x+1], (x, ), show=False).save(tmp_file())\n plot([x, x+1], ( -10, 10), show=False).save(tmp_file())\n plot([x, x+1], (x, -10, 10), show=False).save(tmp_file())\n\n # 2D and 3D parametric lines\n plot(x, 2*x, show=False).save(tmp_file())\n plot(x, 2*x, sin(x), show=False).save(tmp_file())\n\n # surface and parametric surface\n plot(x*y, show=False).save(tmp_file())\n plot(x*y, 1/x, 1/y,show=False).save(tmp_file())\n\n # some bizarre combinatrions\n ## two 3d parametric lines and a surface\n plot(([x, -x], x**2, sin(x)), (x*y,), show=False).save(tmp_file())\n\n\ndef test_matplotlib():\n if matplotlib:\n plot_and_save('test')\n else:\n skip(\"Matplotlib not the default backend\")\n","sub_path":"sympy/plotting/tests/test_plot.py","file_name":"test_plot.py","file_ext":"py","file_size_in_byte":6014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"334032036","text":"from glob import glob\n\nID_COL = \"id\"\nDATE_COL = \"ydt\"\nDESC_COL = \"description\"\nDEBT_COL = \"debit\"\nCRDT_COL = \"credit\"\nBLNC_COL = \"balance\"\n\n\ndef get_csv(path, out, i):\n with open(path) as f:\n for line in f:\n line = line.replace(',,', ',0,')\n out.write(str(i) + \",\" + line)\n i += 1\n return i\n\n\ndef combine_csvs():\n paths = glob(\"../statements/*.csv\")\n i = 1\n with open(\"../combined_statements.csv\", \"w+\") as output_file:\n output_file.write(ID_COL+\",\"+DATE_COL+\",\"+DESC_COL+\",\"+DEBT_COL+\",\"+CRDT_COL+\",\"+BLNC_COL)\n for path in paths:\n i = get_csv(path, output_file, i)\n\n\nif __name__ == \"__main__\":\n combine_csvs()\n","sub_path":"src/csv_parser.py","file_name":"csv_parser.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"73688646","text":"import logging\nimport argparse\nimport os\nimport time\nimport cv2\nimport threading\n\nfrom networktables import NetworkTables\n\nfrom bucketvision.capturers.cv2capture import Cv2Capture\nfrom bucketvision.capturers.csicapture import CSICapture\nfrom bucketvision.displays.cv2display import Cv2Display\nfrom bucketvision.displays.cameraserverdisplay import CameraServerDisplay\nfrom bucketvision.postprocessors.angryprocessor import AngryProcesses\nfrom bucketvision.multiplexers.class_mux import ClassMux\nfrom bucketvision.multiplexers.mux1n import Mux1N\nfrom bucketvision.sourceprocessors.resizesource import ResizeSource\nfrom bucketvision.sourceprocessors.overlaysource import OverlaySource\n\nfrom bucketvision.configs import configs\n\nlogging.basicConfig(level=logging.DEBUG)\n\ndef connectionListener(connected, info):\n \"\"\" used to wait till network tables is initalized \"\"\"\n print(info, '; Connected=%s' % connected)\n with cond:\n notified[0] = True\n cond.notify()\n\nif __name__ == '__main__':\n\n # add parse arguments\n parser = argparse.ArgumentParser()\n \n parser.add_argument('-ip', '--ip-address', required=False, default='10.41.83.2',\n help='IP Address for NetworkTable Server')\n\n parser.add_argument('-t', '--test', required=False,\n help='Test mode (uses cv2 display)', action='store_true')\n\n parser.add_argument('-cam', '--num-cam', required=False, default=1,\n help='Number of cameras to instantiate', type=int, choices=range(1, 10))\n\n parser.add_argument('-co', '--offs-cam', required=False, default=0,\n help='First camera index to instantiate', type=int, choices=range(0, 10))\n \n parser.add_argument('-proc', '--num-processors', required=False, default=4,\n help='Number of processors to instantiate', type=int, choices=range(0, 10))\n\n parser.add_argument('-CSI', '--CSI', \n help='Use CSI interface', action='store_true')\n\n args = vars(parser.parse_args())\n\n cond = threading.Condition()\n notified = [False]\n # init networktables\n NetworkTables.initialize(server=args.ip_address)\n # add a listener for connection\n NetworkTables.addConnectionListener(connectionListener, immediateNotify=True)\n\n # if not connected then block and wait\n with cond:\n print(\"Waiting\")\n if not notified[0]:\n cond.wait()\n\n VisionTable = NetworkTables.getTable(\"BucketVision\")\n VisionTable.putString(\"BucketVisionState\", \"Starting\")\n VisionTable.putNumber(\"Exposure\", 50.0)\n \n # create a source per camera\n source_list = list()\n\n for i in range(args.num_cam):\n if not args.CSI:\n cap = Cv2Capture(camera_num=i+args.offs_cam, network_table=VisionTable, exposure=configs['exposure'], res=configs['camera_res'])\n else:\n cap = CSICapture(camera_num=i+args.offs_cam, network_table=VisionTable, exposure=configs['exposure'], res=configs['camera_res'])\n source_list.append(cap)\n cap.start()\n\n # Output is cropped to match vision target search area. \n # UU would prefer to output full image from camera and adjust traget drawings to croppped target search area.\n # Right now its not clear how the output matches the input image and the target coordinates.\n # This is likely why the drawtarget routine has not yet been enabled.\n\n source_mux = ClassMux(*source_list)\n output_mux = Mux1N(source_mux)\n \n process_output = output_mux.create_output()\n display_output = OverlaySource(ResizeSource(output_mux.create_output(), res=configs['output_res']))\n \n VisionTable.putString(\"BucketVisionState\", \"Started Captures\")\n\n # create post processor threads to process each image before sending it to the CameraServer (or window if testing)\n # this does the more complex target finding. We create multiple process threads to process the frames\n # as they are captured\n proc_list = list()\n for i in range(args.num_processors):\n proc = AngryProcesses(process_output, network_table=VisionTable, debug_label=\"Proc{}\".format(i))\n proc_list.append(proc)\n proc.start()\n\n VisionTable.putString(\"BucketVisionState\", \"Started Processes\")\n\n if args.test:\n window_display = Cv2Display(source=display_output)\n window_display.start()\n VisionTable.putString(\"BucketVisionState\", \"Started CV2 Display\")\n else:\n cs_display = CSDisplay(source=display_output, network_table=VisionTable)\n cs_display.start()\n VisionTable.putString(\"BucketVisionState\", \"Started CS Display\")\n\n try:\n VisionTable.putValue(\"CameraNum\", 0)\n while True:\n source_mux.source_num = int(VisionTable.getEntry(\"CameraNum\").value)\n # not sure how this works and if needed\n if args.test:\n if window_display._new_frame:\n cv2.imshow(window_display.window_name, window_display._frame)\n window_display._new_frame = False\n cv2.waitKey(1)\n \n except KeyboardInterrupt:\n pass\n finally:\n if args.test:\n window_display.stop()\n cv2.destroyAllWindows()\n else:\n cs_display.stop()\n for proc in proc_list:\n proc.stop()\n for cap in source_list:\n cap.stop()\n","sub_path":"2019 Pipeline/BucketVision_AngryEyes_2019.py","file_name":"BucketVision_AngryEyes_2019.py","file_ext":"py","file_size_in_byte":5556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"29026462","text":"# while loop in Python\n\n# example 1\n'''\nwhile True:\n print('hello')\n'''\n# control-C: force the program to stop\n\n# example 2: print a string and strip off its first char every time\nmyString = 'hello'\nwhile myString:\n print(myString, end = '-> ')\n myString = myString[1:]\n","sub_path":"basics/loops/while_loop.py","file_name":"while_loop.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"262354212","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def minDepth(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if not root:\n return 0\n level = 0\n currLevel = [root]\n nextLevel = []\n while True:\n while currLevel:\n node = currLevel[0]\n currLevel[:] = currLevel[1:]\n if not node.left and not node.right:\n return level + 1\n else:\n if node.left:\n nextLevel.append(node.left)\n if node.right:\n nextLevel.append(node.right)\n level += 1\n currLevel = nextLevel\n nextLevel = []","sub_path":"minimum_depth_of_binary_tree.py","file_name":"minimum_depth_of_binary_tree.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"221548370","text":"import asyncio\nimport unittest\n\nimport www.orm as orm\n\n\nclass User(orm.Model):\n __table__ = 'users'\n\n id = orm.IntegerField(primary_key=True)\n name = orm.StringField()\n\n\nclass ModelTestCase(unittest.TestCase):\n def test_model_class(self):\n database = {\n 'host': '127.0.0.1',\n 'port': 3306,\n 'user': 'root',\n 'password': 'root',\n 'db': 'python_test'\n }\n\n expect_user = {\n 'id': 1,\n 'name': 'test'\n }\n\n async def connenct_database_and_create_data(loop):\n await orm.create_pool(loop, **database)\n\n user = await User.find(1)\n if user is not None:\n await user.remove()\n\n user = User()\n user.id = expect_user['id']\n user.name = expect_user['name']\n await user.save()\n return user\n\n loop = asyncio.get_event_loop()\n task = asyncio.ensure_future(\n connenct_database_and_create_data(loop))\n actual_user = loop.run_until_complete(task)\n\n self.assertIsInstance(actual_user, User)\n self.assertEqual(actual_user.id, expect_user['id'])\n self.assertEqual(actual_user.name, expect_user['name'])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/www_test/orm_test.py","file_name":"orm_test.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"217009142","text":"from django.urls import path\n\nfrom routes.views import add_route\nfrom .views import (\n home, TrainCreateView, TrainDeleteView, TrainUpdateView, TrainDetailView,\n)\n\nurlpatterns = [\n path('delete//', TrainDeleteView.as_view(), name='delete'),\n path('update//', TrainUpdateView.as_view(), name='update'),\n path('add/', TrainCreateView.as_view(), name='add'),\n path('details//', TrainDetailView.as_view(), name='details'),\n path('add_route/', add_route, name='add_route'),\n path('', home, name='home'),\n]\n","sub_path":"trains/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"516935156","text":"import random as ran\nimport csv\n\nbreakfast_db = open('breakfast.txt', 'r')\nlunch_db = open('lunch.txt', 'r')\nbreakfast_csv = csv.DictReader(breakfast_db)\nlunch_csv = csv.DictReader(lunch_db)\nbreakfast = sorted(breakfast_csv, key=lambda row: row['recipe_calories'])\nlunch = sorted(lunch_csv, key=lambda row: row['recipe_calories'])\nbreakfast_db.close()\nlunch_db.close()\n\n\ndef random_number(food_list):\n rand_item = ran.randint(0, len(food_list) - 1)\n return rand_item\n\n\ndef get_breakfast():\n rand_num = random_number(breakfast)\n get_ran_break = breakfast[rand_num]\n return get_ran_break\n\n\ndef get_lunch():\n rand_num = random_number(lunch)\n get_ran_lunch = lunch[rand_num]\n return get_ran_lunch\n\n\ndef food_menu(calorie_limit):\n rand_break = random_number(breakfast)\n rand_lunch = random_number(lunch)\n get_ran_lunch = lunch[rand_lunch]['recipe_calories']\n get_ran_break = breakfast[rand_break]['recipe_calories']\n get_total_calories = int(get_ran_break) + int(get_ran_lunch)\n if int(calorie_limit) >= get_total_calories >= (int(calorie_limit) - 50):\n print(\"Today's Breakfast {} and calories are {}\".format(breakfast[rand_break]['recipe_name'],\n breakfast[rand_break]['recipe_calories']))\n print(\"Today's Lunch {} and calories are {}\".format(lunch[rand_lunch]['recipe_name'],\n lunch[rand_lunch]['recipe_calories']))\n\n\nif __name__ == \"__main__\":\n # max_calories = input(\"Enter Calorie Limit: \")\n max_calories = 1130\n food_menu(max_calories)\n","sub_path":"receipe.py","file_name":"receipe.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"602490833","text":"# -*- coding: utf-8 -*-\n\"\"\"\nConsider a list (list = []). You can perform the following commands:\n\n1. insert i e: Insert integer e at position i.\n2. print: Print the list.\n3. remove e: Delete the first occurrence of integer e.\n4. append e: Insert integer e at the end of the list.\n5. sort: Sort the list.\n6. pop: Pop the last element from the list.\n7. reverse: Reverse the list.\n\nInitialize your list and read in the value of n followed by n lines of commands \nwhere each command will be of the types listed above. Iterate through each \ncommand in order and perform the corresponding operation on your list.\n\nExample\nN = 4\nappend 1\nappend 2\ninsert 3 1\nprint\n\n- append 1: Append 1 to the list, arr = [1].\n- append 2: Append 2 to the list, arr = [1,2].\n- insert 3 1: Insert 3 at index 1, arr = [1,3,2].\n- print: Print the array.\n\nOutput:\n[1, 3, 2]\n\nInput Format\nThe first line contains an integer, n, denoting the number of commands.\nEach line i of the n subsequent lines contains one of the commands described \nabove.\n\nConstraints\n- The elements added to the list must be integers.\n\nOutput Format\nFor each command of type print, print the list on a new line.\n\nSample Input 0\n12\ninsert 0 5\ninsert 1 10\ninsert 0 6\nprint\nremove 6\nappend 9\nappend 1\nsort\nprint\npop\nreverse\nprint\n\nSample Output 0\n[6, 5, 10]\n[1, 5, 9, 10]\n[9, 5, 1]\n\"\"\" \n \nif __name__ == '__main__':\n # take in the inputs\n n = int(input())\n output = []\n for _ in range(n):\n line = input().split()\n if(line[0] == \"insert\"):\n output.insert(int(line[1]), int(line[2]))\n if(line[0] == \"print\"):\n print(output)\n if(line[0] == \"remove\"):\n output.remove(int(line[1]))\n if(line[0] == \"append\"):\n output.append(int(line[1]))\n if(line[0] == \"sort\"):\n output.sort()\n if(line[0] == \"pop\"):\n output.pop(len(output) - 1)\n if(line[0] == \"reverse\"):\n output.reverse()","sub_path":"Python/Basic Data Types/Lists.py","file_name":"Lists.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"50022884","text":"#!/usr/bin/env python3\n\n# My solution to 3SUM.\n# The big speed I made was when I was finding the third number...\n# I kept a set of numbers I ALREADY saw instead of looping through the rest\n# of the list every time I was looking for the third number.\n\n# Asks for user input in command line and outputs 3SUMs\ndef main():\n # User input -> list of ints\n user_input = input(\"Enter a list of numbers:\\n> \").strip('[').strip(']')\n\n if (user_input.find(',') > 0):\n nums = [int(c) for c in user_input.split(',')]\n else:\n nums = [int(c) for c in user_input.split(' ')]\n\n results = set() # Set of tuples\n seen = set() # Keep track of seen numbers (key improvement)\n\n for i in range(len(nums) - 1):\n for j in range(i + 1, len(nums)):\n # See if third number to sum to 0 exists\n (n1, n2) = (nums[i], nums[j])\n\n n3 = -(n1 + n2)\n if n3 in seen:\n sum = tuple(sorted([n1, n2, n3]))\n results.add(sum)\n\n # Finished with this number, add it to seen\n seen.add(n1)\n\n for result in results:\n print(str(result)[1:-1])\n\nif __name__ == '__main__':\n main()\n","sub_path":"Challenge #323 [Easy] 3SUM/three_sum.py","file_name":"three_sum.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"152187096","text":"import numpy as np\nimport matplotlib.pyplot as plt \nimport matplotlib.animation as animation\nimport random\n\nN = 100\nON = 255\nOFF = 0\nvals = range(256)\n\n# populate grid with random on/off - more off than on\ngrid = np.random.choice(vals, N*N).reshape(N, N)\n\ndef color(n):\n if 0 <= n < 64:\n return 1\n elif 64 <= n < 128:\n return 2\n elif 128 <= n < 192:\n return 3\n else:\n return 4\n\ndef update(data):\n global grid\n # copy grid since we require 8 neighbors for calculation\n # and we go line by line \n newGrid = grid.copy()\n for i in range(N):\n for j in range(N):\n # compute 8-neghbor sum \n # using toroidal boundary conditions - x and y wrap around \n # so that the simulaton takes place on a toroidal surface.\n colors = {1:0,2:0,3:0,4:0}\n\n colors[color(grid[i, (j-1)%N])] += 1\n colors[color(grid[i, (j+1)%N])] += 1\n colors[color(grid[(i-1)%N, j])] += 1\n colors[color(grid[(i+1)%N, j])] += 1\n colors[color(grid[(i-1)%N, (j-1)%N])] += 1\n colors[color(grid[(i-1)%N, (j+1)%N])] += 1\n colors[color(grid[(i+1)%N, (j-1)%N])] += 1\n colors[color(grid[(i+1)%N, (j+1)%N])] += 1\n\n popularColor = max(colors, key=colors.get)\n cantidad = max(colors.values())\n if cantidad >= 7:\n newGrid[i, j] = abs(popularColor-4)*64\n elif 4 < cantidad < 7:\n newGrid[i,j] = popularColor*64 - 1\n else:\n newGrid[i, j] = grid[i,j]\n mat.set_data(newGrid)\n grid = newGrid\n return [mat]\n\n# set up animation\nfig, ax = plt.subplots()\nmat = ax.matshow(grid)\nani = animation.FuncAnimation(fig, update, interval=50,\n save_count=50)\nplt.show()","sub_path":"more/retarded_game_of_life.py","file_name":"retarded_game_of_life.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"223526638","text":"from __future__ import annotations\n\nfrom copy import deepcopy\nfrom math import log10\nfrom pathlib import Path\nfrom typing import Union\n\nimport librosa\nimport numpy as np\nimport soundfile as sf\nfrom scipy import signal\n\n\nclass AudioFile:\n \"\"\"\n A class for representing and modifying audio files.\n \"\"\"\n\n def __init__(self, path: Union[str, Path] = None):\n \"\"\"\n Initialize an audio file. Load file if path is provided.\n\n :param path: path to audio file.\n \"\"\"\n self.samples: np.ndarray = np.array([])\n self.sr: int = int()\n self.filename: str = str()\n if path is not None:\n self.load(path)\n\n @property\n def length(self) -> int:\n \"\"\"\n The length in samples of the audio data.\n \"\"\"\n return self.samples.shape[-1]\n\n @property\n def peak(self) -> float:\n \"\"\"\n The max absolute amplitude value.\n \"\"\"\n max_amplitude = self.samples.max(axis=-1, initial=0.0)\n min_amplitude = self.samples.min(axis=-1, initial=0.0)\n return max(max_amplitude, abs(min_amplitude))\n\n @staticmethod\n def db_to_scale(db: float) -> float:\n \"\"\"\n Convert a decibel value to a scalar in [0.0, 1.0]\n\n :param db: decibel value - 6db of gain is equivalent to scaling by 2.0\n :return: a scalar in [0.0. 1.0]\n \"\"\"\n return 10.0 ** (db / 20.0)\n\n @staticmethod\n def scale_to_db(factor: float) -> float:\n \"\"\"\n Convert a scalar value in [0.0, 1.0] to a gain adjustment in decibles.\n\n :param factor: a scalar in [0.0, 1.0]\n :return: decibel value - 6db of gain is equivalent to scaling by 2.0\n \"\"\"\n return 20.0 * log10(factor)\n\n def copy(self) -> AudioFile:\n \"\"\"\n Return a copy of the AudioFile.\n\n :return: a copy of the current object.\n \"\"\"\n return deepcopy(self)\n\n def load(self, path: Union[str, Path]):\n \"\"\"\n Load an audio file.\n\n :param path: path to audio file.\n \"\"\"\n path = Path(path)\n if not path.exists():\n raise Exception('file {} does not exist'.format(path))\n self.samples, self.sr = librosa.load(path=path, sr=None)\n self.filename = path.name\n\n def save(self,\n output_path: Union[str, Path],\n filename: str = None,\n subtype: str = 'PCM_16'):\n \"\"\"\n Save the current audio samples to a new file.\n\n :param output_path: output path for audio samples.\n :param filename: filename for output - will use the original filename of the audio file by default.\n :param subtype: soundfile subtype - 16-bit PCM by default.\n \"\"\"\n if filename is None:\n filename = self.filename\n output_path = Path(output_path)\n if not output_path.exists():\n output_path.mkdir(parents=True)\n output_file = output_path.joinpath(filename)\n sf.write(output_file, self.samples, self.sr, subtype=subtype)\n\n def resample(self, new_sr: int):\n \"\"\"\n Resample to new sample rate.\n\n :param new_sr: target sample rate.\n \"\"\"\n self.samples = librosa.resample(self.samples, self.sr, new_sr)\n self.sr = new_sr\n return self\n\n def invert_polarity(self):\n \"\"\"\n Invert the polarity of the waveform.\n \"\"\"\n self.scale(-1)\n return self\n\n def scale(self, scale: float):\n \"\"\"\n Scale amplitudes by a constant.\n\n :param scale: constant used to scale audio\n \"\"\"\n self.samples = self.samples * scale\n return self\n\n def gain(self, db: float):\n \"\"\"\n Adjust gain of audio file by decibels.\n\n :param db: number of decibels to adjust gain by.\n \"\"\"\n scale = self.db_to_scale(db)\n self.scale(scale=scale)\n return self\n\n def normalize(self):\n \"\"\"\n Normalize audio samples.\n \"\"\"\n self.samples = librosa.util.normalize(self.samples, axis=-1)\n return self\n\n def clip(self, clip_db: float = 0.0):\n \"\"\"\n Digitally clip audio samples by scaling beyond [-1., 1.], clipping to [-1., 1.], and reversing the scaling.\n\n :param clip_db: Number of decibels to clip audio by.\n \"\"\"\n peak = min(1.0, self.peak)\n if peak < 1.0:\n self.normalize()\n self.gain(db=clip_db)\n np.clip(self.samples, -1.0, 1.0, out=self.samples)\n self.gain(db=-clip_db)\n self.scale(peak)\n return self\n\n def trim_start(self, relative_start: float = 0.0):\n \"\"\"\n Trim the beginning of an audio file, leaving the remaining samples.\n\n :param relative_start: The relative start position of the new audio file.\n \"\"\"\n start_sample = int(self.length * relative_start)\n self.samples = self.samples[start_sample:]\n return self\n\n def trim_to_n_samples(self, n: int):\n \"\"\"\n Trim an audio file to a specific number of samples.\n\n :param n: The desired number of samples. Any samples after will be removed.\n \"\"\"\n if n >= self.length:\n self.samples = self.samples[:n]\n return self\n\n def add_silence(self,\n samples_before: int = None,\n samples_after: int = None,\n sec_before: float = 0.0,\n sec_after: float = 0.0):\n \"\"\"\n Add silence to the end of the audio samples.\n\n :param samples_before: number of samples of silence to add to beginning of the audio data. Takes precedence over sec_before if set.\n :param samples_after: number of samples of silence to add to end of the audio data. Takes precedence over sec_after if set.\n :param sec_before: seconds of silence to add the beginning of the audio data.\n :param sec_after: seconds of silence to add the end of the audio data.\n \"\"\"\n if samples_before is None:\n samples_before = int(self.sr * sec_before)\n if samples_after is None:\n samples_after = int(self.sr * sec_after)\n silence_before = np.zeros((samples_before,), dtype=self.samples.dtype)\n self.samples = np.concatenate((silence_before, self.samples))\n silence_after = np.zeros((samples_after,), dtype=self.samples.dtype)\n self.samples = np.concatenate((self.samples, silence_after))\n return self\n\n def varispeed(self, rate: float):\n \"\"\"\n Stretch time/pitch of audio data by increasing/decreasing playback speed.\n\n :param rate: Stretch factor. If rate > 1, then the signal is sped up. If rate < 1, then the signal is slowed down.\n \"\"\"\n old_sr = self.sr\n self.sr *= rate\n self.resample(old_sr)\n return self\n\n def mix(self,\n audio: AudioFile,\n relative_start: float = 0.0,\n maintain_length: bool = False):\n \"\"\"\n Combine two audio files.\n\n :param audio: an AudioFile to add to the current AudioFile.\n :param relative_start: the start position of audio relative to the current audio - i.e. 0.5 adds audio starting\n in the middle of the current audio.\n :param maintain_length: if true, mixed audio will be trimmed to maintain the same length as the original audio\n \"\"\"\n assert (self.sr == audio.sr)\n shape = self.samples.shape\n audio = audio.copy()\n\n # delay the start of the new audio\n start_sample = int(self.length * relative_start)\n audio.add_silence(samples_before=start_sample)\n\n # pad end of audio data if needed\n self.add_silence(samples_after=max(0, audio.length - self.length))\n audio.add_silence(samples_after=max(0, self.length - audio.length))\n\n # combine signals\n self.samples = self.samples + audio.samples\n if maintain_length:\n self.samples.resize(shape)\n return self\n\n def lpf(self, cutoff: float, order: int = 1):\n \"\"\"\n Low-pass filter.\n\n https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.butter.html#scipy.signal.butter\n\n :param cutoff: cutoff frequency in Hz.\n :param order: the order of the filter.\n \"\"\"\n sos = signal.butter(order, cutoff, btype='low', analog=False, output='sos', fs=self.sr)\n filtered = signal.sosfilt(sos, self.samples)\n self.samples = filtered\n return self\n\n def hpf(self, cutoff: float, order: int = 1):\n \"\"\"\n High-pass filter.\n\n https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.butter.html#scipy.signal.butter\n\n :param cutoff: cutoff frequency in Hz.\n :param order: the order of the filter.\n \"\"\"\n sos = signal.butter(order, cutoff, btype='high', analog=False, output='sos', fs=self.sr)\n filtered = signal.sosfilt(sos, self.samples)\n self.samples = filtered\n return self\n\n def dynamic_lpf(self,\n cutoff: float,\n order: int = 1,\n relative_start: float = 0.0,\n relative_end: float = 1.0,\n exponential: float = 1.0):\n \"\"\"\n Dynamic low-pass filter.\n\n :param cutoff: cutoff frequency in Hz.\n :param order: the order of the filter.\n :param relative_start: relative position to start filtering, 0.0 is the start of the audio.\n :param relative_end: relative position to end filtering, 0.0 is the end of the audio.\n :param exponential: exponential order dictates crossfade shape.\n \"\"\"\n filtered = self.copy().lpf(cutoff=cutoff, order=order)\n\n crossfade = np.zeros(self.samples.shape)\n start_sample = int(self.length * relative_start)\n end_sample = int(self.length * relative_end)\n num = (end_sample - start_sample) // 2\n fade = np.linspace(0.000001, 1.0, num=num) ** exponential\n\n for i in range(fade.shape[-1]):\n crossfade[start_sample+i] = fade[i]\n crossfade[end_sample-i-1] = fade[i]\n\n filtered.samples = filtered.samples * crossfade\n self.samples = self.samples * (1.0 - crossfade)\n self.mix(filtered)\n return self\n\n def conv_reverb(self,\n ir: AudioFile,\n dry_db: float = 0.0,\n wet_db: float = 0.0,\n predelay: float = 0.0,\n trim_tail: bool = True):\n \"\"\"\n Convolution reverb.\n\n :param ir: AudioFile containing impulse response.\n :param dry_db: db gain to apply to dry audio.\n :param wet_db: db gain to apply to wet audio.\n :param predelay: predelay in ms added to wet audio.\n :param trim_tail: if True, will trim tail of new audio to maintain length of original audio.\n \"\"\"\n ir = ir.copy()\n if ir.sr != self.sr:\n ir.resample(self.sr)\n\n convolution = self.copy()\n convolution.samples = signal.convolve(self.samples, ir.samples, mode='full')\n\n if predelay > 0.0:\n convolution.add_silence(sec_before=predelay / 1000)\n\n self.gain(dry_db).mix(convolution.gain(wet_db), relative_start=0.0, maintain_length=trim_tail)\n self.clip()\n return self\n","sub_path":"AudioFile.py","file_name":"AudioFile.py","file_ext":"py","file_size_in_byte":11345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"416996562","text":"#146. LRU Cache\r\n# Time Complexity : O(1)\r\n# Space Complexity : O(1)\r\n# Did this code successfully run on Leetcode : Yes\r\n# Any problem you faced while coding this : No\r\nclass Node:\r\n def __init__(self,key,val):\r\n self.key = key\r\n self.val = val\r\n self.prev = None\r\n self.next = None\r\n \r\nclass LRUCache:\r\n head = None\r\n Tail = None\r\n\r\n def __init__(self, capacity: int):\r\n self.mapp = {}\r\n self.head = Node(-1,-1)\r\n self.tail = Node(-1,-1)\r\n self.head.next = self.tail\r\n self.tail.prev = self.head\r\n self.capacity = capacity\r\n def remove(self,node):\r\n node.prev.next = node.next\r\n node.next.prev = node.prev\r\n def insert(self,node):\r\n node.prev = self.head\r\n node.next = self.head.next\r\n self.head.next = node\r\n node.next.prev = node \r\n\r\n def get(self, key: int) -> int:\r\n if key not in self.mapp:\r\n return -1\r\n node = self.mapp[key]\r\n self.remove(node)\r\n self.insert(node)\r\n return node.val\r\n\r\n def put(self, key: int, value: int) -> None:\r\n if key in self.mapp:\r\n node = self.mapp[key]\r\n node.val = value\r\n self.remove(node)\r\n self.insert(node)\r\n else:\r\n if len(self.mapp) == self.capacity:\r\n tailnode = self.tail.prev\r\n self.remove(tailnode)\r\n self.mapp.pop(tailnode.key)\r\n newnode = Node(key,value)\r\n self.mapp[key] = newnode\r\n self.insert(newnode)\r\n","sub_path":"LRUCache.py","file_name":"LRUCache.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"536259169","text":"import torch.utils.data as data\nfrom PIL import Image\nimport numpy as np\nimport glob\nimport os\nfrom torchvision import transforms\n\n\nclass DataLoaderSegmentation(data.Dataset):\n def __init__(self, folder_path,transform=None,image_size=[48, 48]):\n super(DataLoaderSegmentation, self).__init__()\n self.img_files = glob.glob(os.path.join(folder_path,'image','*.jpg'))\n self.mask_files = []\n self.image_size = image_size\n self.transform= transform\n for img_path in self.img_files:\n self.mask_files.append(os.path.join(folder_path,'mask',os.path.basename(img_path)))\n\n def __getitem__(self, index):\n img_path = self.img_files[index]\n mask_path = self.mask_files[index]\n _img = Image.open(img_path).convert('RGB')\n _tmp = np.array(Image.open(mask_path).convert('L'), dtype=np.uint8)\n _target = self.encode_segmap(_tmp)\n sample={'image': _img,'label': _target}\n if self.transform:\n sample = self.transform(sample)\n return sample #torch.from_numpy(data).float(), torch.from_numpy(label).float()\n\n def __len__(self):\n return len(self.img_files)\n def encode_segmap(self, mask):\n # Put all void classes to ignore_index\n mask[mask!=0]=1\n mask=Image.fromarray(mask)\n return mask","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"409768967","text":"''' Problem 3\n어떤 수를 소수의 곱으로만 나타내는 것을 소인수분해라 하고, 이 소수들을 그 수의 소인수라고 합니다.\n예를 들면 13195의 소인수는 5, 7, 13, 29 입니다.\n\n600851475143의 소인수 중에서 가장 큰 수를 구하세요.\n'''\nimport time\n\ndef logging_time(original_fn):\n def wrapper_fn(*args, **kwargs):\n start_time = time.time()\n result = original_fn(*args, **kwargs)\n end_time = time.time()\n print(\"WorkingTime[{}]: {} sec\".format(original_fn.__name__, end_time-start_time))\n return result\n return wrapper_fn\n\n# Answer\n@logging_time\ndef problem3(num):\n num_list = []\n\n for i in range(2, num):\n\n while num % i == 0:\n num_list.append(i)\n num = num / i\n print(num, \" | \", num_list)\n\n if num == 1:\n break\n\n return num_list\n\n# Solution\n@logging_time\ndef prime(num):\n factor=2\n while num != 1:\n if num%factor == 0:\n print(num, factor)\n num = num / factor\n else:\n factor +=1\n return factor\n\n\nif __name__ == '__main__':\n\n print(problem3(13195))\n # [5, 7, 13, 29]\n\n print(problem3(600851475143))\n # [71, 839, 1471, 6857]\n\n print(prime(600851475143))\n # 6857\n\n''' Environment\nPyCharm 2019.1 EAP (Community Edition)\nBuild #PC-191.6014.12, built on March 6, 2019\nJRE: 11.0.2+159 amd64\nJVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o\nWindows 7 6.1\nPython 3.6.6\n'''","sub_path":"Algorithm/ProjectEuler/Python/000003.py","file_name":"000003.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"458572445","text":"#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport argparse\nimport gzip\nimport logging\nimport os\nimport random\nimport socket\nimport time\nimport CloudFlare\nimport csv\n\nfrom base64 import b64encode, b64decode\nfrom datetime import datetime, timezone\n\nimport boto3\n\nfrom droidlet.tools.crowdsourcing.servermgr import ping_cuberite\n\nAWS_ACCESS_KEY_ID = os.environ[\"AWS_ACCESS_KEY_ID\"]\nAWS_SECRET_ACCESS_KEY = os.environ[\"AWS_SECRET_ACCESS_KEY\"]\nAWS_DEFAULT_REGION = os.environ[\"AWS_DEFAULT_REGION\"]\n\nec2 = boto3.resource(\"ec2\")\necs = boto3.client(\n \"ecs\", aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY\n)\n\nlogging.basicConfig(format=\"%(asctime)s [%(levelname)s]: %(message)s\")\nlogging.getLogger().setLevel(logging.INFO)\n\nSUBNET_IDS = [\"subnet-bee9d9d9\"]\nSECURITY_GROUP_IDS = [\"sg-04ec8fa6e1d91d460\"]\n\nwith open(\"../utils/run.withagent.sh\", \"rb\") as f:\n txt = f.read()\n txt_flat = txt.replace(b\"diverse_world\", b\"flat_world\")\n run_sh_gz_b64 = b64encode(gzip.compress(txt)).decode(\"utf-8\")\n run_flat_sh_gz_b64 = b64encode(gzip.compress(txt_flat)).decode(\"utf-8\")\n\n\ndef register_task_definition(image_tag, task_name):\n image = f\"492338101900.dkr.ecr.us-west-1.amazonaws.com/craftassist:{image_tag}\"\n task_definition = ecs.register_task_definition(\n family=task_name,\n executionRoleArn=\"arn:aws:iam::492338101900:role/ecsTaskExecutionRole\",\n networkMode=\"awsvpc\",\n memory=\"8192\",\n cpu=\"4096\",\n containerDefinitions=[\n {\n \"name\": task_name,\n \"image\": image,\n \"logConfiguration\": {\n \"logDriver\": \"awslogs\",\n \"options\": {\n \"awslogs-group\": f\"/ecs/craftassist\",\n \"awslogs-region\": \"us-west-1\",\n \"awslogs-stream-prefix\": \"ecs\",\n },\n },\n \"portMappings\": [\n {\"hostPort\": 25565, \"protocol\": \"tcp\", \"containerPort\": 25565},\n {\"hostPort\": 2556, \"protocol\": \"tcp\", \"containerPort\": 2556},\n {\"hostPort\": 2557, \"protocol\": \"tcp\", \"containerPort\": 2557},\n {\"hostPort\": 3000, \"protocol\": \"tcp\", \"containerPort\": 3000},\n {\"hostPort\": 5000, \"protocol\": \"tcp\", \"containerPort\": 5000},\n {\"hostPort\": 9000, \"protocol\": \"tcp\", \"containerPort\": 9000},\n ],\n }\n ],\n requiresCompatibilities=[\"EC2\", \"FARGATE\"],\n )\n print(f\"Registered task definition: {task_definition}\")\n\n\ndef launch_instance(task=\"craftassist\", config=\"random\", debug=False, batch_id=None):\n \"\"\"Returns instance id (specifically, ECS task ARN) of a newly launched instance.\n\n Instance is not yet ready, and may not even have an ip address assigned!\n \"\"\"\n\n if config == \"diverse_world\":\n run_sh = run_sh_gz_b64\n elif config == \"flat_world\":\n run_sh = run_flat_sh_gz_b64\n elif config == \"random\":\n run_sh = random.choice([run_sh_gz_b64, run_flat_sh_gz_b64])\n else:\n raise ValueError(\"Bad config={}\".format(config))\n\n timestamp = datetime.now(timezone.utc).isoformat()\n env_var = [\n {\"name\": \"RUN_SH_GZ_B64\", \"value\": run_sh},\n {\"name\": \"AWS_ACCESS_KEY_ID\", \"value\": AWS_ACCESS_KEY_ID},\n {\"name\": \"AWS_SECRET_ACCESS_KEY\", \"value\": AWS_SECRET_ACCESS_KEY},\n {\"name\": \"TIMESTAMP\", \"value\": timestamp},\n {\n \"name\": \"SENTRY_DSN\",\n \"value\": os.environ.get(\"CRAFTASSIST_SENTRY_DSN\", \"\"),\n },\n {\"name\": \"CLOUDFLARE_TOKEN\", \"value\": os.getenv(\"CLOUDFLARE_TOKEN\")},\n {\"name\": \"CLOUDFLARE_ZONE_ID\", \"value\": os.getenv(\"CLOUDFLARE_ZONE_ID\")},\n ]\n if batch_id:\n env_var.append({\"name\": \"TURK_EXPERIMENT_ID\", \"value\": str(batch_id)})\n\n r = ecs.run_task(\n cluster=\"craftassist\",\n taskDefinition=task,\n count=1,\n launchType=\"FARGATE\",\n networkConfiguration={\n \"awsvpcConfiguration\": {\n \"subnets\": SUBNET_IDS,\n \"securityGroups\": SECURITY_GROUP_IDS,\n \"assignPublicIp\": \"ENABLED\",\n }\n },\n overrides={\n \"containerOverrides\": [\n {\n \"name\": task,\n \"environment\": env_var,\n }\n ]\n },\n )\n logging.info(\"Launched: {}\".format(r))\n return r[\"tasks\"][0][\"taskArn\"], timestamp\n\n\ndef is_instance_up(instance_id):\n try:\n x = ecs.describe_tasks(cluster=\"craftassist\", tasks=[instance_id])\n\n attachment_id = x[\"tasks\"][0][\"containers\"][0][\"networkInterfaces\"][0][\"attachmentId\"]\n attachment = next(y for y in x[\"tasks\"][0][\"attachments\"] if y[\"id\"] == attachment_id)\n\n eni = next(y for y in attachment[\"details\"] if y[\"name\"] == \"networkInterfaceId\")[\"value\"]\n ip = ec2.NetworkInterface(eni).private_ip_addresses[0][\"Association\"][\"PublicIp\"]\n\n s = socket.socket()\n s.settimeout(10)\n s.connect((ip, 25565))\n s.close()\n\n ping_cuberite.ping(ip, 25565, timeout=1)\n\n except:\n return False\n\n return True\n\n\ndef get_instance_ip(instance_id):\n try:\n x = ecs.describe_tasks(cluster=\"craftassist\", tasks=[instance_id])\n\n attachment_id = x[\"tasks\"][0][\"containers\"][0][\"networkInterfaces\"][0][\"attachmentId\"]\n attachment = next(y for y in x[\"tasks\"][0][\"attachments\"] if y[\"id\"] == attachment_id)\n\n eni = next(y for y in attachment[\"details\"] if y[\"name\"] == \"networkInterfaceId\")[\"value\"]\n ip = ec2.NetworkInterface(eni).private_ip_addresses[0][\"Association\"][\"PublicIp\"]\n except:\n raise ValueError(f\"This instance {instance_id} should have been up, but failed to get ip\")\n return ip\n\n\ndef request_instance(instance_num, image_tag, task_name, timeout=-1, batch_id=None):\n register_task_definition(image_tag, task_name)\n NUM_RETRIES = 100\n start_time = time.time()\n logging.info(f\"[ECS] Requesting {instance_num} instances from AWS, timeout: {timeout}\")\n cnt = 0\n instances_ids = []\n while cnt < instance_num and NUM_RETRIES > 0:\n try:\n instance_id, timestamp = launch_instance(\n task=task_name, config=\"flat_world\", debug=False, batch_id=batch_id\n )\n except Exception as e:\n print(e)\n NUM_RETRIES -= 1\n logging.info(\n f\"[ECS] Err on launching one ecs instance, discard this one. Remaining num retries: {NUM_RETRIES}\"\n )\n continue\n else:\n instances_ids.append(instance_id)\n cnt += 1\n finally:\n logging.info(f\"[ECS] Progress: {cnt}/{instance_num}\")\n\n def is_timeout(start_time, timeout):\n if timeout < 0:\n return False\n return (time.time() - start_time) > (timeout * 60)\n\n instance_status = [False] * instance_num\n while not all(instance_status) and not is_timeout(start_time, timeout):\n time.sleep(5)\n logging.info(\n f\"[ECS] Checking status of {instance_num} instances... Not ready, remaining time {timeout - (time.time() - start_time) // 60}\"\n )\n for i in range(instance_num):\n instance_status[i] = is_instance_up(instances_ids[i])\n\n up_instances_ips = []\n up_instances_ids = []\n for i in range(len(instance_status)):\n if is_instance_up(instances_ids[i]):\n up_instances_ids.append(instances_ids[i])\n up_instances_ips.append(get_instance_ip(instances_ids[i]))\n logging.info(\n f\"[ECS] {len(up_instances_ids)} instances have been launched. Request num: {instance_num}.\\nIP list: {up_instances_ips}\"\n )\n return up_instances_ips, up_instances_ids\n\n\ndef register_dashboard_subdomain(cf, zone_id, ip, subdomain):\n \"\"\"Registers a unique subdomain for craftassist.io\n that serves proxied HTTP content using cloudflare.\n Args:\n cf -- CloudFlare context with R/W permissions.\n zone_id -- zone ID used to locate DNS records.\n ip -- IP of the ECS container that runs dashboard.\n subdomain -- subdomain contains a unique identifier for this task run,\n which is the batch ID concatenated with the run number.\n \"\"\"\n # Check that DNS record does not already exist\n dns_record_exists = cf.zones.dns_records.get(\n zone_id, params={\"name\": \"{}.craftassist.io\".format(subdomain)}\n )\n if dns_record_exists:\n print(\"DNS record already exists for {}\".format(subdomain))\n return\n\n dns_record = {\"name\": subdomain, \"type\": \"A\", \"content\": ip, \"proxied\": True}\n try:\n r = cf.zones.dns_records.post(zone_id, data=dns_record)\n print(\"Registered IP {} at subdomain {}\".format(ip, subdomain))\n except Exception as e:\n raise e\n\n\ndef allocate_instances(\n instance_num, batch_id, image_tag, task_name, timeout=-1, cf_email=\"rebeccaqian@fb.com\"\n):\n instance_ips, instance_ids = request_instance(\n instance_num, image_tag, task_name, timeout, batch_id\n )\n if os.getenv(\"CLOUDFLARE_TOKEN\") and os.getenv(\"CLOUDFLARE_ZONE_ID\"):\n logging.info(\"registering subdomains on craftassist.io\")\n cloudflare_token = os.getenv(\"CLOUDFLARE_TOKEN\")\n zone_id = os.getenv(\"CLOUDFLARE_ZONE_ID\")\n cf = CloudFlare.CloudFlare(email=cf_email, token=cloudflare_token)\n dns_records = cf.zones.dns_records.get(zone_id)\n\n # Write the subdomains and batch IDs to input CSV for Mephisto\n # CSV file headers\n headers = [\"subdomain\", \"batch\"]\n with open(\"../../crowdsourcing/droidlet_static_html_task/data.csv\", \"w\") as fd:\n csv_writer = csv.writer(fd, delimiter=\",\")\n csv_writer.writerow(headers)\n for x in range(len(instance_ips)):\n ip = instance_ips[x]\n subdomain = \"dashboard-{}-{}\".format(batch_id, x)\n register_dashboard_subdomain(cf, zone_id, ip, subdomain)\n # Write record to Mephisto task input CSV\n csv_writer.writerow([subdomain, batch_id])\n return instance_ips, instance_ids\n\n\ndef free_ecs_instances(instance_ids):\n for instance_id in instance_ids:\n try:\n ecs.stop_task(\n cluster=\"craftassist\",\n task=instance_id,\n )\n except:\n pass\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--instance_num\", type=int, default=1, help=\"number of instances requested\"\n )\n parser.add_argument(\n \"--batch_id\",\n type=int,\n default=0,\n help=\"ID of the current batch, used to track which group of runs the task was run in\",\n )\n parser.add_argument(\n \"--user\", type=str, default=\"rebeccaqian@fb.com\", help=\"Email of the CloudFlare account\"\n )\n parser.add_argument(\n \"--image_tag\",\n type=str,\n help=\"The tag of docker image that will be used to spin up ecs instance\",\n )\n parser.add_argument(\n \"--task_name\", type=str, help=\"Task name of the ecs instance to be requested\"\n )\n args = parser.parse_args()\n instance_ips, instance_ids = request_instance(\n args.instance_num, args.image_tag, args.task_name, batch_id=\"0643\"\n )\n batch_id = args.batch_id\n # register subdomain to proxy instance IP\n if os.getenv(\"CLOUDFLARE_TOKEN\") and os.getenv(\"CLOUDFLARE_ZONE_ID\"):\n logging.info(\"registering subdomains on craftassist.io\")\n cloudflare_token = os.getenv(\"CLOUDFLARE_TOKEN\")\n zone_id = os.getenv(\"CLOUDFLARE_ZONE_ID\")\n cf = CloudFlare.CloudFlare(email=args.user, token=cloudflare_token)\n dns_records = cf.zones.dns_records.get(zone_id)\n\n # Write the subdomains and batch IDs to input CSV for Mephisto\n # CSV file headers\n headers = [\"subdomain\", \"batch\"]\n with open(\"../../crowdsourcing/droidlet_static_html_task/data.csv\", \"w\") as fd:\n csv_writer = csv.writer(fd, delimiter=\",\")\n csv_writer.writerow(headers)\n for x in range(len(instance_ips)):\n ip = instance_ips[x]\n subdomain = \"dashboard-{}-{}\".format(batch_id, x)\n register_dashboard_subdomain(cf, zone_id, ip, subdomain)\n # Write record to Mephisto task input CSV\n csv_writer.writerow([subdomain, batch_id])\n","sub_path":"droidlet/tools/hitl/utils/allocate_instances.py","file_name":"allocate_instances.py","file_ext":"py","file_size_in_byte":12635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"362800764","text":"'''\nМодуль asyncio доступен для предоставления базовой реализации цикла событий\nпример двух сопрограмм, одна из которых вызывает другую,\nпроизводящую какие-то затратные вычисления\n\nПрименяется устаревший механизм сопрограмм,\nоснованных на генераторах - должен быть применён декоратор @asyncio.coroutine \n'''\nimport asyncio\n\"\"\"\nбудет предупреждение:\nDeprecationWarning: \"@coroutine\" decorator is deprecated since Python 3.8,\nuse \"async def\" instead\n\"\"\"\n@asyncio.coroutine\ndef time_consuming_computation(x):\n print('Computing {0} ** 2...'.format(x))\n yield from asyncio.sleep(1)\n return x ** 2\n\n@asyncio.coroutine\ndef process_data(x):\n result = yield from time_consuming_computation(x)\n print('{0} ** 2 = {1}'.format(x, result))\n\n\nif __name__ == '__main__':\n \"\"\"Функция get_event_loop модуля asyncio возвращает объект цикла событий\"\"\"\n loop = asyncio.get_event_loop()\n \"\"\"метод run_until_complete используется для запуска сопрограммы\"\"\"\n loop.run_until_complete(process_data(238))\n loop.close()\n","sub_path":"Demo-itmo/mod_thread/asyncDemo/Demo@asyncio_coroutine.py","file_name":"Demo@asyncio_coroutine.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"26328297","text":"import logging\nfrom common import errfunctions\n\nfrom PyQt5 import QtCore\nfrom PyQt5.QtCore import Qt, QEvent\nfrom PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QAbstractItemView\n\nfrom common.functions import isHighDef\nfrom database.database import DBModelCommon\nfrom widgets.layoutfunctions import saveState, loadColumnLayout\nfrom widgets.messageboxes import JNothingSelectedMessage\nfrom widgets.widgets import JPushButton, JScreenTitle, labelAbove, JDateEdit, JLineEdit, JCheckBox, JComboBox, JTableView\n\n\nclass BasePage(QWidget):\n def __init__(self, title, parent, showTitleLabel=True):\n super().__init__(parent)\n\n self.title = title\n\n # Add right side buttons to sideBar\n self.sidebarLayout = QVBoxLayout()\n self.sidebarLayout.setContentsMargins(15, 24, 15, 15)\n\n # Add filter lineEdits using labelAbove to filterLayout\n self.filterLayout = QHBoxLayout()\n if isHighDef():\n self.filterLayout.setSpacing(15)\n\n # Add main contents (probably a grid) to mainLayout\n self.mainLayout = QVBoxLayout()\n self.mainLayout.addLayout(self.filterLayout)\n\n self.outerLayout = QHBoxLayout()\n self.outerLayout.setContentsMargins(10, 0, 0, 0)\n self.outerLayout.addLayout(self.mainLayout)\n self.outerLayout.addLayout(self.sidebarLayout)\n\n self.outerOuterLayout = QVBoxLayout()\n self.outerOuterLayout.setContentsMargins(0, 0, 0, 10)\n if showTitleLabel:\n self.lMain = JScreenTitle(title, self)\n self.outerOuterLayout.addWidget(self.lMain)\n self.outerOuterLayout.addLayout(self.outerLayout)\n self.setLayout(self.outerOuterLayout)\n\n self.setFilterActions = []\n self.filteringEnabled = True\n\n self.mainGrid = None\n\n self.window().installEventFilter(self)\n\n def eventFilter(self, watched, event):\n if watched == self.window() and event.type() == QEvent.Close:\n self.saveState()\n\n return self.parent().eventFilter(watched, event)\n\n def loadColumnLayout(self):\n if not loadColumnLayout(self.title, self.mainGrid.header()):\n self.loadDefaultColumnLayout()\n\n def loadDefaultColumnLayout(self):\n errfunctions.print_err(\"No default column layout found for {0}. Implement one by adding a method 'loadDefaultColumnLayout(self)' to the {0} page\".format(self.title))\n\n def saveState(self):\n saveState(self.title, self.mainGrid.header())\n\n def addFilter(self, label, placeholderText, toolTip, columnIndex, width=None, container=None):\n lineEdit = JLineEdit(self)\n lineEdit.setPlaceholderText(placeholderText)\n lineEdit.textChanged.connect(self.invalidateFilter)\n if width:\n lineEdit.setFixedWidth(width)\n\n layout = labelAbove(label, lineEdit, toolTip)\n if container is not None:\n container.addLayout(layout)\n else:\n self.filterLayout.addLayout(layout)\n self.setFilterActions.append(lambda: self.setLineEditFilter(columnIndex, lineEdit))\n\n return lineEdit\n\n def addDateFilter(self, label, placeholderText, toolTip, columnIndex, width=None, container=None):\n dateEdit = JDateEdit(self)\n dateEdit.lineEdit.setPlaceholderText(placeholderText)\n dateEdit.lineEdit.textChanged.connect(self.invalidateFilter)\n if width:\n dateEdit.setFixedWidth(width)\n\n layout = labelAbove(label, dateEdit, toolTip)\n if container is not None:\n container.addLayout(layout)\n else:\n self.filterLayout.addLayout(layout)\n self.setFilterActions.append(lambda: self.setLineEditFilter(columnIndex, dateEdit.lineEdit))\n\n return dateEdit\n\n def addComboNonTypeFilter(self, label, defaultText, list, toolTip, columnIndex, typeIsAbbreviation=True, width=None,\n container=None):\n combo = JComboBox(self)\n combo.addItem(defaultText, None)\n combo.insertSeparator(1)\n\n for i, each in enumerate(list):\n combo.addItem(\"{}\".format(each), None)\n combo.setItemData(i, i, Qt.UserRole)\n\n combo.currentIndexChanged.connect(self.invalidateFilter)\n if width:\n combo.setFixedWidth(width)\n\n layout = labelAbove(label, combo, toolTip)\n if container is not None:\n container.addLayout(layout)\n else:\n self.filterLayout.addLayout(layout)\n\n if typeIsAbbreviation:\n self.setFilterActions.append(lambda: self.setAbbreviatedComboFilter(columnIndex, combo))\n else:\n self.setFilterActions.append(lambda: self.setFullComboFilter(columnIndex, combo))\n\n return combo\n\n def addComboFilter(self, label, defaultText, types, toolTip, columnIndex, typeIsAbbreviation=True, width=None, container=None):\n combo = JComboBox(self)\n combo.addItem(defaultText, None)\n combo.insertSeparator(1)\n\n for i, type in enumerate(types, 2):\n if typeIsAbbreviation:\n combo.addItem(\"{}({})\".format(type.type, type.description[1:]), type)\n else:\n combo.addItem(\"{} ({})\".format(type.type, type.description), type)\n combo.setItemData(i, type.type, Qt.UserRole)\n\n combo.currentIndexChanged.connect(self.invalidateFilter)\n if width:\n combo.setFixedWidth(width)\n\n layout = labelAbove(label, combo, toolTip)\n if container is not None:\n container.addLayout(layout)\n else:\n self.filterLayout.addLayout(layout)\n\n if typeIsAbbreviation:\n self.setFilterActions.append(lambda: self.setAbbreviatedComboFilter(columnIndex, combo))\n else:\n self.setFilterActions.append(lambda: self.setFullComboFilter(columnIndex, combo))\n\n return combo\n\n def addCheckboxFilter(self, label, toolTip, columnIndex, container=None):\n checkBox = JCheckBox(label, self)\n checkBox.setToolTip(toolTip)\n checkBox.stateChanged.connect(self.invalidateFilter)\n\n if container is not None:\n container.addWidget(checkBox)\n else:\n self.filterLayout.addWidget(checkBox)\n\n self.setFilterActions.append(lambda: self.setCheckBoxFilter(columnIndex, checkBox))\n return checkBox\n\n def createGrid(self, model, sort=True):\n if self.mainGrid is not None:\n raise Exception(\"Multiple grids not currently supported due to layout saving\")\n\n mainGrid = JTableView(self, wasJTreeView=True)\n self.mainGrid = mainGrid\n self.mainGrid.setAlternatingRowColors(True)\n self.mainGrid.setModel(model)\n if sort:\n DBModelCommon.selectAndSortByColumn(mainGrid, 0, QtCore.Qt.AscendingOrder)\n self.mainGrid.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.mainGrid.doubleClicked.connect(self.gridDoubleClicked)\n self.mainGrid.setContextMenuPolicy(Qt.CustomContextMenu)\n self.mainGrid.customContextMenuRequested.connect(self.openContextMenu)\n\n def addGridAction(self, buttonText, editAction, notSelectedMessage):\n btnEdit = JPushButton(buttonText, self)\n btnEdit.clicked.connect(lambda: self.actionIfSelected(editAction, notSelectedMessage))\n\n return btnEdit\n\n def actionIfSelected(self, editAction, notSelectedMessage):\n if not self.checkSelected(notSelectedMessage):\n return\n\n editAction(self.mainGrid.selectedIndexes()[0])\n\n def checkSelected(self, notSelectedMessage):\n if len(self.mainGrid.selectedIndexes()) < 1:\n JNothingSelectedMessage(notSelectedMessage, self).exec()\n return False\n\n return True\n\n def invalidateFilter(self):\n for setFilterAction in self.setFilterActions:\n setFilterAction()\n\n self.filterProxyModel.invalidateFilter()\n\n def setLineEditFilter(self, column, lineEdit):\n self.filterProxyModel.filterValues[column] = lineEdit.text().strip().upper()\n\n def setAbbreviatedComboFilter(self, column, combo):\n self.filterProxyModel.filterValues[column] = combo.currentText()[0].upper() if combo.currentIndex() != 0 else None\n\n def setFullComboFilter(self, column, combo):\n self.filterProxyModel.filterValues[column] = combo.currentText().upper()[combo.currentText().find(\"(\") + 1:-1] if combo.currentIndex() != 0 else None\n\n def setCheckBoxFilter(self, column, checkBox):\n self.filterProxyModel.filterValues[column] = str(checkBox.isChecked())\n\n # Sql model\n @staticmethod\n def prefixSql(columnName, filterValue):\n return \" {} LIKE '{}%' \".format(columnName, filterValue) if filterValue else \"\"\n\n @staticmethod\n def partialSql(columnName, filterValue):\n return \" {} LIKE '%{}%' \".format(columnName, filterValue) if filterValue else \"\"\n\n @staticmethod\n def exactSql(columnName, filterValue):\n return \" {} = '{}' \".format(columnName, filterValue) if filterValue else \"\"\n\n @staticmethod\n def inSql(columnName, filterValues):\n return \" {} IN ({}) \".format(columnName, filterValues) if filterValues else \"\"\n\n @staticmethod\n def lessThanOrEqualSql(columnName, date):\n return \" {} <= '{}' \".format(columnName, date) if date else \"\"\n\n @staticmethod\n def ifGreaterThan2(string):\n if len(string) > 2:\n return string\n else:\n return \"\"\n","sub_path":"widgets/basepage.py","file_name":"basepage.py","file_ext":"py","file_size_in_byte":9457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"306830905","text":"# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Command to add IAM policy binding for an organization.\"\"\"\n\nimport httplib\n\nfrom googlecloudsdk.api_lib.util import http_retry\nfrom googlecloudsdk.calliope import base\nfrom googlecloudsdk.command_lib.iam import iam_util\nfrom googlecloudsdk.command_lib.organizations import flags\nfrom googlecloudsdk.command_lib.organizations import orgs_base\n\n\n@base.ReleaseTracks(\n base.ReleaseTrack.GA, base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA)\nclass AddIamPolicyBinding(orgs_base.OrganizationCommand):\n \"\"\"Add IAM policy binding for an organization.\n\n Adds a policy binding to the IAM policy of an organization,\n given an organization ID and the binding.\n \"\"\"\n\n detailed_help = iam_util.GetDetailedHelpForAddIamPolicyBinding('organization',\n '123456789')\n\n @staticmethod\n def Args(parser):\n flags.IdArg('to which you want to add a binding').AddToParser(parser)\n iam_util.AddArgsForAddIamPolicyBinding(parser, 'id',\n 'cloudresourcemanager.organizations')\n\n @http_retry.RetryOnHttpStatus(httplib.CONFLICT)\n def Run(self, args):\n messages = self.OrganizationsMessages()\n\n get_policy_request = (\n messages.CloudresourcemanagerOrganizationsGetIamPolicyRequest(\n organizationsId=args.id,\n getIamPolicyRequest=messages.GetIamPolicyRequest()))\n policy = self.OrganizationsClient().GetIamPolicy(get_policy_request)\n\n iam_util.AddBindingToIamPolicy(messages, policy, args.member, args.role)\n\n set_policy_request = (\n messages.CloudresourcemanagerOrganizationsSetIamPolicyRequest(\n organizationsId=args.id,\n setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy)))\n\n return self.OrganizationsClient().SetIamPolicy(set_policy_request)\n","sub_path":"google-cloud-sdk/lib/surface/organizations/add_iam_policy_binding.py","file_name":"add_iam_policy_binding.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"138923717","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 27 19:36:20 2020\n\n@author: jisuk\n\"\"\"\n\n#%% import module\n\nimport os\nimport sys\nimport xml.etree.ElementTree as Et\nfrom xml.etree.ElementTree import Element, ElementTree\nimport tensorflow as tf\n\nimport config as cfg\n\n#%% classes\n\nclass DatasetTool:\n def __init__(self):\n self.imagesPath = os.path.join(cfg.VOCdatasetConfig['rootDir'], cfg.VOCdatasetConfig['imageFolder'])\n \n self.textFileFolder = cfg.VOCdatasetConfig['textFileFolder']\n self.trainCasesPath = cfg.VOCdatasetConfig['trainCasesPath']\n self.valCasesPath = cfg.VOCdatasetConfig['valCasesPath']\n \n \n def splitDataset(self,val = 0.2):\n ann_root, ann_dir, ann_files = next(os.walk(self.imagesPath))\n \n i = 0\n valBatch = 1/ val\n trainText = open(os.path.join(self.textFileFolder,\"trainNames.txt\"),'w+')\n valText = open(os.path.join(self.textFileFolder,\"valNames.txt\"),'w+')\n for file in ann_files:\n file = file.split('.')\n file = file[0]\n \n if(i > valBatch):\n i = 0\n valText.write(file+\"\\n\")\n else:\n trainText.write(file+\"\\n\")\n \n i = i + 1\n \n trainText.close()\n valText.close()\n \n\nclass PascalVOC2007:\n \n def __init__(self):\n \n self.RootPath = cfg.VOCdatasetConfig['rootDir']\n self.imageFolderPath = cfg.VOCdatasetConfig['imageFolder']\n self.imageExtension = cfg.VOCdatasetConfig['imageExtension']\n self.annotationFolderPath = cfg.VOCdatasetConfig['annotationFolder']\n self.annotationExtension = cfg.VOCdatasetConfig['annotationExtension']\n \n self.imageFolderPath = os.path.join(self.RootPath,self.imageFolderPath)\n self.annotationFolderPath = os.path.join(self.RootPath,self.annotationFolderPath)\n \n self.classNames = cfg.classNames\n self.textFileFolder = cfg.VOCdatasetConfig['textFileFolder']\n \n self.trainCasesPath = cfg.VOCdatasetConfig['trainCasesPath']\n self.valCasesPath = cfg.VOCdatasetConfig['valCasesPath']\n \n \n def getImagePath(self, imageName):\n return os.path.join(self.annotationFolderPath, imageName+self.imageExtension)\n \n \n def getAnnotationPath(self, imageName):\n return os.path.join(self.annotationFolderPath,imageName+self.annotationExtension)\n \n \n def getAnnotation(self, annotationPath, pathtype):\n if(pathtype == 'fileName'):\n annotationPath = self.getAnnotationPath(annotationPath)\n \n result = dict()\n \n xml = open(annotationPath,'r')\n tree = Et.parse(xml)\n root = tree.getroot()\n \n result['filename'] = root.find(\"filename\").text\n \n size = root.find(\"size\") \n result['width'] = size.find(\"width\").text\n result['height'] = size.find(\"height\").text\n result['channels'] = size.find(\"depth\").text\n \n \n objects = root.findall(\"object\")\n result['objects'] = []\n for obj in objects:\n \n objInfo = dict()\n \n objInfo['name'] = obj.find(\"name\").text\n \n bndbox = obj.find(\"bndbox\")\n objInfo['xmin'] = bndbox.find(\"xmin\").text\n objInfo['ymin'] = bndbox.find(\"ymin\").text\n objInfo['xmax'] = bndbox.find(\"xmax\").text\n objInfo['ymax'] = bndbox.find(\"ymax\").text\n \n result['objects'].append(objInfo)\n \n return result\n \n \n def XML2StrLine(self, objDict):\n string = objDict['filename']\n \n for bndbox in objDict['objects']:\n string = string +\" \" + str(bndbox['xmin']) + \" \" + str(bndbox['ymin']) + \" \" + str(bndbox['xmax']) + \" \" + str(bndbox['ymax']) + \" \" + str(self.classNames[bndbox['name']])\n \n return string\n \n def MakeTextFiles(self):\n trainNames = open(os.path.join(self.textFileFolder,\"trainNames.txt\"),'r')\n trainText = open(os.path.join(self.textFileFolder,\"train.txt\"),'w+')\n \n for line in trainNames.readlines():\n line = line.strip().split(' ')\n \n filename = line[0]\n annotationDict = self.getAnnotation(filename,'fileName')\n string = self.XML2StrLine(annotationDict)\n trainText.write(string+\"\\n\")\n \n trainText.close()\n \n \n valNames = open(os.path.join(self.textFileFolder,\"valNames.txt\"),'r')\n valText = open(os.path.join(self.textFileFolder,\"val.txt\"),'w+')\n \n for line in valNames.readlines():\n line = line.strip().split(' ')\n \n filename = line[0]\n annotationDict = self.getAnnotation(filename,'fileName')\n string = self.XML2StrLine(annotationDict)\n valText.write(string+\"\\n\")\n \n valText.close()\n \n \n\n#%% main code\n\n#d = DatasetTool()\n#d.splitDataset(val=0.2)\n\n \n \n \n \n \n \n \n \n \n ","sub_path":"Object Detection/YOLOv1/PascalVOC2007Parse.py","file_name":"PascalVOC2007Parse.py","file_ext":"py","file_size_in_byte":5164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"413302744","text":"\"\"\"\r\n------------------------------\r\nBEHAVE PARALLEL FEATURE RUNNER\r\n------------------------------\r\nThis module provides functionality to run Behave features in parallel.\r\nThe amount of features that will run in parallel is determined by\r\nMAX_WORKERS environment variable, set to a default value when not specified.\r\n Command line usage:\r\n behave_parallel_runner \r\n Accepted args:\r\n \r\n * --tags=some_tag (same as 'behave' command)\r\n \r\n * Single path to a features directory\r\n * Single path to a feature file\r\n * Multiple paths to different feature files\r\n Usage examples:\r\n * behave_parallel_runner --tags=test ui_tests/admin/features\r\n * behave_parallel_runner --tags=test ui_tests/admin/features/health.feature\r\n * behave_parallel_runner --tags=test ui_tests/admin/features/health.feature\r\n ui_tests/admin/features/apigee.feature\r\n\"\"\"\r\nimport copy\r\nimport gc\r\nimport os\r\nimport subprocess\r\nimport sys\r\nimport tempfile\r\nimport time\r\nfrom datetime import datetime\r\nfrom pytz import timezone\r\n\r\nfrom pteromyini.core.runner.feature_worker import FeatureWorker\r\n\r\n\r\nclass __SubprocessRunner:\r\n \"\"\"\r\n main\r\n \"\"\"\r\n\r\n def __init__(self, path, rerun_file='rerun.feature', max_workers=3, periodicity_progress_log=60):\r\n self.rerun_file = rerun_file\r\n self.MAX_WORKERS = max_workers\r\n self.active_workers = []\r\n self.base_command = 'behave --junit {} {} {} {}'\r\n self.tags = []\r\n self.feature_args = []\r\n self.temp_run_id = time.strftime(\"%Y%m%d_%H-%M-%S\")\r\n self.temp_file_counter = 0\r\n self.feature_path = path\r\n self.periodicity_progress_log = periodicity_progress_log\r\n\r\n self.log_path = os.path.join('logs', self.temp_run_id)\r\n if not os.path.exists(self.log_path):\r\n os.makedirs(self.log_path)\r\n\r\n def run(self):\r\n \"\"\"\r\n Behave Parallel Runner main process\r\n \"\"\"\r\n print('\\nBEHAVE PARALLEL RUNNER\\n')\r\n\r\n start_date = datetime.now(timezone('US/Eastern'))\r\n\r\n self._log('Execution started @ {} EST'.format(\r\n datetime.now(timezone('US/Eastern')).strftime('%H:%M:%S')))\r\n\r\n self._set_max_workers()\r\n self._parse_args()\r\n self._unify_tags()\r\n self.worker_controller(self.get_task_list())\r\n self.create_rerun_feature()\r\n end_date = datetime.now(timezone('US/Eastern'))\r\n took = time.strftime('%Hh %Mm %Ss', time.gmtime((end_date - start_date).total_seconds()))\r\n\r\n self._log('Execution finished @ {} EST'.format(\r\n datetime.now(timezone('US/Eastern')).strftime('%H:%M:%S')))\r\n self._log('Took {}'.format(took))\r\n\r\n def _set_max_workers(self):\r\n \"\"\"\r\n Sets the max amount of workers available for the current execution\r\n Default value will be used if MAX_WORKERS environment variable is not specified\r\n \"\"\"\r\n global MAX_WORKERS\r\n MAX_WORKERS = int(os.getenv('BEHAVE_MAX_WORKERS', self.MAX_WORKERS))\r\n\r\n self._log('Enabled {} workers'.format(MAX_WORKERS))\r\n\r\n def _log(self, msg):\r\n \"\"\"\r\n Log a message into the behave parallel runner default output\r\n :param msg:\r\n A string representing the message to _log\r\n \"\"\"\r\n _time = datetime.now(timezone('US/Eastern')).strftime('%H:%M:%S')\r\n print('[behave-parallel-runner @ {}] {}'.format(_time, msg))\r\n\r\n def _parse_args(self):\r\n \"\"\"\r\n Parses the arguments provided to the behave parallel runner script\r\n \"\"\"\r\n self._log('Parsing script arguments')\r\n args = copy.copy(sys.argv)\r\n args.pop(0) # Remove Python file path arg\r\n\r\n for arg in args:\r\n if arg[:7] == '--tags=':\r\n self.tags.append(arg)\r\n else:\r\n self.feature_args.append(arg)\r\n\r\n def _unify_tags(self):\r\n \"\"\"\r\n Converts the tags list to a single string\r\n \"\"\"\r\n if self.tags:\r\n tags_as_str = ''\r\n self._log('Unifying tags')\r\n\r\n for tag in self.tags:\r\n tags_as_str = ' '.join((tags_as_str, tag))\r\n\r\n self.tags = tags_as_str.strip()\r\n else:\r\n self.tags = ''\r\n\r\n def get_task_list(self):\r\n \"\"\"\r\n Scans a features directory for feature files\r\n :returns:\r\n A list of feature files (relative path & filename)\r\n \"\"\"\r\n feature_list = []\r\n\r\n for root, directories, filenames in os.walk(self.feature_path):\r\n for file in filenames:\r\n if file.endswith('.feature'):\r\n feature_list.append(os.path.join(root, file))\r\n\r\n return feature_list\r\n\r\n def get_rerun_path(self):\r\n path = os.path.join('temp_parallel_runner', self.temp_run_id, 'rerun')\r\n if not os.path.exists(path):\r\n os.makedirs(path)\r\n return path\r\n\r\n def _create_temp_log_file(self, file_name):\r\n \"\"\"\r\n Creates a unique temporary file\r\n :param file_name:\r\n A string representing the temporary file name prefix\r\n :returns:\r\n A pair (fd, name) where fd is the file descriptor returned by os.open,\r\n and name is the filename\r\n \"\"\"\r\n dir_name = os.path.join(self.log_path, 'temp')\r\n if not os.path.exists(dir_name):\r\n os.makedirs(dir_name)\r\n\r\n file_descriptor, file_name = tempfile.mkstemp(prefix=f'{file_name}_$run_', dir=os.path.abspath(dir_name),\r\n suffix='.tmp')\r\n return file_descriptor, file_name\r\n\r\n def _trigger_feature(self, feature_path):\r\n \"\"\"\r\n Triggers a feature execution\r\n :param feature_path:\r\n A string representing the feature (relative path & filename)\r\n \"\"\"\r\n self._log('Triggering feature: \"{}\"'.format(feature_path))\r\n\r\n worker = FeatureWorker(feature_path)\r\n\r\n log_file_descriptor, log_file_name = self._create_temp_log_file(worker.file_name)\r\n\r\n outfile = os.path.join(self.get_rerun_path(), f'rerun_{worker.file_name}{self.get_next_temp_file_index()}.features')\r\n format_rerun = f'--format rerun --outfile {outfile}'\r\n\r\n cmd = self.base_command.format(self.tags, \" \".join(self.feature_args), feature_path, format_rerun)\r\n self._log(f'Run feature cmd: \"{cmd}\"')\r\n process = subprocess.Popen(cmd,\r\n shell=True,\r\n stdout=log_file_descriptor,\r\n stderr=log_file_descriptor)\r\n\r\n worker.log_file_descriptor = log_file_descriptor\r\n worker.log_file_name = log_file_name\r\n worker.subprocess = process\r\n\r\n self.active_workers.append(worker)\r\n\r\n def save_log_file(self, log_file_name):\r\n with open(log_file_name, mode='r', encoding='utf8', errors='ignore') as log_file:\r\n text_log = log_file.read()\r\n if text_log.find('Failing scenarios:') < 0:\r\n file_name_result = ''\r\n else:\r\n file_name_result = '_FAILED'\r\n file_name = os.path.basename(log_file_name).split('_$')[0]\r\n file_dir = os.path.abspath(self.log_path)\r\n file_name = f'{file_name}{file_name_result}_{self.get_next_temp_file_index()}.txt'\r\n file_name = os.path.join(file_dir, file_name)\r\n with open(file_name, 'w+', encoding='utf8') as file:\r\n file.write(text_log)\r\n\r\n def worker_controller(self, feature_list):\r\n last_time_progress_log = time.time()\r\n\r\n while True:\r\n for worker in self.active_workers:\r\n if worker.subprocess.poll() is not None:\r\n # If the worker subprocess finished\r\n # Remove worker\r\n self._log(f'Releasing worker: \"{worker.name}\" ({worker.run_time/60:.2f} min)')\r\n self.active_workers.remove(worker)\r\n self.save_log_file(worker.log_file_name)\r\n # Print feature log\r\n\r\n # Delete worker and call garbage collector\r\n del worker\r\n gc.collect()\r\n\r\n if len(feature_list) > 0 and len(self.active_workers) < MAX_WORKERS:\r\n # If there's pending features\r\n # And there's an available worker\r\n # Trigger another feature\r\n feature = feature_list.pop(0)\r\n self._trigger_feature(feature)\r\n\r\n if len(feature_list) == 0 and len(self.active_workers) == 0:\r\n # If no feature's pending\r\n # And there are no active workers\r\n # Terminate the execution\r\n break\r\n\r\n if time.time() - last_time_progress_log > self.periodicity_progress_log:\r\n last_time_progress_log = time.time()\r\n self._log('---------------------------------------------')\r\n self._log('IN PROGRESS:')\r\n for worker in self.active_workers:\r\n self._log(f'\\t\"{worker.name}\" ({worker.run_time/60:.2f} min)')\r\n self._log('---------------------------------------------')\r\n time.sleep(2)\r\n\r\n self._log('All workers has completed')\r\n\r\n def create_rerun_feature(self):\r\n if not self.rerun_file:\r\n return\r\n path = self.get_rerun_path()\r\n files = os.listdir(path)\r\n data = []\r\n for file_name in files:\r\n file_name = os.path.join(path, file_name)\r\n with open(file_name, 'r') as file:\r\n for line in file:\r\n line = line.strip()\r\n if line and line[0] != '#':\r\n data.append(line)\r\n with open(self.rerun_file, 'w+') as file:\r\n file.write(f'# -- RERUN: {str(len(data))} failing scenarios during last test run.\\n')\r\n for d in data:\r\n file.write(d + '\\n')\r\n\r\n def get_next_temp_file_index(self):\r\n self.temp_file_counter += 1\r\n return str(self.temp_file_counter)\r\n\r\n","sub_path":"custom_library/pteromyini/pteromyini/core/runner/__subprocess_runner.py","file_name":"__subprocess_runner.py","file_ext":"py","file_size_in_byte":10285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"571704392","text":"#! /usr/bin/python\n# Sniff DNS traffic\nfrom scapy.all import *\nimport sys\n\ntry:\n interface = raw_input(\"[*] Enter desired interface eth0/eth1: \")\nexcept KeyboardInterrupt:\n print(\"[*] Exit\")\n sys.exit(1)\n\n\n\ndef monitor_callback(pkt):\n print(pkt)\n \nsniff(iface=interface, prn=monitor_callback, filter=\"tcp\", store=0)\nprint(\"[*] Exit\")\n","sub_path":"scapy_scripts/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"239247104","text":"#\n# @lc app=leetcode.cn id=17 lang=python3\n#\n# [17] 电话号码的字母组合\n#\n\n# @lc code=start\nclass Solution:\n def letterCombinations(self, digits: str) -> List[str]:\n if not digits: return []\n\n keyboard = {1: [], \n 2: ['a', 'b', 'c'], 3: ['d', 'e', 'f'], \n 4: ['g', 'h', 'i'], 5: ['j', 'k', 'l'], \n 6: ['m', 'n', 'o'], 7: ['p', 'q', 'r', 's'], \n 8: ['t', 'u', 'v'], 9: ['w', 'x', 'y', 'z']}\n\n def helper(index, maxlen, cur):\n if index == maxlen+1:\n res.append(cur)\n return\n \n for letter in keyboard[int(digits[index])]:\n helper(index+1, maxlen, cur+letter)\n\n cur = ''\n res = []\n helper(0, len(digits)-1, cur)\n return res\n# @lc code=end\n\n","sub_path":"Week_03/实战题目/17.电话号码的字母组合.py","file_name":"17.电话号码的字母组合.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"159583677","text":"import itertools\nfrom django.db import models\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.validators import RegexValidator\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.urlresolvers import reverse\nfrom django.utils.text import slugify\nfrom django.db.models import Q\nfrom django.db import transaction\n\nfrom model_utils.models import TimeStampedModel, StatusModel\nfrom django_extensions.db.models import TitleDescriptionModel\nfrom tags.models import Tag\n# from geopy.geocoders import GoogleV3\nfrom hashid_field import HashidAutoField\n\nfrom .choices import *\nimport itineraries.choices as itin_choices\nfrom .utils import capitalize, is_english, gps_to_address, addr_to_dict, google_place_info, similar\nfrom .merge import merge_objects\nfrom .scrape import scrapeRatings\nfrom core.models import Trip, Image\nfrom addresses.models import AddressField\n# from itineraries.models import ItineraryItem, ItineraryItemImage\n\n\n##########################################\n### CONTACT Class (abstract) ###\n##########################################\nclass ContactModel(models.Model):\n\taddress = AddressField(\n\t\ton_delete=models.CASCADE, \n\t\tnull=True,\n\t\tblank=True)\n\twebsite = models.URLField(_('website'), blank=True)\n\temail = models.EmailField(_('email address'), blank=True)\n\t# phone_regex = RegexValidator(regex=r'^\\+?1?\\d{9,15}$', message=\"Phone/Fax number must be entered in the format: '+999999999'. Up to 15 digits allowed.\")\n\tphone_regex = RegexValidator(regex=r'^\\+?1?[ 0-9-]{9,18}$', message=\"Phone/Fax number must be entered with a '+' sign upfront followed by numbers and spaces only. Up to 15 digits allowed (18 including space/dash).\")\n\tphone = models.CharField(_('phone'), max_length=20, validators=[phone_regex], blank=True) # validators should be a list\n\tfax = models.CharField(_('fax'), max_length=20, validators=[phone_regex], blank=True) # validators should be a list\n\n\tclass Meta:\n\t\tabstract = True\n\n\t# Returns a shortened representation of locality string (up to the set limit of 10 per component)\n\t@property\n\tdef locality_short(self):\n\t\toutput = ''\t\n\t\tif self.address:\n\t\t\tlimit = 10\n\t\t\td = addr_to_dict(self.address)\n\t\t\tif d['locality']:\n\t\t\t\tdata = d['locality']\n\t\t\t\toutput = output + data[:limit] if len(data) > limit else data + ', '\n\t\t\tif d['state_code']:\n\t\t\t\tdata = d['state_code']\n\t\t\t\toutput = output + data + ', '\n\t\t\telif d['state']:\n\t\t\t\tdata = d['state']\n\t\t\t\toutput = output + data[:limit] if len(data) > limit else data + ', '\n\t\t\tif d['country_code']:\n\t\t\t\tdata = d['country_code']\n\t\t\t\toutput = output + data + ', '\n\t\t\telif d['country']:\n\t\t\t\tdata = d['country']\n\t\t\t\toutput = output + data[:limit] if len(data) > limit else data + ', '\n\t\t\tif d['postal_code']:\n\t\t\t\tdata = d['postal_code']\n\t\t\t\toutput = output + data \n\t\treturn output\n\n\n\tdef set_addr_from_gps(self, gps): # gps input should be in a str format 'lat, lng'\n\t\taddr = gps_to_address(gps)\t\n\t\tif addr:\n\t\t\tself.address = addr\n\n\tdef if_same_addr(self, addr):\n\t\tif addr_to_dict(self.address) == addr_to_dict(addr):\n\t\t\treturn True\n\t\treturn False\n\n\n\n\n###################################\n### PLACE Class ###\n###################################\nclass Place(ContactModel, TimeStampedModel, StatusModel, TitleDescriptionModel):\n\t# Inherited fields: title, description,created, modified, status, status_changed, website, email, address, phone, fax\n\tid = HashidAutoField(primary_key=True, min_length=10, salt=\"Place Salt 963819\")\n\tslug = models.SlugField(max_length=255) #default max-length 50\n\t# id_regex = RegexValidator(regex=r'^[A-Za-z0-9_-]{1,255}$', message=\"Must be a valid Google place_id\")\n\t# google_id = models.CharField(_('google place_id'), \n\t# \tmax_length=255,\n\t# \tblank=True,\n\t# \tvalidators=[id_regex],\n\t# \thelp_text=_('Google Places database unique identifier'))\n\tname_local = models.CharField(_('local name'), \n\t\tblank=True,\n\t\tmax_length=255)\n\talias_english = models.TextField(_('english alias names'), \n\t\tblank=True,\n\t\thelp_text=_('Keeps track of a list of English alias names, seperated by \",\"'))\n\talias_local = models.TextField(_('local alias names'), \n\t\tblank=True,\n\t\thelp_text=_('Keeps track of a list of local alias names, seperated by \",\"'))\n\tcategories = models.ManyToManyField('places.PlaceCategory', \n\t\trelated_name='places', \n\t\tblank=True,\n\t\thelp_text=_('all applicable categories'))\n\tparent = models.ForeignKey('self', \n\t\trelated_name=\"children\", \n\t\ton_delete=models.SET_NULL, # deleion of the ForeignKey object doesn't cascade to the related object \n\t\tnull=True, \n\t\tblank=True)\n\tlast_approved = models.DateTimeField(_('last approved'),\n\t\tblank=True, \n\t\tnull=True, \n\t\thelp_text=_('The last time any change was approved. Compare to the modified field will tell if there is any new unapproved change.'))\n\tSTATUS = PLACE_STATUS_CHOICES\n\t# tags = TagField()\n\n\tclass Meta:\n\t\tunique_together = ('title', 'address',)\n\t\tordering = ['title']\n\n\tdef __str__(self):\n\t\tloc = ''\n\t\tif self.address and self.address.locality:\n\t\t\tif self.address.locality.name:\n\t\t\t\tloc += ', ' + self.address.locality.name \n\t\t\tif self.address.locality.state.country.name:\n\t\t\t\tloc += ', ' + self.address.locality.state.country.name\n\t\treturn self.title + loc\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(Place, self).__init__(*args, **kwargs)\n\t\t# keep a copy of the original value so we can check upon if changed when saving later\n\t\tself.__original_title = self.title\n\n\tdef save(self, *args, **kwargs):\t\n\t\t### TBD ###: shouldn't need to update slug upon every save ... only need to do it when place title or place address (locality & country) has been changed. \n\t\t# The challenge is how to check when those fields have been changed\n\t\t# Auto-populate the slug field as we need to use it for the absolute url (generate it every time on the fly is very database expensive)\n\t\tmax_length = self.__class__._meta.get_field('slug').max_length\t\n\t\tself.slug = slugify(str(self))[:max_length]\n\n\t\t# check if the title is already included in the alias list and if not, add it\n\t\t# this should take effect only when the Place object is first created and when title is changed\n\t\tif self.__original_title and self.title != self.__original_title:\n\t\t\tself.add_english_alias(self.title)\n\t\t\tself.add_local_alias(self.name_local)\n\n\t\tsuper(Place, self).save(*args, **kwargs)\n\n\n\tdef get_absolute_url(self):\n\t\treturn reverse('places:place-detail', kwargs={'pk':self.pk, 'slug':self.slug})\n\n\t@property\n\tdef related_count(self):\n\t try:\n\t count = self.item_place_set.count()\n\t except ObjectDoesNotExist:\n\t count = 0\n\t return count\n\n\t@property\n\tdef display_title(self):\n\t\treturn self.title + (' ('+ self.name_local + ')' if self.name_local else '')\n\n\t@property\n\tdef title_and_locality(self):\n\t\tloc = ' ('+self.address.locality.name+')' if self.address.locality.name else ''\n\t\treturn self.title + loc\n\n\tdef alias_include(self, name):\n\t\tif name:\n\t\t\tif is_english(name):\n\t\t\t\treturn (name.lower() + ',') in self.alias_english.lower()\t\t\t\n\t\t\telse:\n\t\t\t\treturn (name + ',') in self.alias_local\n\t\treturn False\n\n\tdef add_english_alias(self, name):\n\t\tif name and (name.lower() + ',' not in self.alias_english.lower()):\n\t\t\tself.alias_english += name + ','\n\n\tdef add_local_alias(self, name):\n\t\tif name and (name + ',' not in self.alias_local):\n\t\t\tself.alias_local += name + ','\n\n\t# If it's unknown whether the given name is english or local\n\tdef add_alias(self, name):\n\t\tif name:\n\t\t\tif is_english(name):\n\t\t\t\tif (name.lower() + ',') not in self.alias_english.lower():\n\t\t\t\t\tself.alias_english += name + ','\n\t\t\telse: \n\t\t\t\tif (name + ',') not in self.alias_local:\n\t\t\t\t\tself.alias_local += name + ','\n\t\t\t\t\t# print('>>>Checkpoint 2: ' + self.alias_local)\n\n\tdef add_alias_and_save(self, name):\n\t\tself.add_alias(name)\n\t\tself.save(update_fields=['alias_english', 'alias_local'])\t\n\n\t@property\n\tdef all_aliases(self):\n\t\ts = set((self.alias_english+self.alias_local).split(','))\n\t\ts.discard('')\n\t\ts.discard(self.title)\n\t\ts.discard(self.name_local)\n\t\treturn s\n\n\n\tdef merge_duplicates(self, duplicates, keep_old=False, fill_empty=True):\n\t\t# if self in duplicates:\n\t\t# \tduplicates.remove(self)\n\t\treturn merge_objects(self, duplicates, keep_old, fill_empty)\n\n\tdef serialize_for_map(self):\n\t\treturn {\n\t\t\t\"url\": self.get_absolute_url(),\n\t\t\t\"pk\": self.pk.hashid,\n\t\t\t\"title\": self.display_title.replace(\"'\", '''),\n\t\t\t\"website\": self.website,\n\t\t\t\"phone\": self.phone,\n\t\t\t\"address\": self.address.formatted.replace(\"'\", ''') if self.address else \"\",\n\t\t\t\"latitude\": self.address.latitude if self.address else None,\n\t\t\t\"longitude\": self.address.longitude if self.address else None,\n\t\t}\n\n\n\t# Checking whether a Place object already exists is complicated. All we get from user input is \n\t# a place title, maybe a google_id, and maybe a gps embedded in the image exif\n\t# Address could be a unique identifier but it's possible multiple businesses reside at the same address\n\t# Title is also bad as an identifier becuase difference places around the world can have the same name, \n\t# and also people can mistype or use alias even if it's the same place.\n\t@classmethod\n\tdef create_if_no_match(cls, title, google_id, gps=''): # gps should be in a str format 'lat, lng'\n\t\tplace = None\n\t\tcreated = False\n\t\t\n\t\t# if google_id is given, we either get the existing place with the matching google_id or create a new one. \n\t\tif google_id:\n\t\t\ttry:\n\t\t\t\t# Check whether an exisiting Place with the same google_id already exists. If it does exist, add the title to alias\n\t\t\t\t# TODO: the following lines could raise MultipleObjectsReturned exception \n\t\t\t\trating = PlaceExternalRating.objects.get(site=GOOGLE, site_id=google_id)\n\t\t\t\tplace = rating.place\n\t\t\t\tplace.add_alias_and_save(title)\n\t\t\texcept PlaceExternalRating.DoesNotExist:\n\t\t\t\t# with transaction.atomic():\n\t\t\t\tinfo = google_place_info(google_id)\n\t\t\t\t# Create a new Place object based on google info\n\t\t\t\tplace = cls.objects.create(title=title, address=info.get('address'), website=info.get('website'), phone=info.get('phone'))\n\t\t\t\tplace.add_alias(info.get('name')) # add Google's place name as an alias if different\n\t\t\t\tplace.set_category_by_google_types(info.get('types'))\n\t\t\t\t# set category again by title because sometimes Google gets the type wrong while it could be easily guessed from place title (e.g. Hotel 1898)\n\t\t\t\tplace.set_category_by_place_name(place.title) \n\t\t\t\tplace.save()\n\t\t\t\t# Create a PlaceExternalRating Google rating for the place\n\t\t\t\tPlaceExternalRating.objects.create(place=place, site=GOOGLE, site_id=google_id,\turl=info.get('url'), rating=info.get('rating'))\n\t\t\t\tcreated = True\n\t\t# if google_id is not given but gps is given, we either get the existing place with the matching address AND a similar title/alias or create a new one\n\t\telif gps:\n\t\t\t# translate the gps to address\n\t\t\taddress = gps_to_address(gps)\n\t\t\tplaces = cls.objects.filter(address=address)\n\t\t\t# Check if the given title is in any alias or similarity between the titles is high (break if found)\n\t\t\tif places:\n\t\t\t\tfor p in places:\n\t\t\t\t\tif p.alias_include(title):\n\t\t\t\t\t\tplace = p \n\t\t\t\t\t\tbreak\n\t\t\t\t\t# QUESTION: is 0.9 a good ratio to determine similarity???\n\t\t\t\t\telif similar(p.title, title) > 0.9:\n\t\t\t\t\t\tplace = p \n\t\t\t\t\t\tplace.add_alias_and_save(title)\n\t\t\t\t\t\tbreak\n\t\t\t# if no place is found with matching address and title/alias, we create a new object with the given title and address.\n\t\t\tif not place:\n\t\t\t\tplace = cls.objects.create(title=title, address=address)\n\t\t\t\tplace.set_category_by_place_name(place.title)\n\t\t\t\tplace.save()\n\t\t\t\tcreated = True\n\t\t# if neither google_id nor gps is given:\n\t\telif title:\n\t\t\t### TBD ### should we check if a Place object with the same title and no address already exists?\n\t\t\t# It might not be prudent to make the judgement of whether any exisitng place is a true match based just on the title\n\t\t\t# place, created = cls.objects.get_or_create(title=title, address=None)\n\t\t\tplace = cls.objects.create(title=title)\n\t\t\tplace.set_category_by_place_name(place.title)\n\t\t\tplace.save()\n\t\t\tcreated = True\n\n\t\treturn (place, created)\n\n\t# update the address field based on the given google_id and gps. If both are null, \n\t# check if we can find a google_id in existing PlaceExternalRating objects\n\tdef update_address(self, google_id=None, gps=None):\n\t\tif not google_id and gps:\n\t\t\tself.address = gps_to_address(gps)\n\t\t\tself.save()\n\t\t\tmsg = 'address updated according to gps'\n\t\telse: \n\t\t\tgoogle_id = google_id if google_id else self.google_rating.site_id\n\t\t\tinfo = google_place_info(google_id)\n\t\t\tif info:\n\t\t\t\tself.address = info.get('address')\n\t\t\t\tself.save()\n\t\t\t\tmsg = 'address updated according to google_id'\n\t\treturn msg\n\n\n\t# Given Google Place types, set the corresponding category for the place\n\t# types is in a list format, e.g. [\"park\", \"point_of_interest\", \"establishment\"]\n\tdef set_category_by_google_types(self, types):\n\t\tcat_obj = None\n\t\tif types:\n\t\t\tcategory = GOOGLE_TYPES_TO_PLACECATEGORY.get(types[0])\n\t\t\tif category:\n\t\t\t\tl = len(category) - 1\n\t\t\t\tp = None\n\t\t\t\twhile (l >= 0): \n\t\t\t\t\tcat_obj = PlaceCategory.objects.get_or_create(title=category[l], parent=p)[0]\n\t\t\t\t\tl = l - 1\n\t\t\t\t\tp = cat_obj\n\t\t# return cat_obj\n\t\tif cat_obj:\n\t\t\tself.categories.add(cat_obj)\n\n\t# Set place category based on the obvious words in the name (when there is no associated google place info)\n\tdef set_category_by_place_name(self, name):\n\t\tfor key in PLACE_NAME_TO_PLACECATEGORY:\n\t\t\tif any(word in name.lower() for word in PLACE_NAME_TO_PLACECATEGORY[key]):\n\t\t\t\tself.categories.add(PlaceCategory.objects.get(title=key))\n\n\n\n\t# Generate a list of external ratings (used by place_detail.html template)\n\t# [['Google', rating_obj], ['Tripadivsor', rating_obj], ... ]\n\tdef list_ratings(self):\n\t\tl = []\n\t\tfor site in RATING_SITE_CHOICES:\n\t\t\tsite_num = int(site[0])\n\t\t\tsite_name = str(site[1])\n\t\t\tl.append([site_name,])\n\t\tfor rating in self.external_ratings.all():\n\t\t\tl[rating.site].append(rating)\n\t\t\t# try:\n\t\t\t# \trating = self.external_ratings.get(site=site_num)\n\t\t\t# except PlaceExternalRating.DoesNotExist:\n\t\t\t# \trating = None\n\t\t\t# r_tuple = (site_name, rating)\t\n\t\t\t# l.append(r_tuple)\n\t\treturn l\n\n\t\n\t@property\n\tdef google_rating(self):\n\t\ttry:\n\t\t\trating = self.external_ratings.get(site=GOOGLE)\n\t\texcept PlaceExternalRating.DoesNotExist:\n\t\t\trating = None\n\t\treturn rating\n\n\t# Get a list of all trips that visited the place (through attached itinerary items)\n\t@property\n\tdef get_trips(self):\n\t\t# id_list = self.primary_items.filter(~Q(category=itin_choices.TRANSIT)).values_list('trip', flat=True).distinct()\n\t\t# trips = Trip.objects.filter(id__in=id_list).order_by('-score')\n\t\t# try: \n\t\t# \ts1 = set(self.images.values_list('trip', flat=True)) \n\t\t# except ObjectDoesNotExist:\n\t\t# \ts1 = set()\n\t\ttry:\n\t\t\ts2 = set(self.item_place_set.values_list('item__trip', flat=True)) \n\t\texcept ObjectDoesNotExist:\n\t\t\ts2 = set()\n\t\t# trips = Trip.objects.filter(id__in=(s1 | s2)).filter(published__isnull=False).order_by('-score')\n\t\ttrips = Trip.objects.filter(id__in=s2).filter(published__isnull=False).order_by('-score')\n\t\treturn trips\n\n\n\tdef get_images(self):\n\t\t# itinerary_items = self.primary_items.filter(~Q(category=itin_choices.TRANSIT))\n\t\t# images = Image.objects.filter(itinerary__item__in=itinerary_items).order_by('-score', '-taken')\n\t\ttry: \n\t\t\timages = self.images.order_by('-score', '-taken')\n\t\texcept ObjectDoesNotExist:\n\t\t\timages = None\n\t\treturn images\n\n\t# Return sorted tags by count of all the images associated with the place\n\t@property\n\tdef all_image_tags(self):\n\t\ttags = sorted(Tag.objects.usage_for_queryset(self.get_images(), counts=True), key=lambda x: x.count, reverse=True)\n\t\treturn tags\n\n\t# check if a place belongs to a place category (i.e. either assigned the same place category or assigned a subcatgory of the given category)\n\tdef belongs_to_category(self, cat):\n\t\tresult = False\n\t\tfor category in self.categories.all():\n\t\t\tif category.is_category_or_subcategory(cat):\n\t\t\t\tresult = True\n\t\t\t\tbreak\n\t\treturn result\n\n\tdef is_accommodation(self):\n\t\tcat = PlaceCategory.objects.get(title=\"Accommodation\")\n\t\treturn self.belongs_to_category(cat)\n\n\tdef is_food_and_drink(self):\n\t\tcat = PlaceCategory.objects.get(title=\"Food & Drink\")\n\t\treturn self.belongs_to_category(cat)\n\n\tdef is_transportation(self):\n\t\tcat = PlaceCategory.objects.get(title=\"Transportation Service\")\n\t\treturn self.belongs_to_category(cat)\n\n\t# From place and time info, guess the implied itinerary title and category\n\t# This is used when we add/edit the place info of an image, we can add/edit the associated itinerary item accordingly\n\tdef implied_itinerary_info(self, t):\n\t\tif self.is_accommodation():\n\t\t\treturn ('Stay at '+self.title, itin_choices.LODGING)\n\t\t# if it's a food and drink place, we check the time input and decide which meal it is\n\t\telif self.is_food_and_drink():\n\t\t\tif t.hour >= 6 and t.hour < 11:\n\t\t\t\tmeal = \"Breakfast at \" \n\t\t\telif t.hour >= 11 and t.hour < 16: \n\t\t\t\tmeal = \"Lunch at \" \n\t\t\telif t.hour >= 17 and t.hour < 23: \n\t\t\t\tmeal = \"Dinner at \" \n\t\t\telse:\n\t\t\t\tmeal = \"Eat at \"\n\t\t\treturn (meal + self.title, itin_choices.MEAL)\n\t\telif self.is_transportation():\n\t\t\treturn ('Transit from ' + self.title, itin_choices.TRANSIT)\n\t\telse:\n\t\t\treturn ('Visit ' + self.title, itin_choices.ACTIVITY)\n\n\n\n\n###############################\n### External Rating Class ###\n###############################\n# Custom validator for Google place_id\nid_regex = RegexValidator(regex=r'^[A-Za-z0-9_-]{1,255}$', message=\"Must be a valid API place id\")\nclass PlaceExternalRating(TimeStampedModel):\n\t# Inherited fields: created, modified\n\tplace = models.ForeignKey('places.Place', \n\t\trelated_name='external_ratings',\n\t\ton_delete=models.CASCADE) \n\tsite = models.PositiveSmallIntegerField(_('rating site'),\n\t\tchoices=RATING_SITE_CHOICES,\n\t\thelp_text=_('Google / Tripadvisor / Yelp / Facebook'))\n\tsite_id = models.CharField(_('rating site place_id'), # id for the place on external site (e.g. google id)\n\t\tmax_length=255,\n\t\tblank=True,\n\t\tvalidators=[id_regex],\n\t\thelp_text=_('The unique identifier for the place on the external rating site'))\n\turl = models.URLField(_('url'), \n\t\tblank=True,\n\t\thelp_text=_('The page url for the place on the external rating site'))\n\trating = models.FloatField(_('rating'), \n\t\tnull=True,\n\t\tblank=True, \t\t\n\t\thelp_text=_('Average rating'))\n\treview_count = models.PositiveIntegerField(_('review count'),\n\t\tnull=True,\n\t\tblank=True, \n\t\thelp_text=_('Number of reviews/votes'))\n\n\tclass Meta:\n\t\tunique_together = ('place', 'site',)\n\t\tordering = ['place', 'site']\n\t\tverbose_name = _('rating')\n\t\tverbose_name_plural = _('ratings')\n\n\tdef __str__(self):\n\t\treturn self.place.title + ' - ' + str(RATING_SITE_CHOICES[self.site][1]) + ' rating'\n\n\tdef save(self, *args, **kwargs):\n\t\tif (not self.rating) or (not self.review_count):\n\t\t\tif self.site and self.url:\n\t\t\t\tavg, count = scrapeRatings(int(self.site), self.url)\n\t\t\t\tself.rating = avg\n\t\t\t\tself.review_count = count\n\t\tsuper(PlaceExternalRating, self).save(*args, **kwargs)\t\n\n\n\n###################################\n### PLACECATEGORY Class ###\n###################################\nclass PlaceCategory(TitleDescriptionModel):\n\t# Inherited fields: title, description\n\tparent = models.ForeignKey('self', \n\t\trelated_name='children', \n\t\ton_delete=models.CASCADE,\n\t\tnull=True, \n\t\tblank=True)\n\tslug = models.SlugField(unique=True)\n\n\tclass Meta:\n\t\tordering = ['slug']\n\t\tverbose_name = _('category')\n\t\tverbose_name_plural = _('categories')\n\n\tdef __str__(self):\n\t\tp_list = self._recurse_for_parents()\n\t\tp_list.append(self.title)\n\t\treturn self.get_separator().join(p_list)\n\n\tdef save(self, *args, **kwargs):\n\t\t# should generate the slug only once upon creating a new object\n\t\tif not self.id: # this checks whether it's a newly created object\n\t\t\t# if yes, set slug field here\n\t\t\tp_list = self._recurse_for_parents()\n\t\t\tp_list.append(self.title)\n\t\t\tslug_str = '-'.join(p_list)\n\t\t\tself.slug = slugify(slug_str)\n\t\tsuper(PlaceCategory, self).save(*args, **kwargs)\n\n\tdef _recurse_for_parents(self):\n\t\tp_list = []\n\t\tp = self.parent\n\t\twhile p:\n\t\t\tp_list.append(p.title)\n\t\t\tp = p.parent\n\t\tif p_list:\n\t\t\tp_list.reverse()\n\t\treturn p_list\n\n\tdef get_separator(self):\n\t\treturn ' > '\n\n\t# wether self is subcategory of the given cat (including cat = self)\n\tdef is_category_or_subcategory(self, cat):\n\t\tresult = False\n\t\tp = self\n\t\twhile p and p != cat:\n\t\t\tp = p.parent\n\t\tif p:\n\t\t\tresult = True\n\t\treturn result\n\n\n\n\n","sub_path":"places/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":20262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"154967254","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: bananasacks\n\"\"\"\n\n#! /usr/bin/env python3\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nos.chdir(\"/Users/bananasacks/Desktop/Optimal Transport Internship/Optimal_Transport/pascalle_s_drafts/test_algos_draft\")\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom sklearn import preprocessing\n\nfrom computeK import computeK\nimport sinkhorn_barycenters as sink\n\n\n\n\"\"\"\nintensity = \"minmax\" or \"zeroone\"\n Will set the plots based off of the minimum and maximum intensity values across all noise levels\n Or sets the plot's intensity to be between 0 and 1\n In case of NAN values? Set to 0 and 1\n \nimgs: number of images used to compute the barycenter\n\nnoise_lvl: choosing to use 4 different or 6 different noise levels for barycenters and plots\n\"\"\"\n\n\n\ndef get_files():\n onlyfiles = [f for f in listdir(\"./data\") if isfile(join(\"./data\", f))]\n onlyfiles = [file for file in onlyfiles if file[-4:] == \".npy\"] \n onlyfiles.sort()\n \n for file in onlyfiles:\n yield file\n \n\n\ndef debiased_sink_bary(epsilon = .1, max_iter = int(1000), intensity = \"zeroone\", plot=True, save=True):\n \n files = get_files() \n \n if plot:\n plt.figure(1, figsize=(15, 10))\n vmin = []\n vmax = []\n \n\n#change on line 78 - first variable in computeK \n#hs for unbalanced\n#hs_hat for unbalanced and normalized\n#data for just normalized\n \n for file in files: \n data = np.load(\"./data/\" + file)\n data = abs((data[:])) \n #data_pos = data - np.min(data)\n #mass = np.sum(data_pos, axis=0).max()\n # unbalanced data\n #hs = data_pos / mass\n # normalized data\n #mass_hs = np.sum(hs, axis=0)\n #hs_hat = hs / mass_hs\n\n #normalized\n data = (data-np.nanmin(data))/(np.nanmax(data)-np.nanmin(data))\n print(np.nanmin(data), np.nanmax(data), )\n\n #Computing barycenter\n \"\"\"using hs for unbalances or hs_hat for normalized\"\"\"\n P, K = computeK(data, epsilon) \n bary = sink.barycenter(P, K, reference=\"debiased\", maxiter = max_iter) \n print(np.nanmin(bary), np.nanmax(bary))\n\n #Finding max and min intensities for consistent plotting\n #Finding the Min intensitywith NAN handler\n if vmin == []:\n if torch.isnan(torch.min(bary)) == True:\n vmin = []\n else:\n vmin = torch.min(bary)\n vmin = vmin.numpy()\n ##If NAN, do nothing\n ##If min(bary) > vmin, do nothing\n else:\n if torch.isnan(torch.min(bary)) == False:\n barymin = torch.min(bary)\n barymin = barymin.numpy()\n if barymin < vmin:\n vmin = barymin \n if np.isnan(vmin):\n vmin = 0\n \n #Finding the Max intensity with NAN handler\n if vmax == []:\n if torch.isnan(torch.max(bary)) == True:\n vmax = []\n else:\n vmax = torch.max(bary)\n vmax = vmax.numpy()\n ##If NAN, do nothing\n ##If max(bary) < vmax, do nothing\n else:\n if torch.isnan(torch.max(bary)) == False:\n barymax = torch.max(bary)\n barymax = barymax.numpy()\n if barymax > vmax:\n vmax = barymax \n if np.isnan(vmax):\n vmax = 1\n #print(vmax)\n #saving the dataset\n title = \"bary\" + file[15:-4] \n params = \"_eps_\" + str(epsilon) + \"_iter_\" + str(max_iter) + \"_intensity_\" + str(intensity) \n if save:\n np.save(\"./results/debiased_sink_bary/\" + title + params + \".npy\", bary)\n #print(vmax)\n \n\n#Choose the intensity scale on the plot to be eith 0/1 or min/max \n if plot:\n k = 1\n params = \"_eps_\" + str(epsilon) + \"_iter_\" + str(max_iter) + \"_intensity_\" + str(intensity)\n #if noise_lvl == 6:\n noise_lvls = [\"0.000\", \"0.100\", \"0.200\", \"0.500\", \"1.000\"]\n m = 3\n for n in noise_lvls: \n barys = np.load(\"./results/debiased_sink_bary/bary_noiselvl_\" + n + params + \".npy\")\n plt.subplot(2, m, k)\n plt.title(\"bary_lvl_\" + n + \"_mean_0.000\")\n ##added vmin and vmax so all plots have same itensity scale\n k += 1\n if intensity == \"zeroone\":\n plt.imshow(barys, vmin=0, vmax=1)\n elif intensity == \"minmax\":\n plt.imshow(barys, vmin=vmin, vmax=vmax)\n else:\n plt.imshow(barys)\n \n\n if save:\n plt.savefig(\"./results/debiased_sink_bary/plots_debiased_sink_bary/\" + title + params + \".png\")\n \n if plot:\n plt.show()\n\n\n\nif __name__ == \"__main__\":\n #iters = [100, 750, 2000, 10000, 1e8]\n #for i in iters:\n debiased_sink_bary(epsilon = .3, max_iter = 100, intensity = \"minmax\") \n\n\"\"\"Notes for Richard\nDebiased:\n#epsilon = .001 max_iter = int(1e6)\n#epsilon = .005 max_iter = int(1e6)\n#epsilon = .01, max_iter = int(1e6), int(1e8) (only works for greater than 1e5)\n#epsilon = .05, max_iter = int(1e7) (anything less than 1e5 doesn't work)\n#epsilon = .2 max_iter = [2500, 3000, 4000]\n#eps = .5 and iters = [500, 750, 1000]\n#eps = .7 and iters = [100, 750, 1000] \n\"\"\"\n\n\n\n#Notes for me to remember\n#takes a long time to run\n#epsilon = .0001, max_iter = int(1e6)\n#epsilon = .05, max_iter = int(1e7)\n\n#eps = [.0001, .005, .01, .05, .1, .2, .5, .7] \n#iters = [100, 750, 2000, 1e8]\n \n#[.001, .025, .05, .075, .1, .15, .2, .3, .5, .7, .9]\n\n\n#ALREADY RUN\n#eps = .05 and iters = [ ] (try with high iterations like 1e6,8,10 [[100, 500, 1000, 2000, 3000, 5000, 1e5] don't work\n#eps = .1 and iters = [100, 10000, ] Need more than 10000 for .1\n#eps = .2 and iters = [2500, 5000] lower than 2500 is no good, 5000 is no good\n#eps = .5 and iters = [500, 750, 1000]\n#eps = .7 and iters = [100, 750, 1000]\n\n\n ","sub_path":"pascalle_s_drafts/test_algos_draft/debiased_sink_bary.py","file_name":"debiased_sink_bary.py","file_ext":"py","file_size_in_byte":6000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"98170145","text":"\"\"\"Read the experimental CPMG data.\"\"\"\nimport numpy as np\n\nfrom chemex import experiments\n\n\ndef read_profiles(path, filenames, details, model):\n \"\"\"Read the CPMG profiles.\"\"\"\n\n details[\"name\"] = name_experiment(details)\n Profile = experiments.grab(details[\"type\"])\n dtype = [(\"ncycs\", \"i4\"), (\"intensity\", \"f8\"), (\"error\", \"f8\")]\n\n profiles = []\n\n for profile_name, filename in filenames.items():\n full_path = path / filename\n data = np.loadtxt(full_path, dtype=dtype)\n profiles.append(Profile(profile_name, data, details, model))\n\n error = details.get(\"error\", \"file\")\n\n if error not in {\"file\", \"duplicates\"}:\n print(\"Warning: The 'error' option should either be 'file' or \")\n print(\"'duplicates'. Using the default 'file' option.\")\n error = \"file\"\n\n if error == \"duplicates\":\n # Estimate the uncertainty using the pooled standard deviation\n # Ref: http://goldbook.iupac.org/html/P/P04758.html\n\n variances = []\n\n for profile in profiles:\n variances.append(profile.get_variance_from_duplicates())\n\n noise_mean = np.sqrt(np.mean(variances))\n\n for profile in profiles:\n profile.data[\"error\"] = noise_mean\n\n return profiles\n\n\ndef name_experiment(experiment_details=None):\n \"\"\"Generate a unique name for the experiment.\"\"\"\n if not experiment_details:\n experiment_details = dict()\n\n if \"name\" in experiment_details:\n name = experiment_details[\"name\"].strip().replace(\" \", \"_\")\n\n else:\n exp_type = experiment_details[\"type\"].replace(\".\", \"_\")\n h_larmor_frq = float(experiment_details[\"h_larmor_frq\"])\n temperature = float(experiment_details[\"temperature\"])\n time_t2 = float(experiment_details[\"time_t2\"])\n\n name = \"{:s}_{:.0f}ms_{:.0f}MHz_{:.0f}C\".format(\n exp_type, time_t2 * 1e3, h_larmor_frq, temperature\n ).lower()\n\n return name\n","sub_path":"chemex/experiments/cpmg/reading.py","file_name":"reading.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"550213817","text":"import requests\nimport single_parser\nimport time\nfrom datetime import datetime\n#runs with python3\n\n# Written by Teddy Rowan\n# READ ME!!!!!!\n# This script prompts the user for a symbol, expiry date, and history range of interest and plots the historic pricing for the selected option.\n# The candlestick binning is 15 minutes if you're going back less than 35 days, or 1 day if you're going back further than 35 days. \n# There is no (?) error handling right now so be careful. \n\n# If you're just going to run it once or whatever this key is fine to use, but if you're going to run it a lot go and sign up for your own key. IT'S FREE, it takes 30 seconds.\n# https://developer.tradier.com/user/sign_up\nAPI_KEY = 'Bearer UNAGUmPNt1GPXWwWUxUGi4ekynpj'\n\nmy_headers = {'Authorization': API_KEY} # Tradier Authorization Header\n\n# TODO: Fix date labels for timesales plots.\n\n# TODO: Validate user inputs\n# TODO: Check API response for error messages. \n# TODO: Add volume line plot below candles\n# TODO: Add technical indicators like moving averages, etc. \n\nprint(\" \")\nprint(\" \")\nprint(\"*********************************************************\")\nprint(\"*********************************************************\")\nprint(\"****** WELCOME TO A HISTORIC OPTIONS DATA PLOTTER *******\")\nprint(\"*********************************************************\")\nprint(\"*********************************************************\")\nprint(\" \")\nprint(\"There is no error-handling in this right now so try to be a grown-up and not fuck everything up.\")\nprint(\"--\")\nprint(\"Also. If you're going to run this more than just to test it out, get your own API key. It's free for fucksake. And that way we don't hit rate-limiting.\")\nprint(\"--\")\nprint(\" \")\n\n# Prompt the user for the underlying symbol of interest\nsymbol = input(\"Select an underlying symbol (that's a stock ticker retard): \")\ntype(symbol)\n\n# Does the user want to look at call options or put options\noptionType = input(\"Type C for Calls or P for Puts: \")\ntype(optionType)\n\nif (optionType == \"C\"):\n print(\"Selected Call Options for \" + symbol)\nelse:\n if (optionType == \"P\"):\n print(\"Selected Put Options for \" + symbol)\n else:\n #exit() #let's try to keep the user going a bit.\n print(\"Invalid input you fucking retard. I guess we're looking at calls.\")\n optionType = \"C\"\n \n\n\n# Grab, parse, and print all the available expiry dates for the symbol.\nurl_dates = \"https://sandbox.tradier.com/v1/markets/options/expirations?symbol=\" + symbol\nrDates = requests.get(url_dates, headers=my_headers)\nsingle_parser.parse_multi_quote(rDates.content.decode(\"utf-8\"), \"date\")\n\n# TODO: Error Handling for no option dates. Should probably move the printing of the dates back into this script instead of having it in the parser.\n\n# Prompt the user to pick one of the expiry dates\ndate = input(\"Select an expiry date from the list above: \")\ntype(date)\n\n# TODO: Check whether the input date is in the list of dates.\n\n\n# Grab a list of all the prices available, then parse and format them properly\nurl_strikes = \"https://sandbox.tradier.com/v1/markets/options/strikes?symbol=\" + symbol + \"&expiration=\" + date\nrStrikes = requests.get(url_strikes, headers=my_headers)\nstrikeList = single_parser.parse_strikes(rStrikes.content.decode(\"utf-8\"))\n\nprint(\"List of available strike prices: \")\n\n# Format the price strings to the standard Tradier price format\nupdatedList = []\nprint(strikeList)\n\nselectedPrice = input(\"Select a strike from the list above: \")\ntype(selectedPrice)\n\n# error handling for retards that can't pick a strike from the list\nif not (selectedPrice in strikeList or str(selectedPrice + \".0\") in strikeList):\n print(\"How hard is it to pick a strike from the list...? Fuck me.\")\n selectedPrice = strikeList[(int)(len(strikeList)/2)] #pick the middle strike.\n print(\"I guess I'm choosing for you... Strike = $ \" + selectedPrice)\n \n# Tradier Formatting is lolz and terrible\ntmp = int(float(selectedPrice)*1000)\nselectedPrice = '{0:08d}'.format(tmp) #edit courtesy: /u/Wallstreet_Fox\n\n\n# Prompt the user for how long of a history they are interested in\nstartDate = input(\"Input a start date for the data range (YYYY-mm-dd): \")\ntype(startDate)\n\n# TODO: Error handling. Make sure that the start date is valid.\n\n\n# Format the date string for Tradier's API formatting\nformat_date = date.replace(\"-\", \"\") # strip out the dashes from the selected date\nformat_date = format_date[2:len(format_date)] # strip the 20 off the front of 2019\n\n# Find out how far back the user wants to look and if it's more than 35 days, use the history endpoint insteal of the timesales endpoint\ndatenum = datetime.strptime(startDate, \"%Y-%m-%d\")\nstartDateTime = time.mktime(datenum.timetuple())\nnowTime = time.mktime(datetime.now().timetuple())\n\nhistory = 0 # should we use the history endpoint.\nif (nowTime - startDateTime > 35*24*60*60): # if it's been more than 35 days, plot daily data\n history = 1\n\n\n# Set either a /history/ or a /timesales/ url\nif (history):\n url = \"https://sandbox.tradier.com/v1/markets/history?symbol=\" + symbol + format_date + optionType + selectedPrice + \"&start=\" + startDate\nelse:\n url = \"https://sandbox.tradier.com/v1/markets/timesales?symbol=\" + symbol + format_date + optionType + selectedPrice + \"&interval=15min&start=\" + startDate\n\ndata_name = \"\" # for plot titles\nif (optionType == \"C\"):\n data_name = symbol + \" Calls Expiring: \" + date + \" w/ Strike: $\" + str(float(selectedPrice)/1000)\n print(\"Now grabbing \" + data_name)\nelse:\n data_name = symbol + \" Puts Expiring: \" + date + \" w/ Strike: $\" + str(float(selectedPrice)/1000)\n print(\"Now grabbing \" + data_name)\n\nrData = requests.get(url, headers=my_headers) #actually download the data\n\n# parse and plot the data\nif (history):\n single_parser.parse_history_quote(rData.content.decode(\"utf-8\"), data_name)\nelse:\n single_parser.parse_timesales_quote(rData.content.decode(\"utf-8\"), data_name)\n\n\n\n","sub_path":"single_plotter.py","file_name":"single_plotter.py","file_ext":"py","file_size_in_byte":5952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"492226881","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom utils.captcha.captcha import Captcha\nfrom utils import restiful\nfrom io import BytesIO\nfrom django.views.decorators.http import require_POST\nfrom utils.smssdk.smssend import send_sms\nimport random\nfrom apps.cms.models import Article, NewsTag, Banners\nfrom django.core.cache import cache\nfrom django.conf import settings\nfrom apps.cms.serializers import ArticleSerialize\nfrom .forms import CommentForms\nfrom .models import Comments\nfrom .serializers import Commentserialize\n# Create your views here.\n\n\ndef index(request):\n tags = NewsTag.objects.all()\n end_page = settings.COUNT_PER_PAGE\n articles = Article.objects.select_related('author','tag').all().order_by('-pub_time')[0:end_page]\n banners = Banners.objects.all().order_by('-position')\n context = {\n \"articles\": articles,\n \"tags\": tags,\n \"banners\": banners\n }\n return render(request, 'news/index.html',context=context)\n\n\ndef newslist(request):\n # djangorestframework 异步新新闻列表\n\n page = int(request.GET.get('page',1))\n print(page)\n start_count = page * settings.COUNT_PER_PAGE\n end_count = start_count + settings.COUNT_PER_PAGE\n category_id = int(request.GET.get('category',0)) # 新闻分类的id为0 是默认查找所有新闻分类\n if category_id != 0:\n tag = NewsTag.objects.get(pk=category_id)\n articles = Article.objects.filter(tag=tag)[start_count:end_count]\n articles_serialize = ArticleSerialize(articles, many=True) # 使用djangorestframework序列化\n else:\n articles = Article.objects.all()[start_count:end_count]\n articles_serialize = ArticleSerialize(articles, many=True)\n\n return restiful.success(data=articles_serialize.data)\n\n# 新闻详情页\ndef news_detail(request, news_id):\n # select_related 将外键关联的模型数据也提取出来减少查询次数。\n article = Article.objects.select_related('author','tag').get(pk=news_id)\n comments = Comments.objects.filter(article=article)\n context = {\n 'article': article,\n 'comments':comments\n }\n return render(request, 'news/news_detail.html',context=context)\n\n\n# 新���评论\n@require_POST\ndef news_comment(request):\n form = CommentForms(request.POST)\n if form.is_valid():\n data = form.cleaned_data\n content = data.get('content')\n news_id = int(data.get('article'))\n author = request.user # 当前默认登陆用户\n article = Article.objects.get(pk=news_id)\n try:\n Comments.objects.create(content=content,author=author,article=article)\n return restiful.success()\n except:\n return restiful.paramserror(message=\"服务器内部错误,添加评论失败\")\n else:\n return restiful.paramserror(data=form.get_errors())\n\n\n# 评论列表:\ndef comment_list(request):\n # 每页显示评论数 per_page_count = 3\n news_id = int(request.GET.get('article'))\n per_page_count = 3\n article = Article.objects.get(pk=news_id)\n page = int(request.GET.get('page', 1))\n start = per_page_count * (page-1)\n end = start + per_page_count\n print(article)\n comments = Comments.objects.filter(article=article)[start:end]\n comments = Commentserialize(comments, many=True)\n return restiful.success(data=comments.data)\n\n\ndef search(request):\n return render(request, 'news/search.html')\n\n\ndef draw_example(request):\n text,image = Captcha.gene_code()\n out = BytesIO()\n image.save(out,'png') # 将对象保存到BytesIO中\n out.seek(0) # 移动文件指针\n cache.set('image_text',text.lower())\n httpresponse = HttpResponse(content_type='image/png')\n httpresponse.write(out.read())\n httpresponse[\"Content-length\"] = out.tell()\n return httpresponse\n\n\ndef sms_send(request):\n sms_code = random.randint(1000, 9999)\n cache.set('sms_code', sms_code, 60*5) # 存储验证码 并设置5分钟过期\n # params = {\n # 'code': sms_code\n # }\n # result = send_sms('17623008502',params)\n return HttpResponse(\"成功发送验证码:\"+str(sms_code))\n\n","sub_path":"apps/news/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"277312260","text":"# image.py\n\nimport urllib.request\nfrom random import randint\nfrom bs4 import BeautifulSoup\nimport helpers\nimport definitions\n\n\ndef get_image():\n\n #join the query words, separated by %20\n base_url = \"https://pixabay.com/en/photos/{}/?image_type=photo&pagi=\".format(\"%20\".join(definitions.search_query)) \n\n print(\"function get_image called\")\n\n # gets the total number of pages\n def get_total_pages(base_url):\n \n print(\"...function total_pages called\")\n\n # get some soup for our url\n soup = helpers.get_soup(base_url + \"1\")\n\n total_pages = soup.find('form', {'class': 'add_search_params pure-form hide-xs hide-sm hide-md'}).getText()\n total_pages = [int(s) for s in total_pages.split() if s.isdigit()][0]\n\n print(\"...returning total pages: {}\".format(total_pages))\n \n return total_pages\n \n\n # select a random page from the total pages\n def get_random_page_url(base_url):\n \n print(\"...function get_random_page_url called\")\n \n total_pages = get_total_pages(base_url)\n\n # create random number within range of total pages\n random_page_number = randint(1, total_pages)\n\n # append random number to the base url\n random_page_url = base_url + str(random_page_number)\n\n print(\"...returning url: {}\".format(random_page_url))\n\n return random_page_url\n\n\n # gets all the image urls from a page\n def get_random_image_url(page_url):\n \n print(\"...function get_random_image_url called\")\n \n #get the soup\n soup = helpers.get_soup(page_url)\n\n # make list of all the image urls\n links = [element['data-lazy-srcset'] for element in soup.findAll('img', attrs = {'data-lazy-srcset' : True})]\n \n # select a random url from the list of links\n image_url = links[helpers.random_list_number(links)]\n\n # do some cleanup\n image_url = image_url.split(',')[1] # split list elements, keep only the second one ([1]), the 480p one\n image_url = image_url.split(' ')[1] # split list elements, keep only the first one ([0]), drop the 2x\n image_url = image_url.replace(\"_480\", \"1280\") # get the larger size images\n\n print(\"...Using this url: {}\".format(image_url))\n \n return image_url\n\n def download_image(base_url):\n\n print(\"...function download_image called\")\n\n # get the page url\n page_url = get_random_page_url(base_url)\n \n # get the image url\n image_url = get_random_image_url(page_url)\n \n # download the image \n filename =\"temp_image.jpg\"\n urllib.request.urlretrieve(image_url, filename)\n\n print(\"...image temp_image.jpg saved\")\n\n\n # call the download image function\n download_image(base_url) \n","sub_path":"image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"351237428","text":"def main():\n from math import inf, ceil\n from collections import deque\n\n N, K = map(int, input().split())\n for _ in range(K):\n if N % 200 == 0:\n N = N // 200\n else:\n N = int(f\"{N}200\")\n print(N)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"abc200/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"489074287","text":"\"\"\"\nCopyright [2009-present] EMBL-European Bioinformatics Institute\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\nimport os\nimport glob\nimport re\n\n\nfrom . import config\n\n\ndef generate_model_info(cm_library, rna_type='SSU'):\n print('Processing files in {}'.format(cm_library))\n\n all_cm = 'all.cm' # file with all CMs\n all_cm_path = os.path.join(cm_library, all_cm)\n\n cmd = 'rm -f {all_cm_path} && cat {cm_library}/*.cm > {all_cm_path}'.format(\n cm_library=cm_library,\n all_cm_path=all_cm_path,\n )\n os.system(cmd)\n\n with open(os.path.join(cm_library, 'modelinfo.txt'), 'w') as f:\n line = '*all* - - %s\\n' % all_cm\n f.write(line)\n for cm in glob.glob('%s/*.cm' % cm_library):\n if all_cm in cm:\n continue\n if re.search(r'RF\\d{5}', cm):\n with open(cm, 'r') as f_cm:\n for line in f_cm:\n if line.startswith('NAME '):\n model_name = line.strip().split()[-1]\n else:\n model_name = os.path.basename(cm).replace('.cm', '')\n line = \"%s %s Bacteria %s\\n\" % (model_name, rna_type, os.path.basename(cm))\n f.write(line)\n print('Done')\n\n\nif __name__ == '__main__':\n generate_model_info(config.CM_LIBRARY)\n","sub_path":"utils/generate_model_info.py","file_name":"generate_model_info.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"153170564","text":"import math\ntextlength = 0\nclass Word:\n '''Handle a single word'''\n def __init__(self, word, index):\n self.word = word\n self.indexes = [index]\n self.count = 1\n self.rho = 0\n self.C = 0\n self.sum = 0\n self.squaredsum = 0\n self.rhonor = 0\n def add_occurence(self, index):\n self.count = self.count + 1\n self.sum = self.sum + (index - self.indexes[-1])\n self.squaredsum = self.squaredsum + math.pow(self.indexes[-1] - index, 2)\n self.indexes.append(index)\n\n def __repr__(self):\n return(\"{word: %d, C: %f, rhonor: %f, rho: %f}\" % (self.word, self.C, self.rhonor, self.rho))\n\n def __str__(self):\n return(\"{word: %s, C: %f, rhonor: %f, rho: %f}\" % (self.word, self.C, self.rhonor, self.rho))\n def nearest_neighbour(self):\n avgdist = self.sum / self.count\n avgsquare = self.squaredsum/self.count\n s = math.sqrt(avgsquare - (avgdist * avgdist))\n p = self.count / textlength\n rhogeo = math.sqrt(1 - p)\n if avgdist == 0:\n rho = 0\n else:\n rho = s/avgdist\n self.rho = rho\n rhonor = rho / rhogeo\n #print(\":%f, :%f, s: %f, p: %f, rhogeo: %f, rho: %f, rhonor: %f\" %(avgdist, avgsquare,s, p, rhogeo, rho, rhonor))\n self.rhonor = rhonor\n self.C = C(rho, self.count)\n return self.C\n\n def relative_clustering(self):\n return self.nearest_neighbour() / self.expected_nearest()\n\n def expected_nearest(self):\n return textlength / len(self.indexes)\n\ndef C(rho, n):\n brarhonor = (2 * n - 1)/(2 * n + 2)\n sdbrarhonor = 1 / (math.sqrt(n) * (1 + 2.8 * math.pow(n, -0.864)))\n return (rho - brarhonor)/sdbrarhonor\n\n\n\ndef clean(w):\n w = w.lower()\n w = w.replace('\\'s', \"\")\n w = w.replace(\".\\\"\", \"\")\n w = w.strip()\n w = w.strip(\"]\")\n w = w.strip(\",\")\n w = w.strip(\".\")\n w = w.strip(\"\\\"\")\n w = w.strip(\"(\")\n w = w.strip(\")\")\n w = w.strip(\"!\")\n w = w.strip(\";\")\n w = w.strip(\"\\\"\")\n return w\n\nif __name__ == \"__main__\":\n f = open(\"data/pg996.txt\")\n data = f.read()\n data = data.replace(\"--\", \" \")\n data = data.replace(\"__\", \" \")\n words = data.split()\n print(len(words))\n textlength = len(words)\n worddict = {}\n for i in range(0,len(words)):\n w = clean(words[i])\n if w in worddict:\n worddict[w].add_occurence(i)\n else:\n worddict[w] = Word(w, i)\n i = 0\n for key in sorted(worddict, key = lambda word: worddict[word].count, reverse=True):\n #print(worddict[key].word, len(worddict[key].indexes), worddict[key].nearest_neighbour(), worddict[key].relative_clustering())\n worddict[key].nearest_neighbour()\n print(len(worddict))\n\n for key in sorted(worddict, key = lambda word: worddict[word].C, reverse=True):\n #print(worddict[key].word, len(worddict[key].indexes), worddict[key].nearest_neighbour(), worddict[key].relative_clustering())\n w = worddict[key]\n print(\"%s: %f\" % (w.word, w.C))\n i = i + 1\n if i > 20:\n break\n","sub_path":"keywords.py","file_name":"keywords.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"530961856","text":"from .BaseDataType import BaseDataTypeClass\nfrom .PrimitiveTypes import Hash\nfrom .ConditionTypes import UnlockHash, UnlockHashType\nfrom .rivine.RivineDataFactory import RivineDataFactory\nfrom hashlib import blake2b\n\nfrom enum import IntEnum\n\n_SIG_Ed25519 = \"ed25519\"\n\n\nclass PublicKeySpecifier(IntEnum):\n NIL = 0\n ED25519 = 1\n\n @classmethod\n def from_json(cls, obj):\n if not obj:\n return PublicKeySpecifier.NIL\n if obj == _SIG_Ed25519:\n return PublicKeySpecifier.ED25519\n raise Exception(\"{} is an invalid Public Key specifier\".format(obj))\n\n def __str__(self):\n if self == PublicKeySpecifier.ED25519:\n return _SIG_Ed25519\n return \"\"\n\n __repr__ = __str__\n\n json = __str__\n\n\nclass PublicKey(BaseDataTypeClass):\n \"\"\"\n A PublicKey is a public key prefixed by a Specifier. The Specifier\n indicates the algorithm used for signing and verification.\n The other part of the PublicKey is the hash itself.\n \"\"\"\n\n def __init__(self, specifier=None, hash=None):\n self._specifier = PublicKeySpecifier.NIL\n self._hash = None\n\n self.specifier = specifier\n self.hash = hash\n\n @classmethod\n def from_json(cls, obj):\n if not obj:\n return cls()\n if not isinstance(obj, str):\n raise Exception(\"expected JSON-encoded PublicKey to be a string, not {}\".format(type(obj)))\n parts = obj.split(sep=\":\", maxsplit=2)\n if len(parts) != 2:\n raise Exception(\"invalid JSON-encoded PublicKey: {}\".format(obj))\n pk = cls()\n pk._specifier = PublicKeySpecifier.from_json(parts[0])\n pk._hash = Hash.from_json(parts[1])\n return pk\n\n @property\n def specifier(self):\n return self._specifier\n\n @specifier.setter\n def specifier(self, value):\n if value == None:\n value = PublicKeySpecifier.NIL\n elif not isinstance(value, PublicKeySpecifier):\n raise Exception(\"expected value to be a PublicKeySpecifier, not {}\".format(type(value)))\n self._specifier = value\n\n @property\n def hash(self):\n if self._hash is None:\n return Hash()\n return self._hash\n\n @hash.setter\n def hash(self, value):\n if value is None:\n self._hash = None\n elif isinstance(value, Hash):\n self._hash = value\n else:\n self._hash = Hash(value=value)\n\n def __str__(self):\n return str(self.specifier) + \":\" + str(self.hash)\n\n __repr__ = __str__\n\n json = __str__\n\n @property\n def unlockhash(self):\n \"\"\"\n Return the unlock hash generated from this public key.\n \"\"\"\n e = RivineDataFactory.encoder_sia_get()\n self.sia_binary_encode(e)\n # need to encode again to add the length\n data = e.data\n e = RivineDataFactory.encoder_sia_get()\n e.add_slice(data)\n h = blake2b(e.data, digest_size=32)\n hash = bytearray.fromhex(h.hexdigest())\n return UnlockHash(type=UnlockHashType.PUBLIC_KEY, hash=hash)\n\n @staticmethod\n def _pad_specifier(specifier):\n _SPECIFIER_SIZE = 16\n value = specifier.encode(\"utf-8\")\n return value + b\"\\0\" * (_SPECIFIER_SIZE - len(value))\n\n def sia_binary_encode(self, encoder):\n \"\"\"\n Encode this binary data according to the Sia Binary Encoding format.\n \"\"\"\n encoder.add_array(PublicKey._pad_specifier(str(self.specifier)))\n encoder.add_slice(self.hash.value)\n\n def rivine_binary_encode(self, encoder):\n \"\"\"\n Encode this binary data according to the Rivine Binary Encoding format.\n \"\"\"\n encoder.add_int8(int(self.specifier))\n encoder.add(self.hash)\n","sub_path":"lib/tfchaintypes/CryptoTypes.py","file_name":"CryptoTypes.py","file_ext":"py","file_size_in_byte":3773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"364760109","text":"#!/usr/bin/python3\n\nimport os\nimport numpy as np\nimport cv2\n\n\ndef train():\n\n\tfaces=[]\n\tIDs=[]\n\n\tRECOG_BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\timage_dir = os.path.join(RECOG_BASE_DIR, \"images\")\n\n\n\trecognizer=cv2.face.LBPHFaceRecognizer_create()\n\t# print(os.path.dirname(os.path.abspath('manage.py')))\n\n\tfor root, dirs, files in os.walk(image_dir):\n\t\tfor file in files:\n\t\t\tif file.endswith(\"png\") or file.endswith(\"jpg\"):\n\t\t\t\tpath = os.path.join(root, file)\n\t\t\t\t# print(path.split('/')[-2].split('-')[1])\n\n\t\t\t\timage = cv2.imread(path,0)\n\t\t\t\tface_array = np.array(image, \"uint8\")\n\n\n\t\t\t\tfaces.append(face_array)\n\t\t\t\tIDs.append(int(path.split('/')[-2].split('-')[1]))\n\n\n\trecognizer.train(faces,np.array(IDs))\n\t# recognizer.save('recognizer_module/recognizer/trainingdata.yml')\n\trecognizer.write('recognizer_module/recognizer/trainingdata.yml')\n\n\treturn \t","sub_path":"src/recognizer_module/train_recognizer_model.py","file_name":"train_recognizer_model.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"502153765","text":"from django.urls import path\n\nfrom web1.views import all_comments, create_comment, edit_comment, delete_comment\n\nurlpatterns = [\n path('', all_comments, name='comments'),\n path('create_comment', create_comment, name='create-comment'),\n path('edit_comment/', edit_comment, name='edit-comment'),\n path('delete_comment/', delete_comment, name='delete-comment'),\n]\n","sub_path":"web/web1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"471697611","text":"from .. import *\nfrom os.path import dirname\nimport sys\n\nif 'runtests.py' in sys.argv[0] or 'test' in sys.argv:\n print(\"Using in memory database.\\n\")\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': ':memory:',\n }\n}\n\n# Avoid sending real emails\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n","sub_path":"project_name/settings/env/unittest.py","file_name":"unittest.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"343446384","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport unittest\nimport re\nimport os.path\nimport codecs\nfrom mock import MagicMock, call, patch\nfrom uiautomatorminus import AutomatorDevice, Selector\n\n\ndef fake_jsonrpc_method(rpc_client, method, **kwargs):\n rpc_method = MagicMock(**kwargs)\n rpc_client.attach_mock(rpc_method, method)\n return rpc_method\n\n\nclass TestDevice(unittest.TestCase):\n\n def setUp(self):\n self.device = AutomatorDevice()\n self.device.server = MagicMock()\n self.device.server.jsonrpc = MagicMock()\n self.rpc_client = MagicMock()\n self.device.server.jsonrpc.return_value = self.rpc_client\n\n def fake_jsonrpc_method(self, method, **kwargs):\n return fake_jsonrpc_method(self.rpc_client, method, **kwargs)\n\n def test_info(self):\n method = self.fake_jsonrpc_method('deviceInfo', return_value={})\n self.assertEqual(self.device.info, {})\n method.assert_called_once_with()\n\n def test_click(self):\n method = self.fake_jsonrpc_method('click', return_value=True)\n self.assertEqual(self.device.click(1, 2), True)\n method.assert_called_once_with(1, 2)\n\n def test_swipe(self):\n method = self.fake_jsonrpc_method('swipe', return_value=True)\n self.assertEqual(self.device.swipe(1, 2, 3, 4, 100), True)\n method.assert_called_once_with(1, 2, 3, 4, 100)\n\n def test_long_click(self):\n method = self.fake_jsonrpc_method('swipe', return_value=True)\n x, y = 100, 200\n self.assertEqual(self.device.long_click(x, y), True)\n method.assert_called_once_with(x, y, x+1, y+1, 100)\n\n def test_drag(self):\n method = self.fake_jsonrpc_method('drag', return_value=True)\n self.assertEqual(self.device.drag(1, 2, 3, 4, 100), True)\n method.assert_called_once_with(1, 2, 3, 4, 100)\n\n def test_dump(self):\n with codecs.open(os.path.join(os.path.dirname(__file__), \"res\", \"layout.xml\"), \"r\", encoding=\"utf8\") as f:\n xml = f.read()\n method = self.fake_jsonrpc_method('dumpWindowHierarchy', return_value=xml)\n self.assertEqual(self.device.dump(\"/tmp/test.xml\"), xml)\n method.assert_called_once_with(True, None)\n self.assertEqual(self.device.dump(\"/tmp/test.xml\", False), xml)\n\n raw_xml = \"\".join(re.split(r\"\\n[ ]*\", xml))\n method = self.fake_jsonrpc_method('dumpWindowHierarchy', return_value=raw_xml)\n self.assertTrue(\"\\n \" in self.device.dump(\"/tmp/test.xml\"))\n\n def test_screenshot(self):\n method = self.fake_jsonrpc_method('takeScreenshot', return_value='1.png')\n self.device.server.adb.cmd = cmd = MagicMock()\n self.device.server.screenshot = MagicMock()\n self.device.server.screenshot.return_value = None\n cmd.return_value.returncode = 0\n self.assertEqual(self.device.screenshot(\"a.png\", 1.0, 99), \"a.png\")\n method.assert_called_once_with(\"screenshot.png\", 1.0, 99)\n self.assertEqual(cmd.call_args_list, [call(\"pull\", \"1.png\", \"a.png\"), call(\"shell\", \"rm\", \"1.png\")])\n\n method = self.fake_jsonrpc_method('takeScreenshot', return_value=None)\n self.assertEqual(self.device.screenshot(\"a.png\", 1.0, 100), None)\n\n def test_freeze_rotation(self):\n method = self.fake_jsonrpc_method('freezeRotation')\n self.device.freeze_rotation(True)\n self.device.freeze_rotation(False)\n self.assertEqual(method.call_args_list, [call(True), call(False)])\n\n def test_orientation(self):\n orientation = {\n 0: \"natural\",\n 1: \"left\",\n 2: \"upsidedown\",\n 3: \"right\"\n }\n for i in range(4):\n method = self.fake_jsonrpc_method('deviceInfo', return_value={'displayRotation': i})\n self.assertEqual(self.device.orientation, orientation[i])\n # set\n orientations = [\n (0, \"natural\", \"n\", 0),\n (1, \"left\", \"l\", 90),\n (2, \"upsidedown\", \"u\", 180),\n (3, \"right\", \"r\", 270)\n ]\n for values in orientations:\n for value in values:\n method = self.fake_jsonrpc_method('setOrientation')\n self.device.orientation = value\n method.assert_called_once_with(values[1])\n\n with self.assertRaises(ValueError):\n self.device.orientation = \"invalid orientation\"\n\n def test_last_traversed_text(self):\n method = self.fake_jsonrpc_method('getLastTraversedText', return_value='abcdef')\n self.assertEqual(self.device.last_traversed_text, \"abcdef\")\n method.assert_called_once_with()\n\n def test_clear_traversed_text(self):\n method = self.fake_jsonrpc_method('clearLastTraversedText')\n self.device.clear_traversed_text()\n method.assert_called_once_with()\n\n def test_open(self):\n method = self.fake_jsonrpc_method('openNotification')\n self.device.open.notification()\n method.assert_called_once_with()\n method = self.fake_jsonrpc_method('openQuickSettings')\n self.device.open.quick_settings()\n method.assert_called_once_with()\n\n def test_watchers(self):\n names = [\"a\", \"b\", \"c\"]\n method = self.fake_jsonrpc_method('getWatchers', return_value=names)\n self.assertEqual(self.device.watchers, names)\n method.assert_called_once_with()\n\n method = self.fake_jsonrpc_method('hasAnyWatcherTriggered', return_value=True)\n self.assertEqual(self.device.watchers.triggered, True)\n method.assert_called_once_with()\n\n method = self.fake_jsonrpc_method('removeWatcher')\n self.device.watchers.remove(\"a\")\n method.assert_called_once_with('a')\n method = self.fake_jsonrpc_method('removeWatcher')\n self.device.watchers.remove()\n self.assertEqual(method.call_args_list, [call(name) for name in names])\n\n method = self.fake_jsonrpc_method('resetWatcherTriggers')\n self.device.watchers.reset()\n method.assert_called_once_with()\n\n method = self.fake_jsonrpc_method('runWatchers')\n self.device.watchers.run()\n method.assert_called_once_with()\n\n def test_watcher(self):\n method = self.fake_jsonrpc_method('hasWatcherTriggered', return_value=False)\n self.assertFalse(self.device.watcher(\"name\").triggered)\n method.assert_called_once_with(\"name\")\n\n method = self.fake_jsonrpc_method('removeWatcher')\n self.device.watcher(\"a\").remove()\n method.assert_called_once_with(\"a\")\n\n method = self.fake_jsonrpc_method('registerClickUiObjectWatcher')\n condition1 = {\"text\": \"my text\", \"className\": \"android\"}\n condition2 = {\"description\": \"my desc\", \"clickable\": True}\n target = {\"className\": \"android.widget.Button\", \"text\": \"OK\"}\n self.device.watcher(\"watcher\").when(**condition1).when(**condition2).click(**target)\n method.assert_called_once_with(\n \"watcher\",\n [Selector(**condition1), Selector(**condition2)],\n Selector(**target)\n )\n\n method = self.fake_jsonrpc_method('registerPressKeyskWatcher')\n self.device.watcher(\"watcher2\").when(**condition1).when(**condition2).press.back.home.power(\"menu\")\n method.assert_called_once_with(\n \"watcher2\", [Selector(**condition1), Selector(**condition2)], (\"back\", \"home\", \"power\", \"menu\"))\n\n def test_press(self):\n key = [\"home\", \"back\", \"left\", \"right\", \"up\", \"down\", \"center\",\n \"menu\", \"search\", \"enter\", \"delete\", \"del\", \"recent\",\n \"volume_up\", \"volume_down\", \"volume_mute\", \"camera\", \"power\"]\n method = self.fake_jsonrpc_method('pressKey', return_value=True)\n self.assertTrue(self.device.press.home())\n self.assertEqual(method.call_args_list, [call(\"home\")])\n method = self.fake_jsonrpc_method('pressKey', return_value=False)\n self.assertFalse(self.device.press.back())\n self.assertEqual(method.call_args_list, [call(\"back\")])\n method = self.fake_jsonrpc_method('pressKey', return_value=False)\n for k in key:\n self.assertFalse(self.device.press(k))\n self.assertEqual(method.call_args_list, [call(k) for k in key])\n\n method = self.fake_jsonrpc_method('pressKeyCode', return_value=True)\n self.assertTrue(self.device.press(1))\n self.assertTrue(self.device.press(1, 2))\n self.assertEqual(method.call_args_list, [call(1), call(1, 2)])\n\n def test_wakeup(self):\n method = self.fake_jsonrpc_method('wakeUp')\n self.device.wakeup()\n method.assert_called_once_with()\n\n method = self.fake_jsonrpc_method('wakeUp')\n self.device.screen.on()\n method.assert_called_once_with()\n\n method = self.fake_jsonrpc_method('wakeUp')\n self.device.screen(\"on\")\n method.assert_called_once_with()\n\n def test_screen_status(self):\n method = self.fake_jsonrpc_method('deviceInfo', return_value={\"screenOn\": True})\n self.assertTrue(self.device.screen == \"on\")\n self.assertTrue(self.device.screen != \"off\")\n\n method = self.fake_jsonrpc_method('deviceInfo', return_value={\"screenOn\": False})\n self.assertTrue(self.device.screen == \"off\")\n self.assertTrue(self.device.screen != \"on\")\n\n def test_sleep(self):\n method = self.fake_jsonrpc_method('sleep')\n self.device.sleep()\n method.assert_called_once_with()\n\n method = self.fake_jsonrpc_method('sleep')\n self.device.screen.off()\n method.assert_called_once_with()\n\n method = self.fake_jsonrpc_method('sleep')\n self.device.screen(\"off\")\n method.assert_called_once_with()\n\n def test_wait_idle(self):\n method = self.fake_jsonrpc_method('waitForIdle', return_value=True)\n self.assertTrue(self.device.wait.idle(timeout=10))\n method.assert_called_once_with(10)\n\n method = self.fake_jsonrpc_method('waitForIdle', return_value=False)\n self.assertFalse(self.device.wait(\"idle\", timeout=10))\n method.assert_called_once_with(10)\n\n def test_wait_update(self):\n method = self.fake_jsonrpc_method('waitForWindowUpdate', return_value=True)\n self.assertTrue(self.device.wait.update(timeout=10, package_name=\"android\"))\n method.assert_called_once_with(\"android\", 10)\n\n method = self.fake_jsonrpc_method('waitForWindowUpdate', return_value=False)\n self.assertFalse(self.device.wait(\"update\", timeout=100, package_name=\"android\"))\n method.assert_called_once_with(\"android\", 100)\n\n def test_get_info_attr(self):\n info = {\"test_a\": 1, \"test_b\": \"string\", \"displayWidth\": 720, \"displayHeight\": 1024}\n method = self.fake_jsonrpc_method('deviceInfo', return_value=info)\n for k in info:\n self.assertEqual(getattr(self.device, k), info[k])\n self.assertEqual(self.device.width, info[\"displayWidth\"])\n self.assertEqual(self.device.height, info[\"displayHeight\"])\n with self.assertRaises(AttributeError):\n self.device.not_exists\n\n def test_device_obj(self):\n with patch(\"uiautomatorminus.AutomatorDeviceObject\") as AutomatorDeviceObject:\n kwargs = {\"text\": \"abc\", \"description\": \"description...\", \"clickable\": True}\n self.device(**kwargs)\n AutomatorDeviceObject.assert_called_once_with(self.device, Selector(**kwargs))\n\n with patch(\"uiautomatorminus.AutomatorDeviceObject\") as AutomatorDeviceObject:\n AutomatorDeviceObject.return_value.exists = True\n self.assertTrue(self.device.exists(clickable=True))\n AutomatorDeviceObject.return_value.exists = False\n self.assertFalse(self.device.exists(text=\"...\"))\n\n\nclass TestDeviceWithSerial(unittest.TestCase):\n\n def test_serial(self):\n with patch('uiautomatorminus.AutomatorServer') as AutomatorServer:\n AutomatorDevice(\"abcdefhijklmn\")\n AutomatorServer.assert_called_once_with(serial=\"abcdefhijklmn\", local_port=None, adb_server_host=None, adb_server_port=None)\n","sub_path":"test/test_device.py","file_name":"test_device.py","file_ext":"py","file_size_in_byte":12122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"609885017","text":"import unittest\nimport logging\nfrom pyrob.loads.p6.loader import P6Loader\nfrom pyrob.schema.ipact_stg import P6ProjectActivity\n\n\nclass TestP6Loader(unittest.TestCase):\n\n def setUp(self):\n self.loader = P6Loader(\n 'pyrob/loads/p6/tests/data/fixture.xml',\n table=P6ProjectActivity\n )\n\n def test_fieldnames(self):\n self.assertEquals(\n self.loader.fieldnames,\n [\n 'activity_id',\n 'activity_name',\n 'activity_state',\n 'activity_status',\n 'activity_type',\n 'bl_finish_date',\n 'bl_start_date',\n 'constraint_date',\n 'cpacss_code',\n 'fact_status',\n 'finish_date',\n 'last_modified_by',\n 'last_modified_date',\n 'project_id',\n 'project_name',\n 'resource_ids',\n 'start_date',\n 'update_log',\n 'wbs',\n 'wbs_name'\n ]\n )\n\n def test_source_data(self):\n self.assertEquals(len(self.loader.source_data()), 11)\n\n def test_get_rows(self):\n self.assertEquals(\n len(list(self.loader.get_rows(process_id='1234'))), 11\n )\n","sub_path":"pyrob/loads/p6/tests/test_loader.py","file_name":"test_loader.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"479281306","text":"import re\n\ndef allyourbase(s):\n base = len(set(s))\n if base == 1:\n base = 2\n minval = 1\n vals = {}\n vals[s[0]] = minval\n date = vals[s[0]]*(long(base)**(len(s)-1))\n for index in xrange(1, len(s)):\n if not vals.has_key(s[index]):\n if minval == 1:\n minval = 0\n elif minval == 0:\n minval = 2\n else:\n minval += 1\n vals[s[index]] = minval\n date += vals[s[index]]*(base**(len(s)-index-1))\n return date\n\ndef allyourbase_printoutput(filename):\n fout = file('e-output.dat', 'w')\n f = file(filename)\n cases = int(re.compile('([0-9]+)').findall(f.next())[0])\n for x in xrange(cases):\n fout.write('Case #%d: ' % (x+1))\n fout.write(str(allyourbase(f.next().strip('\\n')))+'\\n')","sub_path":"googlecodejam/allyourbase.py","file_name":"allyourbase.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"356009627","text":"\nimport random\n# 花色 红黑方梅\nSUITS = ['H', 'S', 'D', 'C']\n#方片 D 黑桃 S 红桃 H 梅花 C\n# 初始基本牌\nINIT_LIST = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q','K','A']\n\nMAPPING_LIST_NUM = '23456789TJQKA'\nMAPPING_LIST_COLOR = 'DCHS' # 方梅红黑\n#初始牌堆\ndef init_landlords():\n lis = []\n for card in INIT_LIST: # 数字\n for suit in SUITS: # 花色\n lis.append('{0}{1}'.format(card, suit))\n random.shuffle(lis)\n # print(lis)\n return lis\n\n # print \"初始化牌堆:\", lis\n\ndef exchange_number(cards):\n number = []\n for r, s in cards:\n temp = MAPPING_LIST_NUM.index(r)\n number.append(temp)\n return number\n\n\ndef exchange_color(cards):\n color = []\n for r, s in cards:\n temp = MAPPING_LIST_COLOR.index(s)\n color.append(temp)\n return color\n\n\n\nif __name__ =='__main__':\n init_landlords()\n\n","sub_path":"game_config.py","file_name":"game_config.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"174927754","text":"'''\nGrupo: G, Hora: 4º grupo da segunda feira\n'''\n\n\n\ndef modulo(h):\n if h>=0:\n h=h\n if h<0:\n h=(-1)*h\n return h\n\nn=int(input('Digite a quantidade de valores: '))\n\nlista=[]\nfor i in range (0, n, 1):\n lista.append(float(input('Digite um valor para a lista: ')))\n\nmedia = sum(lista)/(float(n))\n\nsomat=0\nfor i in range (0, n, 1):\n somat+=((lista[i] - media)**2)\n\ndesvpad= float(((1/(n - 1))*somat)**(float(1/2)))\nprint(desvpad)\n\nqntd68=0\nfor i in range (0, n, 1):\n if modulo(lista[i] - media)=desvpad:\n qntd68+=0\n \nqntd95=0\nfor i in range (0, n, 1):\n if modulo(lista[i] - media)<2*desvpad:\n qntd95+=1\n if modulo(lista[i] - media)>=2*desvpad:\n qntd95+=0\n\nqntd997=0\nfor i in range (0, n, 1):\n if modulo(lista[i] - media)<3*desvpad:\n qntd997+=1\n if modulo(lista[i] - media)>=3*desvpad:\n qntd997+=0\n \nif (float(qntd68/n)>=float(68/100)) and (float(qntd95/n)>=float(95/100)) and (float(qntd997/n)>=float(99.7/100)):\n print('Sim, a distruição é normal.')\nif not (float(qntd68/n)>=float(68/100)) and (float(qntd95/n)>=float(95/100)) and (float(qntd997/n)>=float(99.7/100)):\n print('Não, a distruição não é normal.')\n\n#-------------------------------------------------------------------------------------------------------------------------------------------------\n'''\ndef crescente(lista):\n k=0\n for i in range (0, len(lista)-2, 1):\n if lista[i]=lista[i+1]:\n k+=1\n if k==0:\n cresc=True\n if not k==0:\n cresc=False\n return cresc\n \nn=int(input('Digite a quantidade de valores: '))\n\nlista=[]\nfor i in range (0, n, 1):\n lista.append(int(input('Digite um valor para a lista: ')))\n\nif crescente(lista)==True:\n print('S')\nif crescente(lista)==False:\n print('N')\n'''","sub_path":"moodledata/vpl_data/303/usersdata/298/97801/submittedfiles/testes.py","file_name":"testes.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"290410649","text":"from math import ceil, log\n\nn = [13, 235, 234, 12, 362, 21, 435, 24, 3456, 675, 2, 3456, 213, 5463]\n\ndef second_largest(n):\n i = [-1]*len(n)\n def largest(count, index):\n while count:\n comp1 = False\n for comp2 in n:\n if i[comp2] != index: continue\n if comp1 != False:\n count -= 1\n if n[comp1] > n[comp2]:\n i[comp2] = comp1\n else:\n i[comp1] = comp2\n comp1 = False\n else: comp1 = comp2\n for l in range(len(n)):\n if i[l] == index:\n return l\n return largest(ceil(log(len(n)))-1, largest(len(n)-1, -1))\n\nprint(second_largest(n))\n","sub_path":"second_largest.py","file_name":"second_largest.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"639633239","text":"import pandas as pd\nimport numpy as np\n\npd.set_option('display.unicode.ambiguous_as_wide', True)\npd.set_option('display.unicode.east_asian_width', True)\nnd = locals()\n\nintput_file = '例4-2.csv'\nf = open(intput_file, encoding='UTF-8')\ndata = pd.read_csv(f,\n encoding='UTF-8',\n names=['No', 'Nature', 'x1', 'x2', 'x3', 'x4', 'Class'],\n header=0)\ndata.reset_index()\nprint(\"原始数据是:\\n\")\nprint(data, \"\\n\")\n\np = 3 # 分类数目\nt = 22 # 测试集数目\nna = np.vstack(np.asarray(data.loc[:t-2:-1, \"Nature\"]))[::-1] # (国家)标识列表\n\nfor i in range(1, p+1, 1):\n nd['df_' + str(i)] = data[data['Class'] == i]\n nd['k'+str(i)] = len(nd['df_' + str(i)])\n nd['a'+str(i)] = nd['df_'+str(i)].iloc[:, 2:6]\n nd['matrix_'+str(i)] = np.asmatrix(nd['a'+str(i)])\n nd['miu_'+str(i)] = np.mean(nd['matrix_'+str(i)], axis=0)\n nd['deviation_'+str(i)] = nd['matrix_'+str(i)] - nd['miu_'+str(i)]\n nd['t_deviation_'+str(i)] = nd['deviation_'+str(i)].T\n nd['sigma_'+str(i)] = (nd['t_deviation_'+str(i)] * nd['deviation_'+str(i)])\n\n# 测试向量从数据框后向前依次提取t个(测试集的类别必须是NaN!)\nfor j in range(1, t+1, 1):\n nd['test_'+str(j)] = data.iloc[[-j]]\n nd['t'+str(j)] = nd['test_'+str(j)].iloc[:, 2:6]\n nd['t_matrix_'+str(j)] = np.asmatrix(nd['t'+str(j)])\n\nnumerator = 0\ndenominator = 0\n\nfor i in range(1, p+1, 1):\n numerator += nd['sigma_'+str(i)]\n denominator += nd['k'+str(i)]-1\n\nsigma = numerator/denominator\ninv_sigma = np.linalg.inv(sigma)\n\nn = np.zeros(shape=(t, p))\n\nfor j in range(1, t+1, 1):\n for i in range(1, p+1, 1):\n nd['d'+str(j)+str(i)] = (nd['t_matrix_'+str(j)]-nd['miu_'+str(i)]) * \\\n inv_sigma*((nd['t_matrix_'+str(j)]-nd['miu_'+str(i)]).T)\n n[j-1, i-1] = nd['d'+str(j)+str(i)]\n\nn = n[::-1]\nn_na = np.concatenate((na, n), axis=1)\np_n = pd.DataFrame(data=np.array(n_na), columns=[\n '国家', 'Class1', 'Class2', 'Class3'])\n\nprint(\"每个测试向量对于每一类的距离:\\n\")\nprint(p_n, \"\\n\")\n\ns = np.min(n, axis=1, keepdims=True)\nc = np.vstack(np.argmin(n, axis=1) + 1)\n\nd = np.concatenate((na, s, c), axis=1)\n\np_d = pd.DataFrame(data=np.array(d), columns=['国家', '最短距离', '类别'])\n\nprint(\"最终的结果和归类:\\n\")\nprint(p_d)\n\nq = input(\"Please Enter to quit\")\nif q:\n quit()\n","sub_path":"college_course/Multivariate Statistical Analysis/multiple discriminant analysis/distance discreminant/DD_1.py","file_name":"DD_1.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"184630844","text":"#!/usr/bin/env python3 -tt\n\nfrom scapy.all import *\nimport struct\nimport codecs\nfrom pyasn1.codec.ber import encoder, decoder\n\n\nMESSAGETYPEOFFSETUDP = 17\nMESSAGETYPEOFFSETTCP = 21\nDEBUG = True\n\nTGS_REP = 13\n\ndef findkerbpayloads(packets, verbose=False):\n\tkploads = []\n\ti = 1\n\tunfinished = {}\n\tfor p in packets:\n\t\t# UDP\n\t\tif p.haslayer(UDP) and p.sport == 88 and p[UDP].load[MESSAGETYPEOFFSETUDP] == TGS_REP:\n\t\t\tif verbose: print(\"found UDP payload of size %i\" % len(p[UDP].load) )\n\t\t\tkploads.append(p[UDP].load)\n\n\t\t#TCP\n\t\telif p.haslayer(TCP) and p.sport == 88 and p[TCP].flags & 23== 16: #ACK Only, ignore push (8), urg (32), and ECE (64+128)\n\t\t\t# assumes that each TCP packet contains the full payload\n\n\t\t\ttry:\n\t\t\t\tpayload = p[TCP].load\n\t\t\texcept:\n\t\t\t\tcontinue\n\n\t\t\tif len(payload) > MESSAGETYPEOFFSETTCP and payload[MESSAGETYPEOFFSETTCP] == TGS_REP:\n\t\t\t\t# found start of new TGS-REP\n\t\t\t\tsize = struct.unpack(\">I\", payload[:4])[0]\n\t\t\t\tif size + 4 == len(payload):\n\t\t\t\t\tkploads.append(payload[4:size+4]) # strip the size field\n\t\t\t\telse:\n\t\t\t\t\t#print('ERROR: Size is incorrect: %i vs %i' % (size, len(payload)))\n\t\t\t\t\tunfinished[(p[IP].src, p[IP].dst, p[TCP].dport)] = (payload[4:size+4], size)\n\t\t\t\tif verbose: print(\"found TCP payload of size %i\" % size)\n\t\t\telif (p[IP].src, p[IP].dst, p[TCP].dport) in unfinished:\n\t\t\t\tticketdata, size = unfinished.pop((p[IP].src, p[IP].dst, p[TCP].dport))\n\t\t\t\tticketdata += payload\n\t\t\t\t#print(\"cont: %i %i\" % (len(ticketdata), size))\n\t\t\t\tif len(ticketdata) == size:\n\t\t\t\t\tkploads.append(ticketdata)\n\t\t\t\telif len(ticketdata) < size:\n\t\t\t\t\tunfinished[(p[IP].src, p[IP].dst, p[TCP].dport)] = (ticketdata, size)\n\t\t\t\telse:\n\t\t\t\t\t# OH NO! Oversized!\n\t\t\t\t\tprint('Too much data received! Source: %s Dest: %s DPort %i' % (p[IP].src, p[IP].dst, p[TCP].dport))\n\n\n\treturn kploads\n\n\n\nif __name__ == '__main__':\n\timport argparse\n\n\tparser = argparse.ArgumentParser(description='Find TGS_REP packets in a pcap file and write them for use cracking')\n\tparser.add_argument('-f', '--pcap', dest='pcaps', action='append', required=True,\n\t\t\t\t\tmetavar='PCAPFILE', #type=file, #argparse.FileType('r'), \n\t\t\t\t\thelp='a file to search for Kerberos TGS_REP packets')\n\tparser.add_argument('-w', '--outputfile', dest='outfile', action='store', required=False, \n\t\t\t\t\tmetavar='OUTPUTFILE', type=argparse.FileType('w'), \n\t\t\t\t\thelp='the output file')\n\tparser.add_argument('-v', '--verbose', dest='verbose', action='store_true', default=False,\n\t\t\t\t\thelp='display verbose messages')\n\n\targs = parser.parse_args()\n\tkploads = []\n\tfor f in args.pcaps:\n\t\tpackets = rdpcap(f)\n\t\tkploads += findkerbpayloads(packets, args.verbose)\n\n\tif len(kploads) == 0:\n\t\tprint('no payloads found')\n\t\tsys.exit(0)\n\n\tif args.outfile:\n\t\tprint('writing %i hex encoded payloads to %s' % (len(kploads), args.outfile.name))\n\t\n\tdecode_hex = codecs.getdecoder(\"hex_codec\")\n\tfor p in kploads:\n\t\tencticket = decoder.decode(p)[0][4][3][2].asOctets().hex()\n\t\tout = \"$krb5tgs$23$*user$realm$test/spn*$\" + encticket[:32] + \"$\" + encticket[32:]\n\n\t\tif args.outfile:\n\t\t\targs.outfile.write(out + '\\n')\n\t\telse:\n\t\t\tprint(out)","sub_path":"krbroast-pcap2hashcat.py","file_name":"krbroast-pcap2hashcat.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"313425165","text":"import argparse\nimport logging\nimport glob\nimport os\nimport json\nimport numpy as np\n\n\nlogging.basicConfig(level=logging.INFO)\n\nparser = argparse.ArgumentParser(description='Launch one synthesizer on one or multiple datasets.')\nparser.add_argument('datasets', type=str, nargs='*',\n help='a list of datasets, empty means all datasets.')\nparser.add_argument('--repeat', type=int, default=3,\n help='run generater multiple times.')\n\nparser.add_argument('--output', type=str, default='output',\n help='output dir')\nparser.add_argument('--name', type=str, default='',\n help='model name, default is model class name.')\n\nparser.add_argument('--sample', type=int, default=50000,\n help='maximum samples in the synthetic data.')\n\nclass SynthesizerBase(object):\n \"\"\"docstring for Synthesizer.\"\"\"\n\n supported_datasets = [\n 'asia', 'alarm', 'child', 'insurance', 'grid', 'gridr', 'ring',\n 'adult', 'credit', 'census',\n 'news', 'covtype', 'intrusion', 'mnist12', 'mnist28']\n\n def train(self, train_data):\n pass\n\n def generate(self, n):\n pass\n\n def init(self, meta, working_dir):\n pass\n\n\ndef run(synthesizer):\n assert isinstance(synthesizer, SynthesizerBase)\n\n args = parser.parse_args()\n datasets = args.datasets\n name = args.name\n if name == \"\":\n name = synthesizer.__class__.__name__\n\n output = \"{}/{}\".format(args.output, name)\n\n if not os.path.exists(output):\n os.makedirs(output)\n logging.info(\"Use output dir {}\".format(output))\n\n repeat = args.repeat\n\n if datasets == []:\n datasets = synthesizer.supported_datasets\n else:\n for item in datasets:\n if not item in synthesizer.supported_datasets:\n logging.warning(\"Dataset {} is not supported by {}.\".format(item, name))\n\n\n\n for dataset in datasets:\n\n data_filename = glob.glob(\"data/*/{}.npz\".format(dataset))\n meta_filename = glob.glob(\"data/*/{}.json\".format(dataset))\n\n if len(data_filename) != 1:\n logging.warning(\"Skip. Can't find dataset {}. \".format(dataset))\n continue\n\n if len(meta_filename) != 1:\n logging.warning(\"Skip. Can't find meta {}. \".format(dataset))\n continue\n\n data = np.load(data_filename[0])['train']\n with open(meta_filename[0]) as f:\n meta = json.load(f)\n\n\n for i in range(repeat):\n if glob.glob(\"{}/{}_{}_*.npz\".format(output, dataset, i)):\n logging.warning(\"Skip. {} results on {}_{} exists.\".format(name, dataset, i))\n continue\n\n logging.info(\"Generating {} iter {}\".format(dataset, i))\n working_dir = \"{}/ckpt_{}_{}\".format(output, dataset, i)\n synthesizer.init(meta, working_dir)\n synthesizer.train(data)\n sample = min(args.sample, data.shape[0])\n generated = synthesizer.generate(sample)\n\n if len(generated) == 0:\n logging.warning(\"{} fails on {}. \".format(name, dataset))\n\n for step, syn in generated:\n np.savez(\"{}/{}_{}_{}.npz\".format(output, dataset, i, step), syn=syn)\n","sub_path":"synthetic_data_benchmark/synthesizer/synthesizer_base.py","file_name":"synthesizer_base.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"565587545","text":"\ndef programme_candidat(tableau, taille_x, taille_y):\n out0 = 0\n for i in range(0, taille_y):\n for j in range(0, taille_x):\n out0 += ord(tableau[i][j]) * (i + j * 2)\n print(\"%c\" % tableau[i][j], end='')\n print(\"--\\n\", end='')\n return out0\ntaille_x = int(input())\ntaille_y = int(input())\na = [None] * taille_y\nfor b in range(0, taille_y):\n a[b] = list(input())\ntableau = a\nprint(\"%d\\n\" % programme_candidat(tableau, taille_x, taille_y), end='')\n\n","sub_path":"out/prologin_template_charmatrix.py","file_name":"prologin_template_charmatrix.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"424441389","text":"# Activity Homework_11_2_Task1\r\n# File: Homework_11_2_Task1_maims\r\n# Date: 05 Nov 2018\r\n# By: Melanie Mai\r\n# Section: 011\r\n# Team: 122\r\n# \r\n# ELECTRONIC SIGNATURE\r\n# Melanie Mai\r\n#\r\n# The electronic signature above indicates the script\r\n# submitted for evaluation is my individual work, and I\r\n# have a general understanding of all aspects of its\r\n# development and execution.\r\n#\r\n# A BRIEF DESCRIPTION OF WHAT THE SCRIPT OR FUNCTION DOES\r\n# This program will compute the ending distance of a refraction given the indices of refraction\r\n# for two medias, the angle of incidence, and the first and second distance given by the user. \r\n# If there is no refraction in the second media, an error message should occur. \r\nimport math\r\n\r\nimport sys\r\n\r\n#User input of refraction, angle, and distances\r\nRefractionlist = input('Enter indices of refraction for bottom two media: ').split()\r\nAngle = int(input('Enter angle of incidence (in degrees): '))\r\nDistances = input('Enter d1 and d2 (units): ').split()\r\n\r\n#Convert Refractionlist elements to int\r\nRefractionElement1 = float(Refractionlist[0])\r\nRefractionElement2 = float(Refractionlist[1])\r\nProportion = RefractionElement1/RefractionElement2\r\n\r\n#Conver Distances elements to int\r\nDistance1 = float(Distances[0])\r\nDistance2 = float(Distances[1])\r\n\r\nif (Proportion > 1) or (Proportion < -1):\r\n\tprint(\"Error, no refraction in the second media.\")\r\n\tsys.exit()\r\n\r\n#Math conversion\r\nx = math.tan(Angle)*Distance1\r\n\r\nAngle2 = math.asin((RefractionElement1*math.sin(Angle))/RefractionElement2)\r\n\r\ny = math.tan(Angle2)*Distance2\r\n\r\nD3 = (x+y)\r\n\r\nprint(\"The ending distance is: \",D3,\" units.\")\r\n\r\n\r\n\r\n","sub_path":"Homework_11_2_Task1_maims.py","file_name":"Homework_11_2_Task1_maims.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"317941954","text":"\"\"\"Урок 1. Задача 1.\r\nПоработайте с переменными, создайте несколько, выведите на экран,\r\nзапросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.\r\n\"\"\"\r\nname = input('Ваше имя') #функция ввода\r\nprint('Здравствуй', name) #функция вывода\r\n\r\nvar_str = \"Это строка\" #str это строка\r\nvar_str2 = 'ЭТО тоже строка'\r\nvar_str3 = \"\"\"И это тоже\r\nстрока\r\n\"\"\"\r\nvar_int = 44 #любое целое число\r\nvar_float = 44.5 #дробное число\r\nprint(1 , var_str)\r\nprint(2 , var_str2)\r\nprint(3 , var_str3)\r\n#snake_case = 1\r\n\r\nvar_bool = True #True or False\r\nuser_name = 'Ирина'\r\nuser_age = 16\r\nif user_age >= 17:\r\n print('Доступ разрешен')\r\nelse:\r\n print('Доступ запрещен')\r\n\r\n\r\n","sub_path":"lesson_1.py","file_name":"lesson_1.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"456138552","text":"import os, sys, shutil\nimport torch\nimport torch.nn as nn\nimport torch.utils.data as data\nimport numpy as np\nfrom time import time\n\nimport DataModule_lstur as data_utils\nimport config_lstur as conf\nfrom metrics import evaluate\nfrom Logging import Logging, check_dir, tensorToScalar\n\n\nif __name__ == '__main__':\n ############################## CREATE MODEL ##############################\n from lstur import lstur\n model = lstur()\n \n model.cuda()\n optimizer = torch.optim.Adam(model.parameters(), lr=conf.learning_rate)\n\n ############################## PREPARE DATASET ##############################\n print('System start to load data...')\n t0 = time()\n train_data, val_data = data_utils.load_all()\n t1 = time()\n print('Data has been loaded successfully, cost:%.4fs' % (t1 - t0))\n\n ########################### TRAINING STAGE ##################################\n check_dir('%s/train_log' % conf.out_path)\n log = Logging('%s/train_%s_lstur.log' % (conf.out_path, conf.data_name))\n train_model_path = '%s/train_%s_lstur.mod' % (conf.out_path, conf.data_name)\n\n # prepare data for the training stage\n train_dataset = data_utils.TrainData(train_data)\n val_dataset = data_utils.TestData(val_data)\n\n train_batch_sampler = data.BatchSampler(data.RandomSampler(\n range(train_dataset.length)), batch_size=conf.batch_size, drop_last=False)\n val_batch_sampler = data.BatchSampler(data.SequentialSampler(\n range(val_dataset.length)), batch_size=conf.batch_size, drop_last=True)\n\n # Start Training !!!\n max_auc = 0\n for epoch in range(1, conf.train_epochs+1):\n t0 = time()\n model.train()\n\n train_loss = []\n for batch_idx_list in train_batch_sampler:\n user_indexes, his_input_title, pred_input_title, labels = \\\n train_dataset._get_batch(batch_idx_list)\n obj_loss = model(user_indexes, his_input_title, pred_input_title, labels)\n #import pdb; pdb.set_trace()\n train_loss.append(obj_loss.item())\n model.zero_grad(); obj_loss.backward(); optimizer.step()\n\n train_loss = np.mean(train_loss)\n\n t1 = time()\n\n # evaluate the performance of the model with following xxx \n model.eval()\n\n val_preds, val_labels, val_keys = [], [], []\n for batch_idx_list in val_batch_sampler:\n user_indexes, his_input_title, pred_input_title, labels, keys = \\\n val_dataset._get_batch(batch_idx_list)\n preds = model.predict(user_indexes, his_input_title, pred_input_title) \n val_preds.extend(tensorToScalar(preds))\n val_labels.extend(labels)\n val_keys.extend(keys)\n\n #import pdb; pdb.set_trace()\n auc, mrr, ndcg_5, ndcg_10 = evaluate(val_labels, val_preds, val_keys)\n t2 = time()\n\n # save model when auc > max_auc\n if epoch == 1:\n max_auc = auc\n if auc > max_auc:\n torch.save(model.state_dict(), train_model_path)\n max_auc = max(auc, max_auc)\n\n log.record('Training Stage: Epoch:%d, compute loss cost:%.4fs, evaluation cost:%.4fs' % (epoch, (t1-t0), (t2-t1)))\n log.record('Train loss:{:.4f}'.format(train_loss))\n log.record('auc:%.4f, mrr:%.4f, ndcg@5:%.4f, ndcg@10:%.4f' % (auc, mrr, ndcg_5, ndcg_10))","sub_path":"lstur/train_lstru.py","file_name":"train_lstru.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"200832590","text":"#!/usr/bin/env python\n\n##### imports #####\nimport os\nimport sys\nimport time\nimport ConfigParser\nfrom testlib.base.base_utils import get_args\nfrom testlib.scripts.android.adb import adb_steps\nfrom testlib.scripts.android.fastboot import fastboot_steps\nfrom testlib.scripts.android.fastboot import fastboot_utils\n\n##### initialization #####\nglobals().update(vars(get_args(sys.argv)))\nargs = {}\nfor entry in script_args:\n\tkey, val = entry.split(\"=\")\n\targs[key] = val\nflash_files = args[\"flash_files\"]\n\n##### test start #####\ntry:\n\tos.system(\"mkdir -p ./temp/files/flash ./temp/image/n/img\")\n\tfastboot_utils.download_flash_scripts()\n\n\tconf_url = \"https://shstor001.sh.intel.com/artifactory/acs_test_artifacts/OTC_Android_Auto_Test_Suite/resources/EBImage/System_FastBoot/fastboot.conf\"\n\tfastboot_utils.download_file(url=conf_url, local_filename=\"./temp/fastboot.conf\")\n\tconfig = ConfigParser.ConfigParser()\n\tconfig.read(\"./temp/fastboot.conf\")\n\tfastboot_path = config.get(\"fastboot\", \"path\")\n\n\tplatform_name = fastboot_utils.get_platform_name(serial=serial)\n\tif platform_name == \"bxtp_abl\": image_platform = \"image_m_bxt\"\n\tif platform_name == \"gordon_peak\":\n\t\tram_value = fastboot_utils.get_bxt_ram(serial=serial)\n\t\tif ram_value == \"2g\": image_platform = \"image_o_bxt_2g\"\n\t\tif ram_value == \"4g\": image_platform = \"image_o_bxt_4g\"\n\t\tif ram_value == \"8g\": image_platform = \"image_o_bxt_4g\"\n\tsystem_corrupted_verity_path = config.get(image_platform, \"system_corrupted_verity\")\n\tsystem_corrupted_verity_name = system_corrupted_verity_path.split(\"/\")[-1]\n\tfastboot_utils.download_file(url = fastboot_path + system_corrupted_verity_path, local_filename = \"./temp/image/n/img/\" + system_corrupted_verity_name)\n\n\tadb_steps.reboot(command = \"fastboot\", reboot_timeout = 300, serial = serial)()\n\tfastboot_steps.flash_image(partition_name = \"system\", file_name = \"./temp/image/n/img/\"+system_corrupted_verity_name, lock_dut = True, serial = serial)()\n\n\tcheck_point1 = False\n\tcheck_point2 = False\n\n\tfastboot_utils.start_minicom(serial=serial)\n\n\tos.system(\"fastboot reboot > /dev/null 2>&1\")\n\ttime.sleep(60)\n\tfastboot_utils.to_fastboot_by_script(serial=serial)\n\n\tfastboot_utils.kill_minicom()\n\n\tfile_path = \"./temp/files/minicom_result.txt\"\n\treturn_result = open(file_path).readlines()\n\tfor line in return_result:\n\t\tif \"device-mapper: verity\" in line and \"metadata block\" in line and \"is corrupted\" in line: check_point1 = True\n\t\tif \"Restarting system with command 'dm-verity device corrupted'\" in line: check_point2 = True\n\n\tif not check_point1 or not check_point2:\n\t\traise Exception(\"The test result did not achieve the desired results\")\n\n\tfastboot_utils.flash_bxt(zip_file=flash_files, serial=serial)\n\tos.system(\"sudo rm -rf ./temp\")\n\nexcept:\n\tfastboot_utils.kill_minicom()\n\tfastboot_utils.flash_bxt(zip_file=flash_files, serial=serial)\n\tos.system(\"sudo rm -rf ./temp\")\n\traise\n##### test end #####","sub_path":"ACS_v.18.20.4_1/ACS/testlib/scripts/android/fastboot/tests_bxt-p/system_not_mount_if_hashtree_was_altered_o.py","file_name":"system_not_mount_if_hashtree_was_altered_o.py","file_ext":"py","file_size_in_byte":2883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"259719193","text":"'''\nFile that creates a .mp4 file of the change in solution files. \n'''\n\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.interpolate as sp\nfrom matplotlib import animation\n\ndef init():\n\tfilename = sys.argv[2] + \"000.txt\"\n\tsolution = np.loadtxt(filename, skiprows = 0)\n\n\t# build data for color plot\n\tX = np.arange(0, x+h, h)\n\tY = np.arange(0, y+h, h)\n\tX, Y = np.meshgrid(X, Y)\n\twrap = solution[:,solution.shape[1]-1]\n\tZ = np.c_[wrap, solution]\n\t\n\tplt.pcolor(X, Y, Z)\n\tplt.xticks(np.arange(0, x+h, .2))\n\tplt.xlabel('X')\n\tplt.yticks(np.arange(-y, y*2 + h, .2))\n\tplt.ylabel('Y')\n\tplt.title('Pseudocolor Plot for {}'.format(filename))\n\ndef animate(i):\n\tfilename = sys.argv[2] + str(i).zfill(3) + \".txt\"\n\tsolution = np.loadtxt(filename, skiprows = 0)\n\n\t# build data for color plot\n\tX = np.arange(0, x+h, h)\n\tY = np.arange(0, y+h, h)\n\tX, Y = np.meshgrid(X, Y)\n\twrap = solution[:,solution.shape[1]-1]\n\tZ = np.c_[wrap, solution]\n\t\n\tplt.pcolor(X, Y, Z)\n\tplt.xticks(np.arange(0, x+h, .2))\n\tplt.xlabel('X')\n\tplt.yticks(np.arange(-y, y*2 + h, .2))\n\tplt.ylabel('Y')\n\tplt.title('Pseudocolor Plot for {}'.format(filename))\n\ndef find_nearest(array,value):\n idx = (np.abs(array-value)).argmin()\n return idx\n\nif len(sys.argv) < 4:\n\tprint('Usage:')\n\tprint(' python {} '.format(sys.argv[0]))\n\texit()\n\ntry:\n\tf = open(sys.argv[1], 'r')\n\ttext = f.read().splitlines()\n\tline1 = text[0].split(' ')\n\tline2 = text[1].split(' ')\n\tx = float(line1[0])\n\ty = float(line1[1])\n\th = float(line1[2])\n\tTc = float(line2[0])\n\tTh = float(line2[1])\n\tf.close()\nexcept:\n\traise RuntimeError (\"The file {} entered does not exist.\".format(sys.argv[1]))\n\texit()\n\nfig = plt.figure()\nax = plt.axes(xlim=(0, x), ylim=(-y, 2*y))\nline, = ax.plot([], [], lw=2)\n\nmax_iter = int(sys.argv[3])\niter_range = range(10, (max_iter / 10) * 10 + 10, 10)\niter_range.append(max_iter)\n\nanim = animation.FuncAnimation(fig, animate, init_func=init,\n frames=iter_range, interval=50, blit=False)\n\nanim.save('bonus_' + sys.argv[1].split('.')[0] + '.mp4', fps=2, extra_args=['-vcodec', 'libx264'])\n","sub_path":"Courses/F15/CME211/homework/project/bonus.py","file_name":"bonus.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"53861342","text":"#!/usr/bin/env python3\n# Principles of Data Mining with Dr. Kinsman: HW 04\n# Author: Alvin Lin (axl1439)\n\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nTRAINING_FILE = 'Recipes_For_Release_2181_v202.csv'\nINDENT = ' '\n\nBASE_CODE = \"\"\"#!/usr/bin/env python3\nimport numpy as np\n\nVALIDATION_FILE = 'Recipes_For_VALIDATION_2181_RELEASED_v202.csv'\n\ndef preprocess_training_data_row(row):\n row = row.split(',')\n row[0] = 0 if row[0] == 'Muffin' else 1\n return list(map(float, row))\n\ndef main():\n with open(VALIDATION_FILE) as f:\n header = f.readline()\n for row in f:\n data = preprocess_training_data_row(row)\n{}\n print(category)\n\nif __name__ == '__main__':\n main()\n\"\"\"\n\nclass DecisionTreeNode():\n def __init__(self):\n self.data = None\n self.left = None\n self.right = None\n\ndef preprocess_training_data_row(row):\n \"\"\"\n Preprocessing for a training data row. Zaps Muffin to 0 and Cupcake to 1\n for numpy processing.\n \"\"\"\n row = row.split(',')\n row[0] = 0 if row[0] == 'Muffin' else 1\n return list(map(float, row))\n\ndef get_training_data():\n \"\"\"\n Returns the training data in the csv file.\n \"\"\"\n with open(TRAINING_FILE) as f:\n header = f.readline().strip().split(',')\n types = {}\n for i, label in enumerate(header):\n types[label] = i\n return types, np.array([preprocess_training_data_row(row) for row in f])\n\ndef get_mixed_gini_index(lt, gte):\n \"\"\"\n Calculates the mixed Gini index based on the cupcake/muffin similarity\n given the two splits.\n \"\"\"\n p_cupcake_lt = np.sum(lt[:,0]) / len(lt)\n p_cupcake_gte = np.sum(gte[:,0]) / len(gte)\n gini_index_lt = 1 - (p_cupcake_lt ** 2) - ((1 - p_cupcake_lt) ** 2)\n gini_index_gte = 1 - (p_cupcake_gte ** 2) - ((1 - p_cupcake_gte) ** 2)\n return (gini_index_lt + gini_index_gte) / 2\n\ndef get_majority_class(data):\n \"\"\"\n Returns the majority class of a given chunk of data.\n \"\"\"\n muffin = np.sum(data[:,0] == 0)\n if muffin > len(data) - muffin:\n return 'Muffin'\n return 'Cupcake'\n\ndef train(types, data, root, depth, max_depth=2):\n \"\"\"\n Generate a tree of DecisionTreeNode objects on the given data.\n \"\"\"\n best_gini_index = math.inf\n best_split_type = None\n best_split_value = None\n for t in range(1, 26):\n type_values = data[:,t]\n low = math.floor(min(type_values))\n high = math.ceil(max(type_values) + 1)\n for value in range(low, high):\n lt = data[type_values < value]\n gte = data[type_values >= value]\n if len(lt) == 0 or len(gte) == 0:\n continue\n gini_index = get_mixed_gini_index(lt, gte)\n if gini_index < best_gini_index:\n best_split_type = t\n best_split_value = value\n best_gini_index = gini_index\n split_type_column = data[:,best_split_type]\n lt = data[split_type_column < best_split_value]\n gte = data[split_type_column >= best_split_value]\n root.left = DecisionTreeNode()\n root.right = DecisionTreeNode()\n root.data = 'if data[{}] >= {}:\\n'.format(\n best_split_type, best_split_value)\n if depth == max_depth:\n left_majority_class = get_majority_class(lt)\n right_majority_class = 'Cupcake' if (\n left_majority_class == 'Muffin') else 'Muffin'\n root.left.data = 'category = \\'{}\\'\\n'.format(left_majority_class)\n root.right.data = 'category = \\'{}\\'\\n'.format(right_majority_class)\n else:\n train(types, lt, root.left, depth + 1, max_depth)\n train(types, gte, root.right, depth + 1, max_depth)\n\ndef tree_to_code(root_node, base_indent=''):\n \"\"\"\n Generate Python code from a tree of DecisionTreeNode objects.\n \"\"\"\n def recursive_helper(root, accum, indent=base_indent):\n accum += indent + root.data\n if root.left is not None and root.right is not None:\n accum += recursive_helper(root.right, '', indent + INDENT)\n accum += indent + 'else:\\n'\n accum += recursive_helper(root.left, '', indent + INDENT)\n return accum\n return recursive_helper(root_node, '', base_indent)\n\ndef main():\n types, data = get_training_data()\n root = DecisionTreeNode()\n train(types, data, root, 0, max_depth=1)\n classifier_code = BASE_CODE.format(tree_to_code(root, INDENT * 3))\n print(classifier_code)\n with open('HW_05_Lin_Alvin_Classifier.py', 'w') as f:\n f.write(classifier_code)\n\nif __name__ == '__main__':\n main()\n","sub_path":"cs420/HW_04_Lin_Alvin/HW_04_Lin_Alvin_Trainer.py","file_name":"HW_04_Lin_Alvin_Trainer.py","file_ext":"py","file_size_in_byte":4595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"148049514","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\nfrom joblib import dump, load\r\nimport time\r\n\r\nreferenceType = 'battery'\r\ndesk = 'brisk'\r\ninit_desk = cv2.BRISK_create()\r\nmovie_name = 'videoBattery.mp4'\r\nreference = cv2.imread('originals/referenceBattery.jpg', 0)\r\nreplace = cv2.imread('casperFace.jpg')\r\n\r\nMIN_MATCH_COUNT = 12\r\n\r\nFLANN_INDEX_LSH = 6\r\nindex_params = dict(algorithm=FLANN_INDEX_LSH, table_number=6, key_size=12, multi_probe_level=1)\r\nsearch_params = dict(checks=50)\r\nflann = cv2.FlannBasedMatcher(index_params, search_params)\r\n\r\ndescriptor_list = ['brisk']\r\nkmeans = dict()\r\nfor i in descriptor_list:\r\n kmeans[i] = load(f'written_models/{i}_kmeans.joblib');\r\nforest = dict()\r\nfor i in descriptor_list:\r\n forest[i] = load(f'written_models/{i}_forest.joblib')\r\n\r\n\r\nbrisk = cv2.BRISK_create()\r\n\r\ndescriptor = dict()\r\ndescriptor['brisk'] = brisk\r\n\r\nreplace2 = replace\r\nreplace = cv2.cvtColor(replace, cv2.COLOR_BGR2GRAY)\r\n\r\n\r\ndef create_bag(labels_list):\r\n res = np.zeros((10 * 4,))\r\n for i in labels_list:\r\n res[i] += 1\r\n return res\r\n\r\n\r\ndef preprocess_image(img, estimator):\r\n img = cv2.resize(img, (img.shape[0] // 4, img.shape[1] // 4))\r\n kp, des = descriptor[estimator].detectAndCompute(img, None)\r\n if (des is None):\r\n return None\r\n des = des.astype('float32')\r\n if (des.shape[0] > 500):\r\n des = des[:500, :]\r\n kmeans_labels = kmeans[estimator].predict(des)\r\n bag_of_words = create_bag(kmeans_labels)\r\n return bag_of_words\r\n\r\n\r\ncap = cv2.VideoCapture(movie_name)\r\n\r\nfps = []\r\ncount = 0\r\nimg = replace\r\nimg1 = reference\r\nkp1, des1 = init_desk.detectAndCompute(img1, None)\r\nstart = time.time()\r\ni = 0\r\n\r\nwhile (cap.isOpened()):\r\n\r\n ret, frame = cap.read()\r\n if ret == True:\r\n frame2 = frame\r\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n\r\n vect = dict()\r\n\r\n vect[desk] = preprocess_image(frame, desk)\r\n\r\n temp = vect[desk].reshape((1, vect[desk].shape[0]))\r\n pred = logreg[desk].predict(temp)[0]\r\n\r\n\r\n if (pred == referenceType):\r\n\r\n kp2, des2 = init_desk.detectAndCompute(frame, None)\r\n matches = flann.knnMatch(des1, des2, k=2)\r\n\r\n good = []\r\n\r\n for i in matches:\r\n if (len(i) > 1):\r\n m = i[0]\r\n n = i[1]\r\n if m.distance < 0.7 * n.distance:\r\n good.append(m)\r\n\r\n if len(good) > MIN_MATCH_COUNT:\r\n src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)\r\n dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)\r\n\r\n M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)\r\n matchesMask = mask.ravel().tolist()\r\n\r\n h, w = img1.shape\r\n pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)\r\n dst = cv2.perspectiveTransform(pts, M)\r\n frame = cv2.polylines(frame, [np.int32(dst)], True, 255, 3, cv2.LINE_AA)\r\n h, w = img.shape # строим переобзование точек со 100 грн на 10 грн\r\n pts2 = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)\r\n matrix = cv2.getPerspectiveTransform(pts2, dst)\r\n rows, cols = frame.shape\r\n result = cv2.warpPerspective(replace2, matrix, (cols, rows))\r\n result = cv2.addWeighted(result, 0.8, frame2, 0.5, 1) # склеиваем картинки\r\n\r\n cv2.imshow('Frame', result)\r\n cv2.imwrite(f'resultIm{count}.jpg', result)\r\n\r\n else:\r\n print(\"Not enough matches are found :cry: - %d/%d\" % (len(good), MIN_MATCH_COUNT))\r\n matchesMask = None\r\n cv2.imshow('Frame', frame2)\r\n else:\r\n cv2.imshow('Frame', frame2)\r\n else:\r\n break\r\n count += 1 # для вывода фпс\r\n if (time.time() - start > 1):\r\n fps.append(count)\r\n count = 0\r\n start = time.time()\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n","sub_path":"CVPR L4/lab4.py","file_name":"lab4.py","file_ext":"py","file_size_in_byte":4289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"368722516","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = \"Benny Longwill\"\n__email__ = \"longwill@uw.edu\"\n\n\nfrom nltk import word_tokenize, sent_tokenize, pos_tag, PorterStemmer\n\nfrom nltk.corpus import stopwords\n\nfrom bs4 import BeautifulSoup\nimport document_retriever\nfrom content_realization import get_compressed_sentences\nfrom math import log\nimport os # os module imported here to open multiple files at once\nimport spacy\n\nspacy_parser = spacy.load('/home/longwill/en_core_web_md/en_core_web_md-2.1.0')\nstop_words = set(stopwords.words('english'))\n\n\n#### Put none for non-existing text\n###############################\nclass Topic:\n idf_type=None #### Default value\n tf_type=None\n def __init__(self, topic_id:str=None ,docsetA_id:str=None, title:str=None , narrative:str=None, category=None):\n self.doc_count = 0\n self.sent_count = 0\n self.topic_id=topic_id\n self.docsetA_id=docsetA_id\n self.raw_counts = {} ##### Used for counts across all sentences\n self.tf_norm_values= {}\n ############### Creates and adds title and narrative and category Sentence Objects To Topic\n self.title = Sentence.create_sentence(self, title)\n self.narrative = Sentence.create_sentence(self, narrative) ##### *** Not all topics have this attribute ***\n self.category=Sentence.create_sentence(self,category) ##### *** Not all topics have this attribute ***\n ##########################################################\n self.document_list=[]\n self.summary = []\n self.idf={}\n\n\n #Returns list of all sentences in Topic, including Title sentence, narrative sentences, and headlines\n def all_sentences(self)->list:\n\n total_sentences=[sentence for document in self.document_list for sentence in document.sentence_list]\n\n # checks the title in the topic\n if self.title:\n total_sentences.append(self.title)\n # checks the narrative in the topic\n if self.narrative:\n total_sentences.append(self.narrative)\n\n if self.category:\n total_sentences.append(self.category)\n\n # checks all headlines if available in every document in the topic\n total_sentences += [document.headline for document in self.document_list if document.headline]\n\n return total_sentences\n\n ##### Counts the sentences under this topic that contains a token parameter\n def n_containing(self, token):\n # checks all tokens in each sentence of every document in the topic\n count = sum(1 for document in self.document_list for sentence in document.sentence_list if\n token in sentence)\n\n # checks all headlines if available in every document in the topic\n count += sum(1 for document in self.document_list if document.headline if token in document.headline)\n\n # checks the title in the topic\n if self.title and token in self.title:\n count+=1\n # checks the narrative in the topic\n if self.narrative and token in self.narrative:\n count+=1\n\n return count\n\n\n #Take the ratio of the total number of documents to the number of documents containing any word.\n #Then it adds 1 to the devisor to avoid zero division and then takes the log otherwise the weight will be too high\n def get_smooth_idf(self, token):\n if token in self.idf:\n return self.idf[token]\n else:\n current_idf = log(self.sent_count / (1 + self.n_containing(token)))\n self.idf[token]=current_idf\n return current_idf\n\n #AKA unary IDF score, i.e. don't use IDF\n def get_unary_idf(self):\n return 1\n\n #he logarithm of the number of documents in the corpus divided by the number of documents the term appears\n # in (this will lead to negative scores for terms appearing in all documents in the corpus)\n def get_standard_idf(self, token):\n if token in self.idf:\n return self.idf[token]\n else:\n current_idf = -log(self.n_containing(token)/self.sent_count)\n\n self.idf[token] = current_idf\n return current_idf\n\n #similar to inverse but substracting the number of documents the term appears in from the\n ## total number of documents in the training corpus (this can lead to positive and negative scores)\n def get_probabilistic_idf(self, token):\n if token in self.idf:\n return self.idf[token]\n else:\n current_idf = log(self.sent_count-self.n_containing(token) / self.n_containing(token))\n self.idf[token] = current_idf\n return current_idf\n\n # Must be used after all Documents, Sentences, and Tokens have been filled.\n def compute_tf_idf(self):\n\n cluster_count=sum(self.raw_counts.values())\n\n #for sentence in doc.sentence_list + [self.title, self.narrative, doc.headline]:\n for sentence in self.all_sentences():\n if sentence:\n\n for token in sentence.token_list:\n token_value=token.token_value\n\n if token_value not in self.tf_norm_values.keys():\n raw_token_count=self.raw_counts.get(token_value)\n try:\n self.tf_norm_values.update({token_value: eval(\n 'Sentence.get_' + Topic.tf_type + '(cluster_count=cluster_count,raw_token_count=raw_token_count)')})\n except:\n self.tf_norm_values.update({token_value: Sentence.get_term_frequency(cluster_count=cluster_count, raw_token_count=raw_token_count)})\n\n\n try:\n idf=eval('self.get_' + Topic.idf_type +'(token_value)')\n except:\n idf=self.get_smooth_idf(token_value)\n\n sentence.tf_idf[token_value] = token.raw_count * idf #self.get_standard_idf(token)\n sentence.tf_idf_norm[token_value] = sentence.tf_norm_values[token_value] * idf\n\nclass Document:\n def __init__(self, parent_topic:Topic=None , doc_id:str=None, headline:str=None,date:str=None, category:str=None, document_text:str=None):\n self.parent_topic = parent_topic\n self.sent_count = 0\n self.doc_id=doc_id\n self.date=date\n self.category=category ##### *** Not all topics have this attribute ***\n self.sentence_list = self.create_sentence_list(document_text)\n ############### Creates and adds headline Sentence Objects To Topic\n self.headline = Sentence.create_sentence(self,headline) ##### *** Not all topics have this attribute ***\n\n if parent_topic:\n self.parent_topic.doc_count+=1 ### Increments parent count When initialized\n\n def __repr__(self):\n return str(self.sentence_list)\n # Less than method allows for sorting\n def __lt__(self, other):\n return (self.date < other.date)\n\n # Takes Document object and the text from doc file. The block of text is separated into sentences as sentence objects and also tokenized using NLTK.\n def create_sentence_list(self, doc_text)->list:\n sentence_list=[]\n\n for doc_sentence in sent_tokenize(doc_text):\n\n # Get compressed versions of the original sentence\n compressed_sentences = get_compressed_sentences(doc_sentence, spacy_parser, Document.remove_header, Document.remove_parens, Document.remove_quotes, Document.remove_appos, Document.remove_advcl, Document.remove_relcl, Document.remove_acl)\n # Add a sentence object for each compressed sentence\n for sent in compressed_sentences:\n\n current_sentence=Sentence(self, sent) #Creates sentence object\n current_sentence.index=len(sentence_list)\n sentence_list.append(current_sentence)\n\n return sentence_list\n\n#All sentences are part of a document of either Topic or Document type\nclass Sentence:\n ps = PorterStemmer()\n\n stemming=False\n lower=False\n\n def __init__(self,parent_doc:Document or Topic, original_sentence:str):\n self.score=0\n self.parent_doc=parent_doc\n self.original_sentence = original_sentence.replace(\"\\n\", \" \").strip().replace(\" \", \" \")\n self.nouns=set()\n self.sent_len = original_sentence.count(\" \") + 1 #Counts words in original sentence\n self.raw_counts = {}\n self.tf_norm_values={}\n self.token_list=self.create_token_list(self.original_sentence) ##### *** List of non-duplicate Tokens as Objects ***\n self.tf_idf={}\n self.tf_idf_norm={}\n\n # Increments parent count when initialized. If parent_doc is Document, then Topic sent_count is also incremented\n self.parent_doc.sent_count+=1\n if type(self.parent_doc) is Document and self.parent_doc.parent_topic:\n self.parent_doc.parent_topic.sent_count+=1\n self.index = -1\n\n def __repr__(self):\n return self.original_sentence\n # Less than method allows for sorting\n def __lt__(self, other):\n return (self.score < other.score)\n def __eq__(self, other):\n return (self.score == other.score)\n # allows the use of 'is' operator on Sentence object\n def __contains__(self, param):\n return any(token.token_value == param for token in self.token_list)\n\n ### Wrapper initializer that includes validation\n @classmethod\n def create_sentence(cls, self:Topic or Document, original_sentence: str):\n if original_sentence:\n sentence = Sentence(self, original_sentence)\n else:\n sentence = None\n return sentence\n\n @classmethod\n def get_term_frequency(cls,cluster_count,raw_token_count):\n return raw_token_count / cluster_count\n @classmethod\n def get_raw_count(cls,tokenized_sentence,token):\n return tokenized_sentence.count(token)\n @classmethod\n def get_log_normalization(cls,cluster_count, raw_token_count):\n return log(1+ raw_token_count )\n\n ##### I think this would be good to be implemented but reuqires extra planning\n #def get_augmented_frequency(self,tokenized_sentence,token):\n # return .5 + (.5 *tokenized_sentence.count(token)/ argmax word count in sentence )\n\n\n\n # Tokenizes a sentences and populates the sentence object with a token object list\n def create_token_list(self, original_sentence: str)->list:\n\n # Edits the original sentence to remove article formatting\n # This location was chosen so that all sentences that are tokenized (i.e., Title sentence) could also be effected by this\n token_list = []\n\n '''LOTS OF TOKEN LOOPING WITHIN SENT REQUIRED BECAUSE OF POS TAGGING'''\n #Tokenize sentence\n tokenized_sent = word_tokenize(original_sentence)\n\n #Must tokenize sentence before pos tagging\n #Captures only Nouns and adds to self.nouns set\n [self.nouns.add(token) for token,pos in pos_tag(tokenized_sent) if 'NN' in pos]\n\n #Lowercasing before pos tagging affects tags, so must do after as list\n if Sentence.lower:\n tokenized_sent = [token.lower() for token in tokenized_sent]\n\n #Can only stem one word at a time, can't stem whole sentence\n if Sentence.stemming: ##### THe stemmer also lowercases\n tokenized_sent = [Sentence.ps.stem(token) for token in tokenized_sent]\n\n for token in set(tokenized_sent):\n ''''######### Removes stop words #########'''''\n if token not in stop_words:\n\n raw_token_count = Sentence.get_raw_count(tokenized_sent, token)\n\n #Adds raw count to sentence\n self.raw_counts.update({token:raw_token_count})\n\n try:\n tf_norm = eval('Sentence.get_' + Topic.tf_type + '(cluster_count=len(tokenized_sent),raw_token_count=raw_token_count)')\n except:\n tf_norm = Sentence.get_term_frequency(len(tokenized_sent), raw_token_count)\n\n #Adds normalalized tf to sentence\n self.tf_norm_values.update({token: tf_norm})\n\n ##### Adds tokens raw counts to Parent Topic\n if type(self.parent_doc)==Topic:\n current_topic=self.parent_doc\n else:\n current_topic=self.parent_doc.parent_topic\n\n current_topic.raw_counts.update({token: current_topic.raw_counts.get(token,0)+raw_token_count})\n ###############################################\n\n token_list.append(Token(self, token, raw_token_count ,tf_norm))\n\n return token_list\n\n\nclass Token:\n def __init__(self,parent_sentence:Sentence, token_value:str, raw_count, tf_norm):\n self.raw_count=raw_count\n self.tf_norm=tf_norm\n self.parent_sentence=parent_sentence\n self.token_value=token_value\n def __repr__(self):\n return self.token_value\n\n###############################\n### Tag Variables used to avoid hardcoding later in the document or in case of tag changes\n\ntitle_tag='title'\nnarrative_tag='narrative'\ntopic_category_tag='category'\ndocsetA_tag='docseta'\nid_tag='id'\ndoc_tag='doc'\ntopic_tag='topic'\nparser_tag='lxml'\ncategories_file_tag='/categories.txt'\nheadline_tag='headline'\n\n###############################\n\n# Takes a file path, collects all data and stores into a list of class object 'Topic' data structures\ndef get_data(file_path:str, stemming:bool, lower:bool, idf_type, tf_type, remove_header, remove_parens, remove_quotes, remove_appos, remove_advcl, remove_relcl, remove_acl)->list:\n \"\"\"Extracts database documents and creates data structure objects to hold them. Returns a list of Topic objects\n\n Args:\n file_path:str file path on patas that leads to directory that holds training or testing data\n stemming:bool True enables each sentence to be stored with a stem representation in objects and tokens, False does nothing\n lower:bool True enables each sentence to be stored in lower case, False does nothing.\n idf_type:str String input dictates idf representation in objects. Options are: 'smooth_idf', 'probabilistic_idf' , 'standard_idf' , and 'unary_idf'\n tf_type:str String input dictates tf representation in objects. Options are: 'term_frequency', 'log_normalization'\n remove_header: True if the header should be removed from the sentence\n remove_parens: True if parenthetical information should be removed from the sentence\n remove_quotes: True if unpaired quotes should be removed from the sentence\n remove_appos: True if appositional modifier should be removed from the sentence\n remove_advcl: True if adverbial clause modifier should be removed from the sentence\n remove_relcl: True if relative clause modifier should be removed from the sentence\n remove_acl: True if a finite or non-finite clausal modifier shoule be removed from the sentence\n\n \"\"\"\n\n # Set all the hyperparamaters\n configure_class_objects(stemming, lower, idf_type, tf_type, remove_header, remove_parens, remove_quotes, remove_appos, remove_advcl, remove_relcl, remove_acl)\n\n with open(file_path) as f1:\n task_data = f1.read()\n\n soup = BeautifulSoup(task_data, parser_tag)\n raw_topics = soup.findAll(topic_tag)\n\n return get_topics_list(raw_topics, get_categories(file_path))\n\n# unary_idf smooth_idf standard_idf probabilistic_idf\ndef configure_class_objects(stemming:bool,lower:bool, idf_type:str, tf_type:str, remove_header, remove_parens, remove_quotes, remove_appos, remove_advcl, remove_relcl, remove_acl):\n\n if stemming:\n Sentence.stemming = stemming\n if lower:\n Sentence.lower=lower\n if idf_type:\n Topic.idf_type=idf_type\n if tf_type:\n Topic.tf_type=tf_type\n\n Document.remove_header = remove_header\n Document.remove_parens = remove_parens\n Document.remove_quotes = remove_quotes\n Document.remove_appos = remove_appos\n Document.remove_advcl = remove_advcl\n Document.remove_relcl = remove_relcl\n Document.remove_acl = remove_acl\n\ndef get_categories(file_path:str):\n\n try:\n with open(file_path.rsplit(\"/\",maxsplit=1)[0] + categories_file_tag) as f2:\n categories=f2.read().replace(\":\",\"\").replace(\"(\",\"\").replace(\")\",\"\").replace(\"/\",\" \")\n #Splits on two empty lines in a row\n bag_of_words={}\n for category in categories.split(\"\\n\\n\\n\")[1:]:\n lines=category.strip().split(\"\\n\")\n index, words = lines[0].split(\" \", maxsplit= 1)\n index=index.rstrip(\".\")\n\n bag_of_words.update({index : words.strip().split(\" \")})\n for line in lines[1:]:\n bag_of_words[index]+=line.split()[1:]\n\n return bag_of_words\n\n except FileNotFoundError:\n return None\n\n\n#Takes a Topic class object, an xml or html document set element, and a document retriever object\n# Itterates all document Id's in html/xml element and uses the doc retriever to get the raw document from database\n#Extracts attributes from raw document and creates Document class object, fills it with sentence objects and adds it to the current topic object\ndef populate_document_list(current_topic, docsetA, doc_ret:document_retriever.Document_Retriever):\n\n for doc in docsetA.findAll(doc_tag):\n\n doc_id = doc.attrs[id_tag]\n\n raw_doc = doc_ret.retrieve_doc(doc_id)\n headline, category, dateline, doc_text = get_doc_attributes(raw_doc, doc_ret.headline_tag, doc_ret.category_tag, doc_ret.dateline_tag, doc_ret.text_tag)\n\n current_doc = Document(parent_topic=current_topic, doc_id=doc_id, date=doc_ret.date,headline=headline, category=category, document_text=doc_text) ########## Creates document object\n\n current_topic.document_list.append(current_doc)\n\n# Takes the raw topic xml/html and a set of title, narrative, and docset TAGS according to the format of file\n# extracts the respective text including document IDs for Aqcuaint(2) database\ndef get_topic_attributes(raw_topic, title_tag:str , narrative_tag:str, topic_category_tag:str, docsetA_tag:str):\n\n narrative=None\n title=None\n topic_category=None\n\n topic_id = raw_topic.attrs[id_tag]\n\n if title_tag:\n title_element = raw_topic.find(title_tag)\n if title_element is not None:\n title = title_element.text\n\n if narrative_tag:\n narrative_element = raw_topic.find(narrative_tag)\n if narrative_element is not None:\n narrative = narrative_element.text\n\n if topic_category_tag:\n category_element=raw_topic.attrs.get(topic_category_tag)\n if category_element is not None:\n topic_category=category_element\n\n\n\n docsetA = raw_topic.find(docsetA_tag)\n\n docsetA_id = docsetA.attrs[id_tag]\n\n return topic_id, title, narrative, docsetA_id, docsetA, topic_category\n\n# Requires raw document and the specific tags used according to current HTML or XML.\n# Extracts the headline category dateline and text if available in raw document.\ndef get_doc_attributes(raw_doc, headline_tag:str=\"\", category_tag:str=\"\", dateline_tag:str=\"\", text_tag:str=\"\"):\n\n ### Instantiate variables in case text not available in raw doc\n headline = None\n category = None\n dateline = None\n doc_text = None\n\n\n\n if headline_tag:\n headline_element = raw_doc.find(headline_tag)\n if headline_element is not None:\n headline = headline_element.text\n\n\n if category_tag:\n category_element = raw_doc.find(category_tag)\n if category_element is not None:\n category = category_element.text\n\n\n if dateline_tag:\n dateline_element = raw_doc.find(dateline_tag)\n if dateline_element is not None:\n dateline = dateline_element.text\n\n\n if text_tag:\n doc_text=' '.join(raw_doc.find(text_tag).itertext())\n\n\n return headline, category, dateline, doc_text\n\n#Parses Raw data XML file argument and extracts the topic elements.\n# Creates Topic elements and fills withtopic attributes and Document objects\n# Returns these topic objects as a list.\ndef get_topics_list(raw_topics, topic_categories)->list:\n topics=[]\n doc_ret = document_retriever.Document_Retriever()\n\n for raw_topic in raw_topics:\n topic_id, title, narrative, docsetA_id, docsetA, topic_category = get_topic_attributes(raw_topic, title_tag, narrative_tag,topic_category_tag, docsetA_tag)\n\n if topic_category:\n topic_category = \" \".join(topic_categories[topic_category])\n\n current_topic= Topic(topic_id = topic_id,docsetA_id = docsetA_id, title = title, narrative = narrative, category=topic_category) ########### Creates topic object\n\n populate_document_list(current_topic, docsetA, doc_ret)\n\n current_topic.compute_tf_idf()\n\n topics.append(current_topic)\n\n return topics\n\n###############################\n\n\n'''''''''''''''''''''''''''''''''''''''''''''\nMethod used to create dummy data structures for testing purposes : Requires formatted Topic file\n'''''''''''''''''''''''''''''''''''''''''''''\ndef build_pseudo_topic(pseudo_document_file_path, stemming:bool=False, lower:bool=False, idf_type:str=None, tf_type:str=None):\n\n configure_class_objects(stemming,lower, idf_type, tf_type)\n\n #```doc_id = 1a \\n date = 20110506 \\n ### \\n Sentence 1 would be here. \\n Sentence 2 would be here, etc.```\n # (where ### is a metadata separator and everything below that would be a sentence on its own line)\n with open(pseudo_document_file_path) as f1:\n #Parses whole document by empty line\n topic_meta_data, pseudo_docs=f1.read().split(\"\\n\\n\", maxsplit=1)\n\n\n #Puts topic meta-data into dictionary\n topic_meta_data = dict((x.strip(),y.strip()) for x,y in [data.split(\"=\") for data in topic_meta_data.split(\"\\n\")])\n\n #Loads empty topic object with topic metadata from dictionary\n current_topic=None\n try:\n current_topic=Topic(**topic_meta_data)\n except Exception as e:\n\n print(e)\n\n #Separates documents then document metadata from sentences and loads them into a dictionary\n #Calls populate sentences to finish filling remaining data structures\n for doc in pseudo_docs.split(\"\\n\\n\"):\n doc_meta_data, sentences=doc.split(\"###\")\n doc_meta_data=dict([data.split(\"=\") for data in doc_meta_data.replace(\" \",\"\").split()])\n\n\n try:\n current_doc = Document(parent_topic=current_topic, document_text=sentences.strip().replace(\"\\n\", \" \"),**doc_meta_data)\n current_topic.document_list.append(current_doc)\n except Exception as e:\n print(e)\n\n\n current_topic.compute_tf_idf()\n\n\n return current_topic\n\n\n'''''''''''''''''''''''''''''''''''''''''''''\nMethod used to create dummy data structures for the Gold Standard data\n'''''''''''''''''''''''''''''''''''''''''''''\ndef get_gold_standard_docs(file_path:str)->list:\n return [Document(parent_topic=Topic(),document_text=open(file_path+\"/\"+file_name).read()) for file_name in os.listdir(file_path)]\n","sub_path":"src/data_input.py","file_name":"data_input.py","file_ext":"py","file_size_in_byte":23227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"251625211","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.template import loader\nimport os\nimport json\n\ndef call(req,mobileNum):\n os.system(\"termux-telephony-call \"+str(mobileNum))\n return HttpResponse(\"

hello2

\")\ndef contacts(req):\n try:\n contactsList=open('data.json').read()\n except:\n print(\"rename data_sample.json to data.json\")\n contactsList=open('data_sample.json').read()\n context = {\n 'contactsList': json.loads(contactsList),\n }\n return render(req, 'calling/index.html', context)","sub_path":"calling/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"502352867","text":"#!/usr/bin/env python\n\n#Node that is used to control the height of the robot's linear actuators\nfrom math import pi, cos, sin\n\nimport diagnostic_msgs\nimport diagnostic_updater\nimport roboclaw_driver.roboclaw_driver as roboclaw\nimport rospy\nimport tf\nimport signal\nfrom geometry_msgs.msg import Quaternion, Twist\nfrom nav_msgs.msg import Odometry\nfrom sensor_msgs.msg import JointState\nfrom std_msgs.msg import Header\n\n__author__ = \"bwbazemore@uga.edu (Brad Bazemore)\"\n\ndef timeout_handler(signum, frame):\n raise Exception(\"serial write hanging\")\n\nclass Node:\n def __init__(self):\n\n self.ERRORS = {0x0000: (diagnostic_msgs.msg.DiagnosticStatus.OK, \"Normal\"),\n 0x0001: (diagnostic_msgs.msg.DiagnosticStatus.WARN, \"M1 over current\"),\n 0x0002: (diagnostic_msgs.msg.DiagnosticStatus.WARN, \"M2 over current\"),\n 0x0004: (diagnostic_msgs.msg.DiagnosticStatus.ERROR, \"Emergency Stop\"),\n 0x0008: (diagnostic_msgs.msg.DiagnosticStatus.ERROR, \"Temperature1\"),\n 0x0010: (diagnostic_msgs.msg.DiagnosticStatus.ERROR, \"Temperature2\"),\n 0x0020: (diagnostic_msgs.msg.DiagnosticStatus.ERROR, \"Main batt voltage high\"),\n 0x0040: (diagnostic_msgs.msg.DiagnosticStatus.ERROR, \"Logic batt voltage high\"),\n 0x0080: (diagnostic_msgs.msg.DiagnosticStatus.ERROR, \"Logic batt voltage low\"),\n 0x0100: (diagnostic_msgs.msg.DiagnosticStatus.WARN, \"M1 driver fault\"),\n 0x0200: (diagnostic_msgs.msg.DiagnosticStatus.WARN, \"M2 driver fault\"),\n 0x0400: (diagnostic_msgs.msg.DiagnosticStatus.WARN, \"Main batt voltage high\"),\n 0x0800: (diagnostic_msgs.msg.DiagnosticStatus.WARN, \"Main batt voltage low\"),\n 0x1000: (diagnostic_msgs.msg.DiagnosticStatus.WARN, \"Temperature1\"),\n 0x2000: (diagnostic_msgs.msg.DiagnosticStatus.WARN, \"Temperature2\"),\n 0x4000: (diagnostic_msgs.msg.DiagnosticStatus.OK, \"M1 home\"),\n 0x8000: (diagnostic_msgs.msg.DiagnosticStatus.OK, \"M2 home\")}\n \n rospy.init_node(\"roboclaw_node_height\")\n rospy.on_shutdown(self.shutdown)\n rospy.loginfo(\"Connecting to roboclaw\")\n self.dev_name = rospy.get_param(\"~dev\", \"/dev/ttyACM2\") #may need to change the usb port\n\n self.baud_rate = int(rospy.get_param(\"~baud\", \"38400\")) #may need to change the baud rate. see roboclaw usermanual\n\n self.address = int(rospy.get_param(\"~address\", \"129\")) #roboclaw is current setup to use address 128 which is setting 7\n\n\n #Error Handle\n if self.address > 0x87 or self.address < 0x80:\n rospy.logfatal(\"Address out of range\")\n rospy.signal_shutdown(\"Address out of range\")\n \n # TODO need someway to check if address is correct\n try:\n roboclaw.Open(self.dev_name, self.baud_rate)\n except Exception as e:\n rospy.logfatal(\"Could not connect to Roboclaw\")\n rospy.logdebug(e)\n rospy.signal_shutdown(\"Could not connect to Roboclaw\")\n \n self.updater = diagnostic_updater.Updater()\n self.updater.setHardwareID(\"Roboclaw\")\n self.updater.add(diagnostic_updater.FunctionDiagnosticTask(\"Vitals\", self.check_vitals))\n\n try:\n version = roboclaw.ReadVersion(self.address)\n except Exception as e:\n rospy.logwarn(\"Problem getting roboclaw version\")\n rospy.logdebug(e)\n pass\n\n if not version[0]:\n rospy.logwarn(\"Could not get version from roboclaw\")\n else:\n rospy.logdebug(repr(version[1]))\n\n roboclaw.SpeedM1M2(self.address, 0, 0)\n roboclaw.ResetEncoders(self.address)\n\n self.MAX_SPEED = float(rospy.get_param(\"~max_speed\", \"127\"))\n self.MAX_DUTY = float(rospy.get_param(\"~max_duty\", \"32767\"))\n\n self.last_set_speed_time = rospy.get_rostime()\n\n self.height_vel_sub = rospy.Subscriber(\"roboclaw/height_vel\", Twist, self.cmd_vel_callback)\n self.height_pub = rospy.Publisher(\"roboclaw/height\", JointState, queue_size=10)\n \n self.m1_duty = 0\n self.m2_duty = 0\n \n rospy.sleep(1)\n\n rospy.loginfo(\"dev %s\", self.dev_name)\n rospy.loginfo(\"baud %d\", self.baud_rate)\n rospy.loginfo(\"address %d\", self.address)\n rospy.loginfo(\"max_speed %f\", self.MAX_SPEED)\n\n def run(self):\n rospy.loginfo(\"Starting motor drive\")\n r_time = rospy.Rate(5)\n signal.signal(signal.SIGALRM, timeout_handler)\n \n while not rospy.is_shutdown():\n signal.setitimer(signal.ITIMER_REAL, 0.21, 0)\n \n try:\n if (rospy.get_rostime() - self.last_set_speed_time).to_sec() > 0.3:\n self.m1_duty = 0\n self.m2_duty = 0\n roboclaw.DutyM1M2(self.address,self.m1_duty,self.m2_duty)\n self.pub_enc_values()\n r_time.sleep()\n \n except Exception as e:\n rospy.loginfo(e)\n\n def pub_enc_values(self):\n height_state = JointState()\n height_state.header = Header()\n height_state.header.stamp = rospy.Time.now()\n height_state.name = ['m1', 'm2']\n enc1 = roboclaw.ReadEncM1(self.address)\n enc2 = roboclaw.ReadEncM2(self.address)\n height_state.position = [float(enc1[1]),float(enc2[1])]\n try:\n self.height_pub.publish(height_state)\n except Exception as e:\n rospy.loginfo(\"hanging\")\n rospy.logdebug(e)\n\n def cmd_vel_callback(self, twist):\n #twist 127 full forward, -127 full backward\n self.last_set_speed_time = rospy.get_rostime() \n self.m1_duty = self.twist_to_duty(twist.linear.x)\n self.m2_duty = self.twist_to_duty(twist.linear.y)\n \n def twist_to_duty(self, twist):\n return int((twist / self.MAX_SPEED) * self.MAX_DUTY)\n\n # TODO: Need to make this work when more than one error is raised\n def check_vitals(self, stat):\n try:\n status = roboclaw.ReadError(self.address)[1]\n except OSError as e:\n rospy.logwarn(\"Diagnostics OSError: %d\", e.errno)\n rospy.logdebug(e)\n return\n state, message = self.ERRORS[status]\n stat.summary(state, message)\n try:\n stat.add(\"Main Batt V:\", float(roboclaw.ReadMainBatteryVoltage(self.address)[1] / 10))\n stat.add(\"Logic Batt V:\", float(roboclaw.ReadLogicBatteryVoltage(self.address)[1] / 10))\n stat.add(\"Temp1 C:\", float(roboclaw.ReadTemp(self.address)[1] / 10))\n stat.add(\"Temp2 C:\", float(roboclaw.ReadTemp2(self.address)[1] / 10))\n \n \n except OSError as e:\n rospy.logwarn(\"Diagnostics OSError: %d\", e.errno)\n rospy.logdebug(e)\n return stat\n\n # TODO: need clean shutdown so motors stop even if new msgs are arriving\n def shutdown(self):\n rospy.loginfo(\"Shutting down\")\n self.height_vel_sub.unregister()\n try:\n roboclaw.ForwardM1(self.address, 0)\n roboclaw.ForwardM2(self.address, 0)\n\n except OSError:\n rospy.logerr(\"Shutdown did not work trying again\")\n try:\n roboclaw.ForwardM1(self.address, 0)\n roboclaw.ForwardM2(self.address, 0)\n \n except OSError as e:\n rospy.logerr(\"Could not shutdown motors!!!!\")\n rospy.logdebug(e)\n\n\nif __name__ == \"__main__\":\n try:\n node = Node()\n node.run()\n except rospy.ROSInterruptException:\n pass\n rospy.loginfo(\"Exiting\")\n","sub_path":"roboclaw_node/nodes/roboclaw_node_height.py","file_name":"roboclaw_node_height.py","file_ext":"py","file_size_in_byte":7921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"133488163","text":"from pyspark.sql import SparkSession\n\nspark = SparkSession.builder.appName(\"WordCount\").getOrCreate()\ndata = ['cat bat hat', 'bat mat cat', 'bat mat that']\n\n\ndef load_RDD(Spark, Data):\n myRDD = Spark.sparkContext.parallelize(Data)\n return myRDD\n\n\ndef wordcount_func(myRDD):\n words = myRDD.flatMap(lambda x: x.split(' ')).map(lambda a: (a, 1)).reduceByKey(lambda x, y: x + y)\n return words.collect()\n\n\nwordcount_func(load_RDD(spark, data))\n","sub_path":"com/uday/pyspark/WordCount.py","file_name":"WordCount.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"81895436","text":"import os\nfrom blockchain import Blockchain, Block\nimport discord\nimport asyncio\nimport ast\n\nDATA_DIR = 'data'\nNEW_DATA = 'new_data.txt'\nNOTE_CONVERT = 'CONVERT'\nNOTE_LOAD = 'LOAD'\nNOTE_TRANSFER = 'TRANSFER'\n\n\nclass BlockchainManager(object):\n\n def __init__(self, client, server_id, blockchain_channel_id):\n self.client = client\n self.server_id = server_id\n self.blockchain_channel_id = blockchain_channel_id\n self.blockchain = Blockchain()\n\n async def update_blockchain(self):\n print('Update blockchain')\n await self.client.wait_until_ready()\n server = self.client.get_guild(self.server_id)\n blockchain_channel = self.client.get_channel(self.blockchain_channel_id)\n print(self.client.is_closed())\n while not self.client.is_closed():\n if NEW_DATA in os.listdir(DATA_DIR):\n f = open(DATA_DIR + '/' + NEW_DATA, 'r')\n data = ''\n for line in f:\n data = line\n f.close()\n self.blockchain.mine(Block(data))\n os.remove(DATA_DIR + '/' + NEW_DATA)\n await blockchain_channel.send(self.blockchain.block)\n await asyncio.sleep(5)\n\n async def update_block(self, sender, receiver, amount, note):\n s_bal = await self.get_balance(sender)\n r_bal = await self.get_balance(receiver)\n print(s_bal, r_bal, amount)\n try:\n sender_bal = s_bal - amount\n receiver_bal = r_bal + amount\n if sender_bal >= 0:\n f = open(DATA_DIR + '/' + NEW_DATA, 'a+')\n # [sender_user_id, receiver_id, transver_amount, sender_new_bal]\n f.write('[\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\"],'.format(\n sender, receiver, amount, sender_bal, receiver_bal, note))\n f.close()\n return(True)\n else:\n return(False)\n except Exception as e:\n return(False)\n\n async def load_balance(self, receiver_id, amount):\n server_bal = await self.get_balance(self.server_id)\n f = open(DATA_DIR + '/' + NEW_DATA, 'a+')\n # [sender_user_id, receiver_id, transver_amount, sender_new_bal]\n f.write('[\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\"],'.format(\n self.server_id, receiver_id, amount, server_bal, amount, NOTE_LOAD))\n f.close()\n\n async def get_balance(self, blockchain_id):\n await self.client.wait_until_ready()\n server = self.client.get_guild(self.server_id)\n blockchain_channel = self.client.get_channel(self.blockchain_channel_id)\n messages = []\n counter = 0\n current_bal = None\n async for message in blockchain_channel.history(limit=None, oldest_first=False):\n try:\n data = message.content.split('\\n')[2].replace('Block Data: ', '')[:-1]\n data = '[' + data + ']'\n data = ast.literal_eval(data)\n should_break = False\n for t in data:\n if t[0] == str(blockchain_id):\n # print(t)\n # print('Current bal: {}'.format(t[3]))\n current_bal = float(t[3])\n should_break = True\n elif t[1] == str(blockchain_id):\n # print('id here')\n current_bal = float(t[4])\n should_break = True\n if should_break:\n break\n except Exception as e:\n print('Bad data: ', e)\n current_bal = None\n return(current_bal)\n\n\nclass IssueManager(object):\n\n def __init__(self, bm, commands_channel_id):\n self.bm = bm\n self.client = bm.client\n self.server_id = bm.server_id\n self.blockchain_channel_id = bm.blockchain_channel_id\n self.commands_channel_id = commands_channel_id\n self.issue_in_session = False\n\n async def get_issue(self, issue_id):\n issue_data = issue_id.split('-')\n server = self.client.get_guild(id=int(issue_data[0]))\n channel = self.client.get_channel(int(issue_data[1]))\n message = await channel.fetch_message(int(issue_data[2]))\n return(message.content.replace('!IBDD ', '').replace('\"', ''))\n\n async def non_voters_transver(self):\n await self.client.wait_until_ready()\n server = self.client.get_guild(id=self.server_id)\n channel = self.client.get_channel(self.blockchain_channel_id)\n counter = 0\n current_bal = None\n print(self.issue_in_session)\n for member in server.members:\n print(member.id)\n voted = False\n async for message in channel.history(limit=None, oldest_first=False):\n data = message.content.split('\\n')[2].replace('Block Data: ', '')[:-1]\n data = '[' + data + ']'\n data = ast.literal_eval(data)\n for t in data:\n if t[0] == str(member.id) and t[1] == self.issue_in_session:\n voted = True\n if voted:\n print(member.id, 'voted')\n else:\n await self.bm.update_block(member.id, self.issue_in_session, 0, NOTE_CONVERT)\n\n async def get_converts(self):\n server = self.client.get_guild(id=self.server_id)\n channel = self.client.get_channel(self.blockchain_channel_id)\n converts = 0\n convert_ids = []\n async for message in channel.history(limit=None, oldest_first=False):\n data = message.content.split('\\n')[2].replace('Block Data: ', '')[:-1]\n data = '[' + data + ']'\n data = ast.literal_eval(data)\n for t in data:\n if t[1] == self.issue_in_session and t[5] == NOTE_CONVERT:\n converts += 1\n convert_ids.append(t[0])\n return(converts, convert_ids)\n\n async def count_votes(self):\n await self.non_voters_transver()\n await asyncio.sleep(10) # change this for end vote check on BC\n sum_traded_votes, convert_ids = await self.get_converts()\n server_bal = await self.bm.get_balance(self.server_id)\n vote_price = round(float(server_bal)/float(sum_traded_votes), 2)\n for id in convert_ids:\n await self.bm.update_block(self.server_id, id, vote_price, NOTE_TRANSFER)\n print(sum_traded_votes, vote_price)\n\n async def issue_timer(self):\n server = self.client.get_guild(id=self.server_id)\n channel = self.client.get_channel(self.commands_channel_id)\n await asyncio.sleep(60*1)\n await channel.send(\"**1 min** remaining...\")\n await asyncio.sleep(60*1)\n await channel.send(\"*Vote finished*\")\n await self.count_votes()\n self.issue_in_session = False\n","sub_path":"discordibdd.py","file_name":"discordibdd.py","file_ext":"py","file_size_in_byte":6899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"247978758","text":"from result.HTMLTestRunner import HTMLTestRunner\nfrom unittest import unittest\nfrom testCase.testcase_login import Login\nfrom testCase.testcase_login_null import LoginNull\nfrom testCase.multilotto_get_config import TestML\n\n\nclass TestResult:\n\n suite = unittest.TestSuite()\n\n def get_html_report(self):\n with open(\"HTMLTestReport.html\", 'w') as f:\n runner = HTMLTestRunner(stream=f, title='testReport', description='generated by htmlTestReport', verbosity=3)\n runner.run(self.suite)\n\n def get_text_result(self):\n with open(\"textTestResult.txt\", 'a') as f:\n runner = unittest.TextTestRunner(stream=f, descriptions='generated by textTestReport', verbosity=2)\n runner.run(self.suite)\n\n\nif __name__ == \"__main__\":\n h1 = TestResult()\n h1.suite.addTest(Login('test_login'))\n tests = [LoginNull('test_login_null'), Login('test_login_error'), TestML('testGetnearbyplace')]\n h1.suite.addTests(tests)\n h1.get_html_report()\n\n","sub_path":"ML/result/testResult.py","file_name":"testResult.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"558700619","text":"import ast\nimport sys\n\nfileName = sys.argv[1]\n\nlines = []\nwith open(fileName, \"r\", encoding = 'utf-8', errors = 'ignore') as file:\n lines = file.readlines()\n#print(lines)\n\nlink = []\nfor line in lines :\n link.extend(ast.literal_eval(line))\nlink = set(link)\nwith open(\"linkList.txt\", \"a+\", encoding = 'utf-8', errors = 'ignore') as w:\n for l in link:\n w.write(str(l)+\"\\n\")\n#print(link)\n","sub_path":"comp6976_security/Source Code/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"138857948","text":"#!/usr/bin/env python\n\nimport os, sys\nimport argparse\nimport math\nimport numpy as np\nfrom utils import create_dir, SubmitBase\n\ngit_tag=os.popen('git describe --tags --abbrev=0').read()\n\nparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('-t', '--git-tag' , dest='gittag' , help='git tag version', default=git_tag)\nparser.add_argument( '--nRuns' , dest='nRuns' , type=int, help='number of run, 0-indexed', default=-1)\nparser.add_argument('-v', '--version' , dest='version' , type=int, help='detector version', default=3)\nparser.add_argument('-m', '--model' , dest='model' , type=int, help='detector model', default=3)\nparser.add_argument('-a', '--etas' , dest='etas' , type=float, help='incidence eta', nargs='+')\nparser.add_argument('-p', '--phi' , dest='phi' , type=float, help='incidence phi angle in pi unit' , default=0.5)\nparser.add_argument( '--shape' , dest='shape' , type=int, help='shape', default=1) # 1 = hexagons, 2=diamonds, 3=triangles, 4=squares\nparser.add_argument('-b', '--Bfield' , dest='Bfield' , type=float, help='B field value in Tesla' , default=0)\nparser.add_argument('-d', '--datatype' , dest='datatype' , help='data type or particle to shoot', default='e-')\nparser.add_argument('-f', '--datafile' , dest='datafile' , help='full path to HepMC input file', default='') #data/example_MyPythia.dat\nparser.add_argument('-F', '--datafileeos' , dest='datafileeos', help='EOS path to HepMC input file', default='') #/eos/cms/store/cmst3/group/hgcal/HGCalMinbias/Pythia8/\nparser.add_argument('-n', '--nevts' , dest='nevts' , type=int, help='number of events to generate' , default=1000)\nparser.add_argument( '--wcuseed' , dest='wcuseed' , type=int, help='Seed to use when randomizing WCu density' , default=42)\nparser.add_argument( '--wcuresol' , dest='wcuresol' , type=float, help='Relative resolution to use when randomizing WCu density' , default=-1)\nparser.add_argument('-o', '--out' , dest='out' , help='output directory' , default=os.getcwd() )\nparser.add_argument('-e', '--eosOut' , dest='eos' , help='eos path to save root file to EOS', default='')\nparser.add_argument('-g', '--gun' , dest='dogun' , help='use particle gun.', action=\"store_true\")\nparser.add_argument( '--enList' , dest='enList' , type=int, help='E_T list to use with gun', nargs='+', default=[5,10,20,30,40,60,80,100,150,200])\nparser.add_argument('-S', '--no-submit' , dest='nosubmit' , help='Do not submit batch job.', action=\"store_true\")\nopt, _ = parser.parse_known_args()\n\nprint(opt)\n\n###################################################################################################\n###################################################################################################\n###################################################################################################\nclass SubmitProd(SubmitBase):\n def __init__(self, **kwargs):\n super(SubmitProd, self).__init__(**kwargs)\n\n self.etaint_tag = '$(ETAX10)'\n \n #variables\n self.condor_submit_name = 'condorSubmitProd.sub'\n self.mac_var = '$(MACFILE)'\n self.mac_name = self._unique_name( (('prefix', 'g4steer'),\n ('en', self.shellify_tag(self.en_tag)),\n ('eta', self.shellify_tag(self.etaint_tag)),\n ('run', self.shellify_tag(self.run_tag)),\n ('ext', 'mac')) )\n\n self.tags = (self.en_tag, self.eta_tag, self.run_tag, self.gran_tag)\n self.labels = ('energy', 'eta', 'run', 'granularity')\n \n def gen_uniform_int_random_seeds_(self, low, high, size):\n np.random.seed()\n r = np.random.uniform(low=low, high=high, size=size)\n return [int(x) for x in r]\n \n def write_shell_script_file(self):\n with open('{}/runJob.sh'.format(self.outDir), 'w') as s:\n s.write('#!/usr/bin/env bash\\n')\n\n #input arguments: energy, eta and run\n s.write('ARGS=`getopt -o \"\" -l \",energy:,eta:,run:,granularity:\" -n \"getopts_${0}\" -- \"$@\"`\\n')\n s.write('eval set -- \"$ARGS\"\\n')\n s.write('while true; do\\n')\n s.write('case \"$1\" in\\n')\n for l,t in zip(self.labels, self.tags):\n s.write('--'+l+')\\n')\n s.write('if [ -n \"$2\" ]; then\\n')\n if l=='eta':\n tmp = \"$(echo ${2} | sed 's/\\.//');\"\n s.write('{}='.format(self.clean_tag(self.etaint_tag))+tmp+'\\n')\n s.write('echo \"'+l+'x10: {}\";\\n'.format(self.shellify_tag(self.etaint_tag)))\n s.write('{}=\"${{2}}\";\\n'.format(self.clean_tag(t)))\n s.write('echo \"'+l+': {}\";\\n'.format(self.shellify_tag(t)))\n s.write('fi\\n')\n s.write('shift 2;;\\n')\n s.write('--)\\n')\n s.write('shift\\n')\n s.write('break;;\\n')\n s.write('esac\\n')\n s.write('done\\n\\n')\n \n s.write('localdir=`pwd`\\n')\n s.write('echo \"Job local dir: ${localdir}\"\\n')\n s.write('{}=\"{}/{}\"\\n'.format(self.clean_tag(self.mac_var),self.outDir,self.mac_name))\n s.write('export HOME={}\\n'.format(os.environ['HOME']))\n s.write('cd {}/\\n'.format(os.getcwd()))\n s.write('source {}/g4env.sh\\n'.format(os.getcwd()))\n s.write('cd $localdir\\n')\n if len(self.p.datafileeos)>0:\n s.write('eos cp {} {}\\n'.format( os.path.join(self.p.datafileeos,self.p.datafile),self.p.datafile))\n\n cmd = ( 'PFCalEE \"{}\" --model {} --version {} --eta {} --shape {} --wcuseed {} --wcuresol {}'\n .format(self.shellify_tag(self.mac_var), self.p.model, self.p.version, self.shellify_tag(self.eta_tag), self.p.shape,self.p.wcuseed,self.p.wcuresol) )\n s.write('if [ \"${GRAN}\" -eq 0 ]; then\\n')\n s.write(cmd + ' --fineGranularity\\n')\n s.write('elif [ \"${GRAN}\" -eq -1 ]; then\\n')\n s.write(cmd + ' --ultraFineGranularity\\n')\n s.write('else\\n')\n s.write(cmd + '\\n')\n s.write('fi\\n')\n \n\n outTag = 'version{}_model{}_{}'.format(self.p.version, self.p.model, self.bfield)\n outTag += '_en{}_eta{}'.format(self.shellify_tag(self.en_tag),self.shellify_tag(self.etaint_tag)) \n if self.p.phi != 0.5: outTag += '_phi{n:.{r}f}pi'.format(n=self.p.phi,r=3)\n outTag += '_run{}'.format(self.shellify_tag(self.run_tag))\n logfile = os.path.join(self.outDir, 'g4_'+outTag+'.log')\n s.write('mv PFcal.root HGcal_{}.root\\n'.format(outTag))\n s.write('echo \"--Local directory is $localdir\" >> {}\\n'.format(logfile))\n s.write('echo home=$HOME >> {}\\n'.format(logfile))\n s.write('echo path=$PATH >> {}\\n'.format(logfile))\n s.write('echo ldlibpath=$LD_LIBRARY_PATH >> {}\\n'.format(logfile))\n s.write('ls -ltrh * >> {}\\n'.format(logfile))\n if len(self.p.eos)>0:\n s.write('eos mkdir -p {}\\n'.format(self.eosDirOut))\n s.write('eos cp HGcal_{}.root {}/HGcal_{}.root\\n'.format(outTag,self.eosDirOut,outTag))\n s.write('if (( \"$?\" != \"0\" )); then\\n')\n s.write('echo \" --- Problem with copy of file PFcal.root to EOS. Keeping locally.\" >> {}\\n'.format(logfile))\n s.write('else\\n')\n s.write('eossize=`eos ls -l {}/HGcal_{}.root | awk \\'{{print $5}}\\'`\\n'.format(self.eosDirOut,outTag))\n s.write('localsize=`ls -l HGcal_{}.root | awk \\'{{print $5}}\\'`\\n'.format(outTag))\n s.write('if [ \"${eossize}\" != \"${localsize}\" ]; then\\n')\n s.write('echo \" --- Copy of sim file to eos failed. Localsize = ${{localsize}}, eossize = ${{eossize}}. Keeping locally...\" >> {}\\n'.format(logfile))\n s.write('else\\n')\n s.write('echo \" --- Size check done: Localsize = ${{localsize}}, eossize = ${{eossize}}\" >> {}\\n'.format(logfile))\n s.write('echo \" --- File PFcal.root successfully copied to EOS: {}/HGcal_{}.root\" >> {}\\n'.format(self.eosDirOut,outTag,logfile))\n s.write('rm HGcal_{}.root\\n'.format(outTag))\n s.write('fi\\n')\n s.write('fi\\n')\n\n s.write('echo \"--deleting core files and hepmc files: too heavy!!\"\\n')\n s.write('rm core.*\\n')\n if len(self.p.datafileeos)>0:\n s.write('rm {}\\n'.format(self.p.datafile))\n s.write('cp * {}/\\n'.format(self.outDir))\n s.write('echo \"All done\"\\n')\n\n def write_geant4_files(self):\n \"\"\"\n Writes all required geant4 input files, one\n for each run (different seed) and energy.\n \"\"\"\n niters = self.p.nRuns*len(self.p.enList)*len(self.p.etas)\n gen_kwargs = dict(low=0, high=100000, size=niters)\n seeds1 = self.gen_uniform_int_random_seeds_(**gen_kwargs)\n seeds2 = self.gen_uniform_int_random_seeds_(**gen_kwargs)\n \n for run in range(self.p.nRuns):\n for iet,et in enumerate(self.p.enList):\n for ieta,eta in enumerate(self.p.etas):\n gen_idx = ( ( run * len(self.p.enList) * len(self.p.etas) ) +\n ( iet * len(self.p.etas) ) +\n ( ieta ) )\n assert(gen_idx < niters)\n \n t = ( ('prefix', 'g4steer'), ('en', et), ('eta', int(eta*10.)), ('run', run), ('ext', 'mac') )\n this_mac_name = self._unique_name(t)\n with open('{}/{}'.format(self.outDir, this_mac_name), 'w') as s:\n s.write('/control/verbose 0\\n')\n s.write('/control/saveHistory\\n')\n s.write('/run/verbose 0\\n')\n s.write('/event/verbose 0\\n')\n s.write('/tracking/verbose 0\\n')\n s.write('/N03/det/setField {n:.{r}f} T\\n'.format(n=self.p.Bfield,r=1))\n s.write('/N03/det/setModel {}\\n'.format(self.p.model))\n s.write('/random/setSeeds {} {}\\n'.format(seeds1[gen_idx], seeds2[gen_idx]) )\n if self.p.dogun :\n s.write('/generator/select particleGun\\n')\n s.write('/gun/particle {} \\n'.format(self.p.datatype))\n en = et*math.cosh(eta) if eta<5 else et\n s.write('/gun/energy {n:.{r}f} GeV\\n'.format(n=en, r=6))\n if self.p.model != 2 and eta<5:\n alpha = 2*math.atan(math.exp(-1.*eta));\n s.write('/gun/direction {} {} {}\\n'.format(math.cos(math.pi*self.p.phi)*math.sin(alpha),math.sin(math.pi*self.p.phi)*math.sin(alpha),math.cos(alpha)))\n \n else :\n s.write('/generator/select hepmcAscii\\n')\n s.write('/generator/hepmcAscii/open {}\\n'.format(self.p.datafile))\n s.write('/generator/hepmcAscii/verbose 0\\n')\n s.write('/run/beamOn {}\\n'.format(self.p.nevts))\n\n\n def write_condor_submission_file(self):\n \"\"\"\n Writes one single condor submission file, which is expanded to multiple\n jobs for different energies, etas and runs.\n \"\"\"\n with open('{}/{}'.format(self.outDir,self.condor_submit_name), 'w') as s:\n s.write('universe = vanilla\\n')\n s.write('Executable = {}/runJob.sh\\n'.format(self.outDir))\n s.write( ('Arguments = --energy {} --eta {} --run {} --granularity {}\\n'\n .format(self.en_tag, self.eta_tag, self.run_tag, self.gran_tag)) )\n #s.write('Requirements = (OpSysAndVer =?= \"CentOS7\")\\n')\n s.write('MY.WantOS = \"el7\"\\n')\n\n t = ( ('prefix', 'prod'), ('en', self.en_tag), ('eta', self.eta_tag),\n ('run', self.run_tag) )\n out_name = self._unique_name( t + (('ext', 'out'),) )\n err_name = self._unique_name( t + (('ext', 'err'),))\n log_name = self._unique_name( t + (('ext', 'log'),))\n s.write('Output = {}/{}\\n'.format(self.outDir,out_name))\n s.write('Error = {}/{}\\n'.format(self.outDir,err_name))\n s.write('Log = {}/{}\\n'.format(self.outDir,log_name))\n s.write('RequestMemory = 2GB\\n')\n s.write('+JobFlavour = \"testmatch\"\\n') \n s.write('JobBatchName = prod_' + self.p.gittag + '_' + str(self.p.version) + '_' + self.p.datatype + '\\n')\n s.write('Queue {nruns} {entag}, {etatag}, {gtag} from (\\n'.format( nruns=self.p.nRuns, entag=self.clean_tag(self.en_tag),\n etatag=self.clean_tag(self.eta_tag),\n gtag=self.clean_tag(self.gran_tag)))\n for et in self.p.enList:\n for eta in self.p.etas:\n gran = 1 if eta < 2.4 else 0\n if (opt.model==3): gran = -1\n s.write('{}, {}, {}\\n'.format(et,str(eta),gran))\n s.write(')')\n\n###################################################################################################\n###################################################################################################\n###################################################################################################\n\nbval = 'BON' if opt.Bfield>0 else 'BOFF'\nlab = '200u'\nodir = '{}/git{}/version_{}/model_{}/{}/{}/{}'.format(opt.out,opt.gittag,opt.version,opt.model,opt.datatype,bval,lab)\nif opt.phi != 0.5: odir='{out}/phi_{n:.{r}f}pi'.format(out=odir,n=opt.phi,r=3)\neos_partial = opt.eos[1:] if os.path.isabs(opt.eos) else opt.eos\nedir = os.path.join('/eos', 'cms', eos_partial, 'git' + opt.gittag, opt.datatype)\n\nsubprod = SubmitProd(outDir=odir, eosDirOut=edir, bfield=bval, params=opt)\nsubprod.write_shell_script_file()\nsubprod.write_geant4_files()\nsubprod.write_condor_submission_file()\n\nos.system('chmod u+rwx {}/runJob.sh'.format(odir))\nif opt.nosubmit:\n os.system('echo condor_submit {}/{}'.format(odir, subprod.condor_submit_name)) \nelse:\n os.system('condor_submit {}/{}'.format(odir, subprod.condor_submit_name))\n","sub_path":"PFCalEE/submitProd.py","file_name":"submitProd.py","file_ext":"py","file_size_in_byte":14891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"426469434","text":"import numpy as np\n\nclass BaseEnvironment1D():\n def __init__(self, size, num_nodes):\n self.size = size \n self.num_nodes = num_nodes\n self.node_spacing = (size[1] - size[0]) / (num_nodes-1) \n self.space_vec = np.linspace(size[0], size[1], num_nodes)\n\nclass BaseEnvironment2D():\n def __init__(self, size, num_nodes):\n self.size = size \n self.num_nodes = num_nodes\n self.node_spacing = (size[:, 1] - size[:, 0]) / (num_nodes - 1)\n lin_x = np.linspspace(size[0, 0], size[0, 1], num_nodes[0])\n lin_y = np.linspspace(size[1, 0], size[1, 1], num_nodes[1])\n space_x, space_y = np.meshgrid(lin_x, lin_y)\n self.space_vec = np.array([space_x.flatten(), space_y.flatten()]).T\n\nclass BaseWave1D():\n def __init__(self, pos_init, mom_init, environment):\n self.psi = np.zeros(environment.num_nodes, dtype=np.cfloat)\n self.pos_init = pos_init\n self.mom_init = mom_init\n self.environment = environment\n\n\n","sub_path":"quantum_dynamics/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"109518212","text":"import os\nimport subprocess\n\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\n\ndef extract_warc_files():\n for file in os.listdir('.'):\n if not file.endswith('warc.gz'):\n continue\n\n output_dir = file.replace('.warc.gz', '')\n \n if not os.path.isdir(output_dir):\n os.mkdir(output_dir)\n\n filepath = os.path.dirname( os.path.abspath(__file__))\n\n filepath = os.path.join(filepath, file)\n\n command = [\n 'python3',\n '-m' 'warcat',\n 'extract',\n '{file}'.format(file=filepath),\n '--output-dir',\n '{output_dir}'.format(output_dir=output_dir),\n '--progress'\n ]\n\n extract_warc = subprocess.Popen(command)\n extract_warc.wait()\n\n\nif __name__ == '__main__':\n extract_warc_files()\n","sub_path":"extra_docs/warc2files/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"25012313","text":"\"\"\"The Channel class provides a wrapper for interacting with RabbitMQ\nimplementing the methods and behaviors for an AMQP Channel.\n\n\"\"\"\nimport collections\nimport logging\nimport warnings\nimport uuid\n\nfrom . import frame as frame\nfrom . import exceptions\nfrom . import spec as spec\nfrom .utils import is_callable\nfrom .compat import unicode_type, dictkeys, as_bytes\n\n\nLOGGER = logging.getLogger(__name__)\nMAX_CHANNELS = 32768\n\n\nclass Channel(object):\n \"\"\"A Channel is the primary communication method for interacting with\n RabbitMQ. It is recommended that you do not directly invoke\n the creation of a channel object in your application code but rather\n construct the a channel by calling the active connection's channel()\n method.\n\n \"\"\"\n CLOSED = 0\n OPENING = 1\n OPEN = 2\n CLOSING = 3\n\n _ON_CHANNEL_CLEANUP_CB_KEY = '_on_channel_cleanup'\n\n def __init__(self, connection, channel_number, on_open_callback=None):\n \"\"\"Create a new instance of the Channel\n\n :param pika.connection.Connection connection: The connection\n :param int channel_number: The channel number for this instance\n :param method on_open_callback: The method to call on channel open\n\n \"\"\"\n if not isinstance(channel_number, int):\n raise exceptions.InvalidChannelNumber\n self.channel_number = channel_number\n self.callbacks = connection.callbacks\n self.connection = connection\n\n # The frame-handler changes depending on the type of frame processed\n self.frame_dispatcher = ContentFrameDispatcher()\n\n self._blocked = collections.deque(list())\n self._blocking = None\n self._has_on_flow_callback = False\n self._cancelled = set()\n self._consumers = dict()\n self._consumers_with_noack = set()\n self._on_flowok_callback = None\n self._on_getok_callback = None\n self._on_openok_callback = on_open_callback\n self._pending = dict()\n self._state = self.CLOSED\n\n # opaque cookie value set by wrapper layer (e.g., BlockingConnection)\n # via _set_cookie\n self._cookie = None\n\n def __int__(self):\n \"\"\"Return the channel object as its channel number\n\n :rtype: int\n\n \"\"\"\n return self.channel_number\n\n def add_callback(self, callback, replies, one_shot=True):\n \"\"\"Pass in a callback handler and a list replies from the\n RabbitMQ broker which you'd like the callback notified of. Callbacks\n should allow for the frame parameter to be passed in.\n\n :param method callback: The method to call\n :param list replies: The replies to get a callback for\n :param bool one_shot: Only handle the first type callback\n\n \"\"\"\n for reply in replies:\n self.callbacks.add(self.channel_number, reply, callback, one_shot)\n\n def add_on_cancel_callback(self, callback):\n \"\"\"Pass a callback function that will be called when the basic_cancel\n is sent by the server. The callback function should receive a frame\n parameter.\n\n :param method callback: The method to call on callback\n\n \"\"\"\n self.callbacks.add(self.channel_number, spec.Basic.Cancel, callback,\n False)\n\n def add_on_close_callback(self, callback):\n \"\"\"Pass a callback function that will be called when the channel is\n closed. The callback function will receive the channel, the\n reply_code (int) and the reply_text (int) sent by the server describing\n why the channel was closed.\n\n :param method callback: The method to call on callback\n\n \"\"\"\n self.callbacks.add(self.channel_number, '_on_channel_close', callback,\n False, self)\n\n def add_on_flow_callback(self, callback):\n \"\"\"Pass a callback function that will be called when Channel.Flow is\n called by the remote server. Note that newer versions of RabbitMQ\n will not issue this but instead use TCP backpressure\n\n :param method callback: The method to call on callback\n\n \"\"\"\n self._has_on_flow_callback = True\n self.callbacks.add(self.channel_number, spec.Channel.Flow, callback,\n False)\n\n def add_on_return_callback(self, callback):\n \"\"\"Pass a callback function that will be called when basic_publish as\n sent a message that has been rejected and returned by the server.\n\n :param method callback: The method to call on callback with the\n signature callback(channel, method, properties,\n body), where\n channel: pika.Channel\n method: pika.spec.Basic.Return\n properties: pika.spec.BasicProperties\n body: str, unicode, or bytes (python 3.x)\n\n \"\"\"\n self.callbacks.add(self.channel_number, '_on_return', callback, False)\n\n def basic_ack(self, delivery_tag=0, multiple=False):\n \"\"\"Acknowledge one or more messages. When sent by the client, this\n method acknowledges one or more messages delivered via the Deliver or\n Get-Ok methods. When sent by server, this method acknowledges one or\n more messages published with the Publish method on a channel in\n confirm mode. The acknowledgement can be for a single message or a\n set of messages up to and including a specific message.\n\n :param int delivery-tag: The server-assigned delivery tag\n :param bool multiple: If set to True, the delivery tag is treated as\n \"up to and including\", so that multiple messages\n can be acknowledged with a single method. If set\n to False, the delivery tag refers to a single\n message. If the multiple field is 1, and the\n delivery tag is zero, this indicates\n acknowledgement of all outstanding messages.\n \"\"\"\n if not self.is_open:\n raise exceptions.ChannelClosed()\n return self._send_method(spec.Basic.Ack(delivery_tag, multiple))\n\n def basic_cancel(self, callback=None, consumer_tag='', nowait=False):\n \"\"\"This method cancels a consumer. This does not affect already\n delivered messages, but it does mean the server will not send any more\n messages for that consumer. The client may receive an arbitrary number\n of messages in between sending the cancel method and receiving the\n cancel-ok reply. It may also be sent from the server to the client in\n the event of the consumer being unexpectedly cancelled (i.e. cancelled\n for any reason other than the server receiving the corresponding\n basic.cancel from the client). This allows clients to be notified of\n the loss of consumers due to events such as queue deletion.\n\n :param method callback: Method to call for a Basic.CancelOk response\n :param str consumer_tag: Identifier for the consumer\n :param bool nowait: Do not expect a Basic.CancelOk response\n :raises: ValueError\n\n \"\"\"\n self._validate_channel_and_callback(callback)\n if consumer_tag not in self.consumer_tags:\n return\n if callback:\n if nowait is True:\n raise ValueError('Can not pass a callback if nowait is True')\n self.callbacks.add(self.channel_number, spec.Basic.CancelOk,\n callback)\n self._cancelled.add(consumer_tag)\n self._rpc(spec.Basic.Cancel(consumer_tag=consumer_tag,\n nowait=nowait), self._on_cancelok,\n [(spec.Basic.CancelOk, {'consumer_tag': consumer_tag})] if\n nowait is False else [])\n\n def basic_consume(self, consumer_callback,\n queue='',\n no_ack=False,\n exclusive=False,\n consumer_tag=None,\n arguments=None):\n \"\"\"Sends the AMQP command Basic.Consume to the broker and binds messages\n for the consumer_tag to the consumer callback. If you do not pass in\n a consumer_tag, one will be automatically generated for you. Returns\n the consumer tag.\n\n For more information on basic_consume, see:\n http://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.consume\n\n :param method consumer_callback: The method to callback when consuming\n with the signature consumer_callback(channel, method, properties,\n body), where\n channel: pika.Channel\n method: pika.spec.Basic.Deliver\n properties: pika.spec.BasicProperties\n body: str, unicode, or bytes (python 3.x)\n\n :param queue: The queue to consume from\n :type queue: str or unicode\n :param bool no_ack: Tell the broker to not expect a response\n :param bool exclusive: Don't allow other consumers on the queue\n :param consumer_tag: Specify your own consumer tag\n :type consumer_tag: str or unicode\n :param dict arguments: Custom key/value pair arguments for the consume\n :rtype: str\n\n \"\"\"\n self._validate_channel_and_callback(consumer_callback)\n\n # If a consumer tag was not passed, create one\n if not consumer_tag:\n consumer_tag = self._generate_consumer_tag()\n\n if consumer_tag in self._consumers or consumer_tag in self._cancelled:\n raise exceptions.DuplicateConsumerTag(consumer_tag)\n\n if no_ack:\n self._consumers_with_noack.add(consumer_tag)\n\n self._consumers[consumer_tag] = consumer_callback\n self._pending[consumer_tag] = list()\n self._rpc(spec.Basic.Consume(queue=queue,\n consumer_tag=consumer_tag,\n no_ack=no_ack,\n exclusive=exclusive,\n arguments=arguments or dict()),\n self._on_eventok, [(spec.Basic.ConsumeOk,\n {'consumer_tag': consumer_tag})])\n\n return consumer_tag\n\n def _generate_consumer_tag(self):\n \"\"\"Generate a consumer tag\n\n NOTE: this protected method may be called by derived classes\n\n :returns: consumer tag\n :rtype: str\n \"\"\"\n return 'ctag%i.%s' % (self.channel_number,\n uuid.uuid4().hex)\n\n def basic_get(self, callback=None, queue='', no_ack=False):\n \"\"\"Get a single message from the AMQP broker. If you want to\n be notified of Basic.GetEmpty, use the Channel.add_callback method\n adding your Basic.GetEmpty callback which should expect only one\n parameter, frame. For more information on basic_get and its\n parameters, see:\n\n http://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.get\n\n :param method callback: The method to callback with a message that has\n the signature callback(channel, method, properties, body), where:\n channel: pika.Channel\n method: pika.spec.Basic.GetOk\n properties: pika.spec.BasicProperties\n body: str, unicode, or bytes (python 3.x)\n :param queue: The queue to get a message from\n :type queue: str or unicode\n :param bool no_ack: Tell the broker to not expect a reply\n\n \"\"\"\n self._validate_channel_and_callback(callback)\n self._on_getok_callback = callback\n self._send_method(spec.Basic.Get(queue=queue, no_ack=no_ack))\n\n def basic_nack(self, delivery_tag=None, multiple=False, requeue=True):\n \"\"\"This method allows a client to reject one or more incoming messages.\n It can be used to interrupt and cancel large incoming messages, or\n return untreatable messages to their original queue.\n\n :param int delivery-tag: The server-assigned delivery tag\n :param bool multiple: If set to True, the delivery tag is treated as\n \"up to and including\", so that multiple messages\n can be acknowledged with a single method. If set\n to False, the delivery tag refers to a single\n message. If the multiple field is 1, and the\n delivery tag is zero, this indicates\n acknowledgement of all outstanding messages.\n :param bool requeue: If requeue is true, the server will attempt to\n requeue the message. If requeue is false or the\n requeue attempt fails the messages are discarded or\n dead-lettered.\n\n \"\"\"\n if not self.is_open:\n raise exceptions.ChannelClosed()\n return self._send_method(spec.Basic.Nack(delivery_tag, multiple,\n requeue))\n\n def basic_publish(self, exchange, routing_key, body,\n properties=None,\n mandatory=False,\n immediate=False):\n \"\"\"Publish to the channel with the given exchange, routing key and body.\n For more information on basic_publish and what the parameters do, see:\n\n http://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.publish\n\n :param exchange: The exchange to publish to\n :type exchange: str or unicode\n :param routing_key: The routing key to bind on\n :type routing_key: str or unicode\n :param body: The message body\n :type body: str or unicode\n :param pika.spec.BasicProperties properties: Basic.properties\n :param bool mandatory: The mandatory flag\n :param bool immediate: The immediate flag\n\n \"\"\"\n if not self.is_open:\n raise exceptions.ChannelClosed()\n if immediate:\n LOGGER.warning('The immediate flag is deprecated in RabbitMQ')\n if isinstance(body, unicode_type):\n body = body.encode('utf-8')\n properties = properties or spec.BasicProperties()\n self._send_method(spec.Basic.Publish(exchange=exchange,\n routing_key=routing_key,\n mandatory=mandatory,\n immediate=immediate),\n (properties, body))\n\n def basic_qos(self,\n callback=None,\n prefetch_size=0,\n prefetch_count=0,\n all_channels=False):\n \"\"\"Specify quality of service. This method requests a specific quality\n of service. The QoS can be specified for the current channel or for all\n channels on the connection. The client can request that messages be sent\n in advance so that when the client finishes processing a message, the\n following message is already held locally, rather than needing to be\n sent down the channel. Prefetching gives a performance improvement.\n\n :param method callback: The method to callback for Basic.QosOk response\n :param int prefetch_size: This field specifies the prefetch window\n size. The server will send a message in\n advance if it is equal to or smaller in size\n than the available prefetch size (and also\n falls into other prefetch limits). May be set\n to zero, meaning \"no specific limit\",\n although other prefetch limits may still\n apply. The prefetch-size is ignored if the\n no-ack option is set.\n :param int prefetch_count: Specifies a prefetch window in terms of whole\n messages. This field may be used in\n combination with the prefetch-size field; a\n message will only be sent in advance if both\n prefetch windows (and those at the channel\n and connection level) allow it. The\n prefetch-count is ignored if the no-ack\n option is set.\n :param bool all_channels: Should the QoS apply to all channels\n\n \"\"\"\n self._validate_channel_and_callback(callback)\n return self._rpc(spec.Basic.Qos(prefetch_size, prefetch_count,\n all_channels), callback,\n [spec.Basic.QosOk])\n\n def basic_reject(self, delivery_tag, requeue=True):\n \"\"\"Reject an incoming message. This method allows a client to reject a\n message. It can be used to interrupt and cancel large incoming messages,\n or return untreatable messages to their original queue.\n\n :param int delivery-tag: The server-assigned delivery tag\n :param bool requeue: If requeue is true, the server will attempt to\n requeue the message. If requeue is false or the\n requeue attempt fails the messages are discarded or\n dead-lettered.\n :raises: TypeError\n\n \"\"\"\n if not self.is_open:\n raise exceptions.ChannelClosed()\n if not isinstance(delivery_tag, int):\n raise TypeError('delivery_tag must be an integer')\n return self._send_method(spec.Basic.Reject(delivery_tag, requeue))\n\n def basic_recover(self, callback=None, requeue=False):\n \"\"\"This method asks the server to redeliver all unacknowledged messages\n on a specified channel. Zero or more messages may be redelivered. This\n method replaces the asynchronous Recover.\n\n :param method callback: Method to call when receiving Basic.RecoverOk\n :param bool requeue: If False, the message will be redelivered to the\n original recipient. If True, the server will\n attempt to requeue the message, potentially then\n delivering it to an alternative subscriber.\n\n \"\"\"\n self._validate_channel_and_callback(callback)\n return self._rpc(spec.Basic.Recover(requeue), callback,\n [spec.Basic.RecoverOk])\n\n def close(self, reply_code=0, reply_text=\"Normal Shutdown\"):\n \"\"\"Will invoke a clean shutdown of the channel with the AMQP Broker.\n\n :param int reply_code: The reply code to close the channel with\n :param str reply_text: The reply text to close the channel with\n\n \"\"\"\n if not self.is_open:\n raise exceptions.ChannelClosed()\n LOGGER.info('Channel.close(%s, %s)', reply_code, reply_text)\n if self._consumers:\n LOGGER.debug('Cancelling %i consumers', len(self._consumers))\n for consumer_tag in dictkeys(self._consumers):\n self.basic_cancel(consumer_tag=consumer_tag)\n self._set_state(self.CLOSING)\n self._rpc(spec.Channel.Close(reply_code, reply_text, 0, 0),\n self._on_closeok, [spec.Channel.CloseOk])\n\n def confirm_delivery(self, callback=None, nowait=False):\n \"\"\"Turn on Confirm mode in the channel. Pass in a callback to be\n notified by the Broker when a message has been confirmed as received or\n rejected (Basic.Ack, Basic.Nack) from the broker to the publisher.\n\n For more information see:\n http://www.rabbitmq.com/extensions.html#confirms\n\n :param method callback: The callback for delivery confirmations\n :param bool nowait: Do not send a reply frame (Confirm.SelectOk)\n\n \"\"\"\n self._validate_channel_and_callback(callback)\n if (self.connection.publisher_confirms is False or\n self.connection.basic_nack is False):\n raise exceptions.MethodNotImplemented('Not Supported on Server')\n\n # Add the ack and nack callbacks\n if callback is not None:\n self.callbacks.add(self.channel_number, spec.Basic.Ack, callback,\n False)\n self.callbacks.add(self.channel_number, spec.Basic.Nack, callback,\n False)\n\n # Send the RPC command\n self._rpc(spec.Confirm.Select(nowait), self._on_selectok,\n [spec.Confirm.SelectOk] if nowait is False else [])\n\n @property\n def consumer_tags(self):\n \"\"\"Property method that returns a list of currently active consumers\n\n :rtype: list\n\n \"\"\"\n return dictkeys(self._consumers)\n\n def exchange_bind(self,\n callback=None,\n destination=None,\n source=None,\n routing_key='',\n nowait=False,\n arguments=None):\n \"\"\"Bind an exchange to another exchange.\n\n :param method callback: The method to call on Exchange.BindOk\n :param destination: The destination exchange to bind\n :type destination: str or unicode\n :param source: The source exchange to bind to\n :type source: str or unicode\n :param routing_key: The routing key to bind on\n :type routing_key: str or unicode\n :param bool nowait: Do not wait for an Exchange.BindOk\n :param dict arguments: Custom key/value pair arguments for the binding\n\n \"\"\"\n self._validate_channel_and_callback(callback)\n return self._rpc(spec.Exchange.Bind(0, destination, source, routing_key,\n nowait, arguments or dict()),\n callback, [spec.Exchange.BindOk] if nowait is False\n else [])\n\n def exchange_declare(self,\n callback=None,\n exchange=None,\n exchange_type='direct',\n passive=False,\n durable=False,\n auto_delete=False,\n internal=False,\n nowait=False,\n arguments=None,\n type=None):\n \"\"\"This method creates an exchange if it does not already exist, and if\n the exchange exists, verifies that it is of the correct and expected\n class.\n\n If passive set, the server will reply with Declare-Ok if the exchange\n already exists with the same name, and raise an error if not and if the\n exchange does not already exist, the server MUST raise a channel\n exception with reply code 404 (not found).\n\n :param method callback: Call this method on Exchange.DeclareOk\n :param exchange: The exchange name consists of a non-empty\n :type exchange: str or unicode\n sequence of these characters: letters,\n digits, hyphen, underscore, period, or\n colon.\n :param str exchange_type: The exchange type to use\n :param bool passive: Perform a declare or just check to see if it exists\n :param bool durable: Survive a reboot of RabbitMQ\n :param bool auto_delete: Remove when no more queues are bound to it\n :param bool internal: Can only be published to by other exchanges\n :param bool nowait: Do not expect an Exchange.DeclareOk response\n :param dict arguments: Custom key/value pair arguments for the exchange\n :param str type: The deprecated exchange type parameter\n\n \"\"\"\n self._validate_channel_and_callback(callback)\n if type is not None:\n warnings.warn('type is deprecated, use exchange_type instead',\n DeprecationWarning)\n if exchange_type == 'direct' and type != exchange_type:\n exchange_type = type\n return self._rpc(spec.Exchange.Declare(0, exchange, exchange_type,\n passive, durable, auto_delete,\n internal, nowait,\n arguments or dict()), callback,\n [spec.Exchange.DeclareOk] if nowait is False else [])\n\n def exchange_delete(self,\n callback=None,\n exchange=None,\n if_unused=False,\n nowait=False):\n \"\"\"Delete the exchange.\n\n :param method callback: The method to call on Exchange.DeleteOk\n :param exchange: The exchange name\n :type exchange: str or unicode\n :param bool if_unused: only delete if the exchange is unused\n :param bool nowait: Do not wait for an Exchange.DeleteOk\n\n \"\"\"\n self._validate_channel_and_callback(callback)\n return self._rpc(spec.Exchange.Delete(0, exchange, if_unused, nowait),\n callback, [spec.Exchange.DeleteOk] if nowait is False\n else [])\n\n def exchange_unbind(self,\n callback=None,\n destination=None,\n source=None,\n routing_key='',\n nowait=False,\n arguments=None):\n \"\"\"Unbind an exchange from another exchange.\n\n :param method callback: The method to call on Exchange.UnbindOk\n :param destination: The destination exchange to unbind\n :type destination: str or unicode\n :param source: The source exchange to unbind from\n :type source: str or unicode\n :param routing_key: The routing key to unbind\n :type routing_key: str or unicode\n :param bool nowait: Do not wait for an Exchange.UnbindOk\n :param dict arguments: Custom key/value pair arguments for the binding\n\n \"\"\"\n self._validate_channel_and_callback(callback)\n return self._rpc(spec.Exchange.Unbind(0, destination, source,\n routing_key, nowait, arguments),\n callback, [spec.Exchange.UnbindOk] if nowait is False\n else [])\n\n def flow(self, callback, active):\n \"\"\"Turn Channel flow control off and on. Pass a callback to be notified\n of the response from the server. active is a bool. Callback should\n expect a bool in response indicating channel flow state. For more\n information, please reference:\n\n http://www.rabbitmq.com/amqp-0-9-1-reference.html#channel.flow\n\n :param method callback: The callback method\n :param bool active: Turn flow on or off\n\n \"\"\"\n self._validate_channel_and_callback(callback)\n self._on_flowok_callback = callback\n self._rpc(spec.Channel.Flow(active), self._on_flowok,\n [spec.Channel.FlowOk])\n\n @property\n def is_closed(self):\n \"\"\"Returns True if the channel is closed.\n\n :rtype: bool\n\n \"\"\"\n return self._state == self.CLOSED\n\n @property\n def is_closing(self):\n \"\"\"Returns True if the channel is closing.\n\n :rtype: bool\n\n \"\"\"\n return self._state == self.CLOSING\n\n @property\n def is_open(self):\n \"\"\"Returns True if the channel is open.\n\n :rtype: bool\n\n \"\"\"\n return self._state == self.OPEN\n\n def open(self):\n \"\"\"Open the channel\"\"\"\n self._set_state(self.OPENING)\n self._add_callbacks()\n self._rpc(spec.Channel.Open(), self._on_openok, [spec.Channel.OpenOk])\n\n def queue_bind(self, callback, queue, exchange,\n routing_key=None,\n nowait=False,\n arguments=None):\n \"\"\"Bind the queue to the specified exchange\n\n :param method callback: The method to call on Queue.BindOk\n :param queue: The queue to bind to the exchange\n :type queue: str or unicode\n :param exchange: The source exchange to bind to\n :type exchange: str or unicode\n :param routing_key: The routing key to bind on\n :type routing_key: str or unicode\n :param bool nowait: Do not wait for a Queue.BindOk\n :param dict arguments: Custom key/value pair arguments for the binding\n\n \"\"\"\n self._validate_channel_and_callback(callback)\n replies = [spec.Queue.BindOk] if nowait is False else []\n if routing_key is None:\n routing_key = queue\n return self._rpc(spec.Queue.Bind(0, queue, exchange, routing_key,\n nowait, arguments or dict()), callback,\n replies)\n\n def queue_declare(self, callback,\n queue='',\n passive=False,\n durable=False,\n exclusive=False,\n auto_delete=False,\n nowait=False,\n arguments=None):\n \"\"\"Declare queue, create if needed. This method creates or checks a\n queue. When creating a new queue the client can specify various\n properties that control the durability of the queue and its contents,\n and the level of sharing for the queue.\n\n Leave the queue name empty for a auto-named queue in RabbitMQ\n\n :param method callback: The method to call on Queue.DeclareOk\n :param queue: The queue name\n :type queue: str or unicode\n :param bool passive: Only check to see if the queue exists\n :param bool durable: Survive reboots of the broker\n :param bool exclusive: Only allow access by the current connection\n :param bool auto_delete: Delete after consumer cancels or disconnects\n :param bool nowait: Do not wait for a Queue.DeclareOk\n :param dict arguments: Custom key/value arguments for the queue\n\n \"\"\"\n if queue:\n condition = (spec.Queue.DeclareOk,\n {'queue': queue})\n else:\n condition = spec.Queue.DeclareOk\n replies = [condition] if nowait is False else []\n self._validate_channel_and_callback(callback)\n return self._rpc(spec.Queue.Declare(0, queue, passive, durable,\n exclusive, auto_delete, nowait,\n arguments or dict()), callback,\n replies)\n\n def queue_delete(self,\n callback=None,\n queue='',\n if_unused=False,\n if_empty=False,\n nowait=False):\n \"\"\"Delete a queue from the broker.\n\n :param method callback: The method to call on Queue.DeleteOk\n :param queue: The queue to delete\n :type queue: str or unicode\n :param bool if_unused: only delete if it's unused\n :param bool if_empty: only delete if the queue is empty\n :param bool nowait: Do not wait for a Queue.DeleteOk\n\n \"\"\"\n replies = [spec.Queue.DeleteOk] if nowait is False else []\n self._validate_channel_and_callback(callback)\n return self._rpc(spec.Queue.Delete(0, queue, if_unused, if_empty,\n nowait), callback, replies)\n\n def queue_purge(self, callback=None, queue='', nowait=False):\n \"\"\"Purge all of the messages from the specified queue\n\n :param method callback: The method to call on Queue.PurgeOk\n :param queue: The queue to purge\n :type queue: str or unicode\n :param bool nowait: Do not expect a Queue.PurgeOk response\n\n \"\"\"\n replies = [spec.Queue.PurgeOk] if nowait is False else []\n self._validate_channel_and_callback(callback)\n return self._rpc(spec.Queue.Purge(0, queue, nowait), callback, replies)\n\n def queue_unbind(self,\n callback=None,\n queue='',\n exchange=None,\n routing_key=None,\n arguments=None):\n \"\"\"Unbind a queue from an exchange.\n\n :param method callback: The method to call on Queue.UnbindOk\n :param queue: The queue to unbind from the exchange\n :type queue: str or unicode\n :param exchange: The source exchange to bind from\n :type exchange: str or unicode\n :param routing_key: The routing key to unbind\n :type routing_key: str or unicode\n :param dict arguments: Custom key/value pair arguments for the binding\n\n \"\"\"\n self._validate_channel_and_callback(callback)\n if routing_key is None:\n routing_key = queue\n return self._rpc(spec.Queue.Unbind(0, queue, exchange, routing_key,\n arguments or dict()), callback,\n [spec.Queue.UnbindOk])\n\n def tx_commit(self, callback=None):\n \"\"\"Commit a transaction\n\n :param method callback: The callback for delivery confirmations\n\n \"\"\"\n self._validate_channel_and_callback(callback)\n return self._rpc(spec.Tx.Commit(), callback, [spec.Tx.CommitOk])\n\n def tx_rollback(self, callback=None):\n \"\"\"Rollback a transaction.\n\n :param method callback: The callback for delivery confirmations\n\n \"\"\"\n self._validate_channel_and_callback(callback)\n return self._rpc(spec.Tx.Rollback(), callback, [spec.Tx.RollbackOk])\n\n def tx_select(self, callback=None):\n \"\"\"Select standard transaction mode. This method sets the channel to use\n standard transactions. The client must use this method at least once on\n a channel before using the Commit or Rollback methods.\n\n :param method callback: The callback for delivery confirmations\n\n \"\"\"\n self._validate_channel_and_callback(callback)\n return self._rpc(spec.Tx.Select(), callback, [spec.Tx.SelectOk])\n\n # Internal methods\n\n def _add_callbacks(self):\n \"\"\"Callbacks that add the required behavior for a channel when\n connecting and connected to a server.\n\n \"\"\"\n # Add a callback for Basic.GetEmpty\n self.callbacks.add(self.channel_number, spec.Basic.GetEmpty,\n self._on_getempty, False)\n\n # Add a callback for Basic.Cancel\n self.callbacks.add(self.channel_number, spec.Basic.Cancel,\n self._on_cancel, False)\n\n # Deprecated in newer versions of RabbitMQ but still register for it\n self.callbacks.add(self.channel_number, spec.Channel.Flow,\n self._on_flow, False)\n\n # Add a callback for when the server closes our channel\n self.callbacks.add(self.channel_number, spec.Channel.Close,\n self._on_close, True)\n\n def _add_on_cleanup_callback(self, callback):\n \"\"\"For internal use only (e.g., Connection needs to remove closed\n channels from its channel container). Pass a callback function that will\n be called when the channel is being cleaned up after all channel-close\n callbacks callbacks.\n\n :param method callback: The method to call on callback with the\n signature: callback(channel)\n\n \"\"\"\n self.callbacks.add(self.channel_number, self._ON_CHANNEL_CLEANUP_CB_KEY,\n callback, one_shot=True, only_caller=self)\n\n def _add_pending_msg(self, consumer_tag, method_frame, header_frame, body):\n \"\"\"Add the received message to the pending message stack.\n\n :param str consumer_tag: The consumer tag for the message\n :param pika.frame.Method method_frame: The received method frame\n :param pika.frame.Header header_frame: The received header frame\n :param body: The message body\n :type body: str or unicode\n\n \"\"\"\n self._pending[consumer_tag].append((self, method_frame.method,\n header_frame.properties, body))\n\n def _cleanup(self):\n \"\"\"Remove all consumers and any callbacks for the channel.\"\"\"\n self.callbacks.process(self.channel_number,\n self._ON_CHANNEL_CLEANUP_CB_KEY, self,\n self)\n self._consumers = dict()\n self.callbacks.cleanup(str(self.channel_number))\n self._cookie = None\n\n def _cleanup_consumer_ref(self, consumer_tag):\n \"\"\"Remove any references to the consumer tag in internal structures\n for consumer state.\n\n :param str consumer_tag: The consumer tag to cleanup\n\n \"\"\"\n if consumer_tag in self._consumers_with_noack:\n self._consumers_with_noack.remove(consumer_tag)\n if consumer_tag in self._consumers:\n del self._consumers[consumer_tag]\n if consumer_tag in self._pending:\n del self._pending[consumer_tag]\n self._cancelled.discard(consumer_tag)\n\n def _get_cookie(self):\n \"\"\"Used by the wrapper implementation (e.g., `BlockingChannel`) to\n retrieve the cookie that it set via `_set_cookie`\n\n :returns: opaque cookie value that was set via `_set_cookie`\n \"\"\"\n return self._cookie\n\n def _get_pending_msg(self, consumer_tag):\n \"\"\"Get a pending message for the consumer tag from the stack.\n\n :param str consumer_tag: The consumer tag to get a message from\n :rtype: tuple(pika.frame.Header, pika.frame.Method, str|unicode)\n\n \"\"\"\n return self._pending[consumer_tag].pop(0)\n\n def _handle_content_frame(self, frame_value):\n \"\"\"This is invoked by the connection when frames that are not registered\n with the CallbackManager have been found. This should only be the case\n when the frames are related to content delivery.\n\n The frame_dispatcher will be invoked which will return the fully formed\n message in three parts when all of the body frames have been received.\n\n :param pika.amqp_object.Frame frame_value: The frame to deliver\n\n \"\"\"\n try:\n response = self.frame_dispatcher.process(frame_value)\n except exceptions.UnexpectedFrameError:\n return self._unexpected_frame(frame_value)\n\n if response:\n if isinstance(response[0].method, spec.Basic.Deliver):\n self._on_deliver(*response)\n elif isinstance(response[0].method, spec.Basic.GetOk):\n self._on_getok(*response)\n elif isinstance(response[0].method, spec.Basic.Return):\n self._on_return(*response)\n\n def _has_content(self, method_frame):\n \"\"\"Return a bool if it's a content method as defined by the spec\n\n :param pika.amqp_object.Method method_frame: The method frame received\n\n \"\"\"\n return spec.has_content(method_frame.INDEX)\n\n def _on_cancel(self, method_frame):\n \"\"\"When the broker cancels a consumer, delete it from our internal\n dictionary.\n\n :param pika.frame.Method method_frame: The method frame received\n\n \"\"\"\n if method_frame.method.consumer_tag in self._cancelled:\n # User-initiated cancel is waiting for Cancel-ok\n return\n\n self._cleanup_consumer_ref(method_frame.method.consumer_tag)\n\n def _on_cancelok(self, method_frame):\n \"\"\"Called in response to a frame from the Broker when the\n client sends Basic.Cancel\n\n :param pika.frame.Method method_frame: The method frame received\n\n \"\"\"\n self._cleanup_consumer_ref(method_frame.method.consumer_tag)\n\n def _on_close(self, method_frame):\n \"\"\"Handle the case where our channel has been closed for us\n\n :param pika.frame.Method method_frame: The close frame\n\n \"\"\"\n LOGGER.info('%s', method_frame)\n LOGGER.warning('Received remote Channel.Close (%s): %s',\n method_frame.method.reply_code,\n method_frame.method.reply_text)\n if self.connection.is_open:\n self._send_method(spec.Channel.CloseOk())\n self._set_state(self.CLOSED)\n self.callbacks.process(self.channel_number, '_on_channel_close', self,\n self, method_frame.method.reply_code,\n method_frame.method.reply_text)\n self._cleanup()\n\n def _on_closeok(self, method_frame):\n \"\"\"Invoked when RabbitMQ replies to a Channel.Close method\n\n :param pika.frame.Method method_frame: The CloseOk frame\n\n \"\"\"\n self._set_state(self.CLOSED)\n self.callbacks.process(self.channel_number, '_on_channel_close', self,\n self, 0, '')\n self._cleanup()\n\n def _on_deliver(self, method_frame, header_frame, body):\n \"\"\"Cope with reentrancy. If a particular consumer is still active when\n another delivery appears for it, queue the deliveries up until it\n finally exits.\n\n :param pika.frame.Method method_frame: The method frame received\n :param pika.frame.Header header_frame: The header frame received\n :param body: The body received\n :type body: str or unicode\n\n \"\"\"\n consumer_tag = method_frame.method.consumer_tag\n if consumer_tag in self._cancelled:\n if self.is_open and consumer_tag not in self._consumers_with_noack:\n self.basic_reject(method_frame.method.delivery_tag)\n return\n if consumer_tag not in self._consumers:\n return self._add_pending_msg(consumer_tag, method_frame,\n header_frame, body)\n while self._pending[consumer_tag]:\n self._consumers[consumer_tag](*self._get_pending_msg(consumer_tag))\n self._consumers[consumer_tag](self, method_frame.method,\n header_frame.properties, body)\n\n def _on_eventok(self, method_frame):\n \"\"\"Generic events that returned ok that may have internal callbacks.\n We keep a list of what we've yet to implement so that we don't silently\n drain events that we don't support.\n\n :param pika.frame.Method method_frame: The method frame received\n\n \"\"\"\n LOGGER.debug('Discarding frame %r', method_frame)\n\n def _on_flow(self, method_frame_unused):\n \"\"\"Called if the server sends a Channel.Flow frame.\n\n :param pika.frame.Method method_frame_unused: The Channel.Flow frame\n\n \"\"\"\n if self._has_on_flow_callback is False:\n LOGGER.warning('Channel.Flow received from server')\n\n def _on_flowok(self, method_frame):\n \"\"\"Called in response to us asking the server to toggle on Channel.Flow\n\n :param pika.frame.Method method_frame: The method frame received\n\n \"\"\"\n self.flow_active = method_frame.method.active\n if self._on_flowok_callback:\n self._on_flowok_callback(method_frame.method.active)\n self._on_flowok_callback = None\n else:\n LOGGER.warning('Channel.FlowOk received with no active callbacks')\n\n def _on_getempty(self, method_frame):\n \"\"\"When we receive an empty reply do nothing but log it\n\n :param pika.frame.Method method_frame: The method frame received\n\n \"\"\"\n LOGGER.debug('Received Basic.GetEmpty: %r', method_frame)\n\n def _on_getok(self, method_frame, header_frame, body):\n \"\"\"Called in reply to a Basic.Get when there is a message.\n\n :param pika.frame.Method method_frame: The method frame received\n :param pika.frame.Header header_frame: The header frame received\n :param body: The body received\n :type body: str or unicode\n\n \"\"\"\n if self._on_getok_callback is not None:\n callback = self._on_getok_callback\n self._on_getok_callback = None\n callback(self, method_frame.method, header_frame.properties, body)\n else:\n LOGGER.error('Basic.GetOk received with no active callback')\n\n def _on_openok(self, frame_unused):\n \"\"\"Called by our callback handler when we receive a Channel.OpenOk and\n subsequently calls our _on_openok_callback which was passed into the\n Channel constructor. The reason we do this is because we want to make\n sure that the on_open_callback parameter passed into the Channel\n constructor is not the first callback we make.\n\n :param pika.frame.Method frame_unused: Unused Channel.OpenOk frame\n\n \"\"\"\n self._set_state(self.OPEN)\n if self._on_openok_callback is not None:\n self._on_openok_callback(self)\n\n def _on_return(self, method_frame, header_frame, body):\n \"\"\"Called if the server sends a Basic.Return frame.\n\n :param pika.frame.Method method_frame: The Basic.Return frame\n :param pika.frame.Header header_frame: The content header frame\n :param body: The message body\n :type body: str or unicode\n\n \"\"\"\n if not self.callbacks.process(self.channel_number, '_on_return', self,\n self,\n method_frame.method,\n header_frame.properties,\n body):\n LOGGER.warning('Basic.Return received from server (%r, %r)',\n method_frame.method, header_frame.properties)\n\n def _on_selectok(self, method_frame):\n \"\"\"Called when the broker sends a Confirm.SelectOk frame\n\n :param pika.frame.Method method_frame: The method frame received\n\n \"\"\"\n LOGGER.debug(\"Confirm.SelectOk Received: %r\", method_frame)\n\n def _on_synchronous_complete(self, method_frame_unused):\n \"\"\"This is called when a synchronous command is completed. It will undo\n the blocking state and send all the frames that stacked up while we\n were in the blocking state.\n\n :param pika.frame.Method method_frame_unused: The method frame received\n\n \"\"\"\n LOGGER.debug('%i blocked frames', len(self._blocked))\n self._blocking = None\n while len(self._blocked) > 0 and self._blocking is None:\n self._rpc(*self._blocked.popleft())\n\n def _rpc(self, method_frame, callback=None, acceptable_replies=None):\n \"\"\"Shortcut wrapper to the Connection's rpc command using its callback\n stack, passing in our channel number.\n\n :param pika.amqp_object.Method method_frame: The method frame to call\n :param method callback: The callback for the RPC response\n :param list acceptable_replies: The replies this RPC call expects\n\n \"\"\"\n # Make sure the channel is open\n if self.is_closed:\n raise exceptions.ChannelClosed\n\n # If the channel is blocking, add subsequent commands to our stack\n if self._blocking:\n return self._blocked.append([method_frame, callback,\n acceptable_replies])\n\n # Validate we got None or a list of acceptable_replies\n if acceptable_replies and not isinstance(acceptable_replies, list):\n raise TypeError(\"acceptable_replies should be list or None\")\n\n # Validate the callback is callable\n if callback and not is_callable(callback):\n raise TypeError(\"callback should be None, a function or method.\")\n\n # Block until a response frame is received for synchronous frames\n if method_frame.synchronous:\n self._blocking = method_frame.NAME\n\n # If acceptable replies are set, add callbacks\n if acceptable_replies:\n for reply in acceptable_replies or list():\n if isinstance(reply, tuple):\n reply, arguments = reply\n else:\n arguments = None\n LOGGER.debug('Adding in on_synchronous_complete callback')\n self.callbacks.add(self.channel_number, reply,\n self._on_synchronous_complete,\n arguments=arguments)\n if callback:\n LOGGER.debug('Adding passed in callback')\n self.callbacks.add(self.channel_number, reply, callback,\n arguments=arguments)\n\n self._send_method(method_frame)\n\n def _send_method(self, method_frame, content=None):\n \"\"\"Shortcut wrapper to send a method through our connection, passing in\n the channel number\n\n :param pika.object.Method method_frame: The method frame to send\n :param tuple content: If set, is a content frame, is tuple of\n properties and body.\n\n \"\"\"\n self.connection._send_method(self.channel_number, method_frame, content)\n\n def _set_cookie(self, cookie):\n \"\"\"Used by wrapper layer (e.g., `BlockingConnection`) to link the\n channel implementation back to the proxy. See `_get_cookie`.\n\n :param cookie: an opaque value; typically a proxy channel implementation\n instance (e.g., `BlockingChannel` instance)\n \"\"\"\n self._cookie = cookie\n\n def _set_state(self, connection_state):\n \"\"\"Set the channel connection state to the specified state value.\n\n :param int connection_state: The connection_state value\n\n \"\"\"\n self._state = connection_state\n\n def _unexpected_frame(self, frame_value):\n \"\"\"Invoked when a frame is received that is not setup to be processed.\n\n :param pika.frame.Frame frame_value: The frame received\n\n \"\"\"\n LOGGER.warning('Unexpected frame: %r', frame_value)\n\n def _validate_channel_and_callback(self, callback):\n if not self.is_open:\n raise exceptions.ChannelClosed()\n if callback is not None and not is_callable(callback):\n raise ValueError('callback must be a function or method')\n\n\nclass ContentFrameDispatcher(object):\n \"\"\"Handle content related frames, building a message and return the message\n back in three parts upon receipt.\n\n \"\"\"\n\n def __init__(self):\n \"\"\"Create a new instance of the Dispatcher passing in the callback\n manager.\n\n \"\"\"\n self._method_frame = None\n self._header_frame = None\n self._seen_so_far = 0\n self._body_fragments = list()\n\n def process(self, frame_value):\n \"\"\"Invoked by the Channel object when passed frames that are not\n setup in the rpc process and that don't have explicit reply types\n defined. This includes Basic.Publish, Basic.GetOk and Basic.Return\n\n :param Method|Header|Body frame_value: The frame to process\n\n \"\"\"\n if (isinstance(frame_value, frame.Method) and\n spec.has_content(frame_value.method.INDEX)):\n self._method_frame = frame_value\n elif isinstance(frame_value, frame.Header):\n self._header_frame = frame_value\n if frame_value.body_size == 0:\n return self._finish()\n elif isinstance(frame_value, frame.Body):\n return self._handle_body_frame(frame_value)\n else:\n raise exceptions.UnexpectedFrameError(frame_value)\n\n def _finish(self):\n \"\"\"Invoked when all of the message has been received\n\n :rtype: tuple(pika.frame.Method, pika.frame.Header, str)\n\n \"\"\"\n content = (self._method_frame, self._header_frame,\n b''.join(self._body_fragments))\n self._reset()\n return content\n\n def _handle_body_frame(self, body_frame):\n \"\"\"Receive body frames and append them to the stack. When the body size\n matches, call the finish method.\n\n :param Body body_frame: The body frame\n :raises: pika.exceptions.BodyTooLongError\n :rtype: tuple(pika.frame.Method, pika.frame.Header, str)|None\n\n \"\"\"\n self._seen_so_far += len(body_frame.fragment)\n self._body_fragments.append(body_frame.fragment)\n if self._seen_so_far == self._header_frame.body_size:\n return self._finish()\n elif self._seen_so_far > self._header_frame.body_size:\n raise exceptions.BodyTooLongError(self._seen_so_far,\n self._header_frame.body_size)\n return None\n\n def _reset(self):\n \"\"\"Reset the values for processing frames\"\"\"\n self._method_frame = None\n self._header_frame = None\n self._seen_so_far = 0\n self._body_fragments = list()\n","sub_path":"aio_pika/pika/channel.py","file_name":"channel.py","file_ext":"py","file_size_in_byte":53073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"627547504","text":"# -*- coding: UTF-8 -*-\nfrom tkinter import *\nfrom Unit import *\nfrom Flag import *\nfrom Helper import *\nimport tkinter.messagebox as mb\nimport subprocess\n\nclass View(): \n def __init__(self, parent):\n self.parent = parent \n self.root=Tk()\n self.root.title(\"Orion\")\n self.root.resizable(0,0)\n #la taille du jeu se resize selon la résolution de l'écran, niceshithum?\n self.taille=self.root.winfo_screenheight()-125\n if self.taille>800:\n self.taille=800\n self.root.geometry('+25+5')\n self.dragging = False\n self.hpBars=False\n self.selectStart = [0,0]\n self.selectEnd = [0,0]\n self.positionMouse = [0,0,0]\n self.mainMenuBG = PhotoImage(file='images\\\\Menus\\\\MainMenuBG.gif')\n self.mainMenu = self.fMainMenu()\n self.mainMenu.pack()\n self.pLobby = None\n self.currentFrame = self.mainMenu\n self.firstTime = True\n self.gameFrame = None\n self.joinGame = self.fJoinGame()\n self.createServer = self.fCreateServer()\n self.sun=PhotoImage(file='images\\\\Galaxy\\\\sun.gif')\n self.sunFOW = PhotoImage(file='images\\\\Galaxy\\\\sunFOW.gif')\n self.planet=PhotoImage(file='images\\\\Galaxy\\\\planet.gif')\n self.planetFOW = PhotoImage(file='images\\\\Galaxy\\\\planetFOW.gif')\n self.nebula=PhotoImage(file='images\\\\Galaxy\\\\nebula.gif')\n self.nebulaFOW=PhotoImage(file='images\\\\Galaxy\\\\nebulaFOW.gif')\n self.explosion=PhotoImage(file='images\\\\explosion.gif')\n self.attacking = False\n self.asteroid=PhotoImage(file='images\\\\Galaxy\\\\asteroid.gif')\n self.asteroidFOW=PhotoImage(file='images\\\\Galaxy\\\\asteroidFOW.gif')\n self.mineral = PhotoImage(file='images\\\\Planet\\\\crystal.gif')\n self.gifStop = PhotoImage(file='images\\\\icones\\\\stop2.gif')\n self.gifMove = PhotoImage(file='images\\\\icones\\\\move2.gif')\n self.gifCancel = PhotoImage(file='images\\\\icones\\\\delete2.gif')\n self.gifAttack = PhotoImage(file='images\\\\icones\\\\attack2.gif')\n self.gifIcone2 = PhotoImage(file='images\\\\icones\\\\icone2.gif')\n self.gifPatrol = PhotoImage(file='images\\\\icones\\\\patrol2.gif')\n self.gifChat = PhotoImage(file='images\\\\icones\\\\boutonChat.gif')\n self.gifTrade = PhotoImage(file='images\\\\icones\\\\boutonTrade.gif')\n self.gifTeam = PhotoImage(file='images\\\\icones\\\\boutonTeam.gif')\n self.planetBackground = PhotoImage(file='images\\\\Planet\\\\background.gif')\n self.galaxyBackground = PhotoImage(file='images\\\\Galaxy\\\\night-sky.gif')\n self.gifCadreMenuAction = PhotoImage(file='images\\\\cadreMenuAction2.gif')\n self.attacking = False\n self.selectAllUnits = False\n # Quand le user ferme la fenêtre et donc le jeu, il faut l'enlever du serveur\n self.root.protocol('WM_DELETE_WINDOW', self.parent.removePlayer)\n \n def changeFrame(self, frame):\n self.currentFrame.pack_forget()\n frame.pack()\n self.currentFrame = frame\n\n #Frame principal du jeu \n def fGame(self):\n gameFrame = Frame(self.root, bg=\"black\")\n self.scoutShips = []\n self.attackShips = []\n self.motherShips = []\n self.trasportShips = []\n for i in range(0,8):\n self.scoutShips.append(PhotoImage(file='images\\\\Ships\\\\Scoutships\\\\Scoutship'+str(i)+'.gif'))\n self.attackShips.append(PhotoImage(file='images\\\\Ships\\\\Attackships\\\\Attackship'+str(i)+'.gif'))\n self.motherShips.append(PhotoImage(file='images\\\\Ships\\\\Motherships\\\\Mothership'+str(i)+'.gif'))\n self.trasportShips.append(PhotoImage(file='images\\\\Ships\\\\Transport\\\\Transport'+str(i)+'.gif'))\n Label(gameFrame, text=\"Mineraux: \", bg=\"black\", fg=\"white\", width=10, anchor=E).grid(column=0, row=0)\n self.showMinerals=Label(gameFrame, text=self.parent.players[self.parent.playerId].mineral, fg=\"white\", bg=\"black\", anchor=W)\n self.showMinerals.grid(column=1,row=0)\n Label(gameFrame, text=\"Gaz: \", bg=\"black\", fg=\"white\", width=10, anchor=E).grid(column=2, row=0)\n self.showGaz=Label(gameFrame, text=self.parent.players[self.parent.playerId].gaz, fg=\"white\", bg=\"black\", anchor=W)\n self.showGaz.grid(column=3,row=0)\n self.gameArea=Canvas(gameFrame, width=self.taille, height=self.taille-200, background='Black', relief='ridge')\n self.gameArea.grid(column=0,row=1, columnspan=5)#place(relx=0, rely=0,width=taille,height=taille)\n self.minimap= Canvas(gameFrame, width=200,height=200, background='Black', relief='raised')\n self.minimap.grid(column=0,row=2, rowspan=4)\n self.menuModes=Canvas(gameFrame, width=self.taille, height=200, background='black', relief='ridge')\n self.menuModes.grid(row=2,column=2) \n self.Actionmenu = Canvas(gameFrame,width=200,height=200,background='black')\n self.Actionmenu.grid(column=3,row=2, rowspan=4)\n self.changeBackground('GALAXY')\n self.drawWorld()\n self.createActionMenu()\n self.menuChat(gameFrame)\n self.assignControls()\n return gameFrame\n \n def menuTeam(self):\n self.menuModesremove() \n self.menuModes.create_text(150,50,text='voici le menu Team',fill='white')\n \n def menuTrade(self):\n self.menuModesremove()\n self.menuModes.create_text(150,50,text='voici le menu Tradeeee',fill='red')\n \n def menuChat(self,gameFrame):\n self.menuModesremove()\n self.menuModes.chat = Label(gameFrame, anchor=W, justify=LEFT, width=75, background='black', fg='white', relief='raised')\n self.menuModes.chat.grid(row=2, column=2)\n self.menuModes.entryMess = Entry(gameFrame, width=60)\n self.menuModes.entryMess.grid(row=5, column=2)\n \n # delete tout ce qu'il y a dans le canvas menuModes + affiche les 3 menus\n def menuModesremove(self):\n self.menuModes.delete(ALL)\n self.menuModes.create_image(0,0,image=self.gifChat,anchor = NW,tag='bouton_chat')\n self.menuModes.create_image(77,0,image=self.gifTrade,anchor = NW,tag='bouton_trade')\n self.menuModes.create_image(150,0,image=self.gifTeam,anchor = NW,tag='bouton_team')\n\n #Creation du menu Action\n def createActionMenu(self):\n self.Actionmenu.delete(ALL)\n units = self.parent.players[self.parent.playerId].selectedObjects\n self.Actionmenu.create_image(0,0,image=self.gifCadreMenuAction,anchor = NW)\n if len(units) > 0:\n if isinstance(units[0], Unit):\n self.Actionmenu.create_image(13,35,image=self.gifMove,anchor = NW)\n self.Actionmenu.create_image(76,35,image=self.gifStop,anchor = NW)\n if isinstance(units[0], SpaceAttackUnit):\n self.Actionmenu.create_image(140,35,image=self.gifAttack,anchor = NW)\n if isinstance(units[0],Mothership):\n self.Actionmenu.create_image(140,35,image=self.gifAttack,anchor = NW)\n self.Actionmenu.create_image(13,89,image=self.gifCancel,anchor = NW)\n self.Actionmenu.create_image(76,89,image=self.gifPatrol,anchor = NW)\n\n\t#Frame du menu principal \n def fMainMenu(self):\n mainMenuFrame = Frame(self.root, bg=\"black\")\n panel1 = Label(mainMenuFrame, image=self.mainMenuBG)\n panel1.grid(row=0, column=0, rowspan=10)\n Button(mainMenuFrame, text='Créer une partie', command=lambda:self.changeFrame(self.createServer)).grid(row=7, column=0)\n Button(mainMenuFrame, text='Rejoindre une partie', command=lambda:self.changeFrame(self.joinGame)).grid(row=8, column=0)\n return mainMenuFrame\n \n #Frame permettant de rejoindre une partie\n def fJoinGame(self):\n joinGameFrame = Frame(self.root, bg=\"black\")\n Label(joinGameFrame, text=\"Nom de joueur:\", fg=\"white\", bg=\"black\").grid(row=0, column=0)\n self.entryLogin = Entry(joinGameFrame, width=20)\n self.entryLogin.focus_set()\n self.entryLogin.grid(row=0, column=1)\n #self.entryLogin.delete(0,END)\n Label(joinGameFrame, text=\"Adresse du serveur:\", fg=\"white\", bg=\"black\").grid(row=1, column=0)\n self.entryServer = Entry(joinGameFrame, width=20)\n self.entryServer.grid(row=1, column=1)\n #self.entryServer.delete(0,END)\n widget = Button(joinGameFrame, text='Connecter', command=lambda:self.lobbyEnter(0, self.entryLogin.get(), self.entryServer.get()))\n widget.grid(row=2, column=1)\n\t\t#Crée un bouton de retour au menu principal\n widget = Button(joinGameFrame, text='Retour', command=lambda:self.changeFrame(self.mainMenu), width=10)\n widget.grid(row=3, column=1, columnspan=2, pady=10)\n self.entryServer.bind(\"\",self.lobbyEnter)\n return joinGameFrame\n \n #Frame de création de nouveau serveur\n def fCreateServer(self):\n #Crée le frame\n createServerFrame = Frame(self.root, bg=\"black\")\n #Crée le label de l'IP du serveur\n Label(createServerFrame, text=\"Adresse du serveur:\", fg=\"white\", bg=\"black\").grid(row=0, column=0)\n #Crée le champ texte pour l'IP du serveur\n self.entryCreateServer = Entry(createServerFrame, width=20)\n #On met l'adresse de l'hôte comme valeur par défaut\n self.entryCreateServer.insert(0,self.parent.playerIp)\n self.entryCreateServer.grid(row=0, column=1)\n #Crée le label du nom du joueur\n Label(createServerFrame, text=\"Nom de joueur:\", fg=\"white\", bg=\"black\").grid(row=1, column=0)\n #Crée le champ texte pour le nom du joueur\n self.entryCreateLogin = Entry(createServerFrame, width=20)\n self.entryCreateLogin.focus_set()\n self.entryCreateLogin.grid(row=1, column=1)\n #Crée le bouton de confirmation\n widget = Button(createServerFrame, text='Créer', command=lambda:self.startServer(False))\n widget.grid(row=2, column=1)\n #Crée le bouton de confirmation et se connecte\n widget = Button(createServerFrame, text='Créer et connecter', command=lambda:self.startServer(True))\n widget.grid(row=3, column=1)\n\t\t#Crée un bouton de retour au menu principal\n widget = Button(createServerFrame, text='Retour', command=lambda:self.changeFrame(self.mainMenu), width=10)\n widget.grid(row=5, column=1, columnspan=2, pady=10)\n return createServerFrame\n\n def startServer(self, connect):\n serverAddress= self.entryCreateServer.get()\n #Démarre le serveur dans un autre processus avec l'adresse spécifiée\n child = subprocess.Popen(\"C:\\python32\\python.exe server.py \" + serverAddress, shell=True)\n #On vérifie si le serveur s'est terminé en erreur et si oui, on affiche un message à l'utilisateur\n if child.poll():\n if child.returncode != None:\n child.terminate()\n self.serverNotCreated()\n else:\n self.serverCreated(serverAddress)\n #Si l'usager veut se connecter en créant le serveur, on le connecte\n if connect:\n self.parent.connectServer(self.entryCreateLogin.get(), self.entryCreateServer.get())\n else:\n self.changeFrame(self.mainMenu)\n\n \n #Frame du lobby\n def fLobby(self):\n self.entryServer.unbind(\"\")\n lobbyFrame = Frame(self.root, bg=\"black\")\n if self.parent.server != None:\n pNum = len(self.parent.server.getSockets())\n for i in range(0, pNum):\n Label(lobbyFrame, text=self.parent.server.getSockets()[i][1], fg=\"white\", bg=\"black\").grid(row=i,column=0)\n Label(lobbyFrame, text='Admin : '+self.parent.server.getSockets()[0][1], fg=\"white\", bg=\"black\").grid(row=(pNum+1), column=1)\n if self.parent.playerId == 0:\n Button(lobbyFrame, text='Demarrer la partie', command=self.parent.startGame, bg=\"black\", fg=\"white\").grid(row=(pNum+2), column=1)\n self.chatLobby = Label(lobbyFrame, anchor=W, justify=LEFT, width=45, background='black', fg='white', relief='raised')\n self.chatLobby.grid(row=(pNum+11), column=1)\n self.entryMessLobby = Entry(lobbyFrame, width=35)\n self.entryMessLobby.grid(row=(pNum+12), column=1)\n self.entryMessLobby.bind(\"\", self.sendMessLobby)\n #Choix de couleur\n self.variableColor = StringVar(lobbyFrame)\n self.colorOPTIONS = [\"Orange\",\"Rouge\",\"Bleu\",\"Vert\",\"Jaune\",\"Brun\",\"Blanc\",\"Rose\"]\n self.variableColor.set(self.colorOPTIONS[0]) # default value\n self.colorChoice = OptionMenu(lobbyFrame, self.variableColor, *self.colorOPTIONS, command=self.parent.choiceColor)\n self.colorChoice.grid(row=(self.parent.playerId), column=1)\n self.buttonColor = Button(lobbyFrame, text=\"OK\", command=self.parent.choiceColor, bg=\"black\", fg=\"white\")\n self.buttonColor.grid(row=(self.parent.playerId), column=2)\n return lobbyFrame\n\n def redrawLobby(self ,lobbyFrame):\n if self.parent.server.getSockets()[self.parent.playerId][3] == -1:\n listOfColors = self.parent.server.getColorChoices()\n self.colorChoice['menu'].delete(0, END)\n for i in listOfColors:\n if i[1] == False:\n self.colorChoice['menu'].add_command(label=i[0], command=lambda temp = i[0]: self.colorChoice.setvar(self.colorChoice.cget(\"textvariable\"), value = temp))\n else:\n self.buttonColor.configure(state=DISABLED, background='white')\n self.colorChoice['menu'].delete(0, END)\n if self.parent.server != None:\n pNum = len(self.parent.server.getSockets())\n for i in range(0, pNum):\n Label(lobbyFrame, text=self.parent.server.getSockets()[i][1], fg=\"white\", bg=\"black\").grid(row=i,column=0)\n Label(lobbyFrame, text='Admin : '+self.parent.server.getSockets()[0][1], fg=\"white\", bg=\"black\").grid(row=(pNum+1), column=1)\n if self.parent.playerId == 0:\n Button(lobbyFrame, text='Demarrer la partie', command=self.parent.startGame, bg=\"black\", fg=\"white\").grid(row=(pNum+2), column=1)\n\n def sendMessLobby(self, eve):\n if self.entryMessLobby.get() != \"\":\n self.parent.sendMessageLobby(self.entryMessLobby.get(), self.parent.server.getSockets()[self.parent.playerId][1])\n self.entryMessLobby.delete(0,END)\n \n def loginFailed(self):\n mb.showinfo('Erreur de connection', 'Le serveur est introuvable. Veuillez reessayer.')\n \n def colorAlreadyChosen(self):\n mb.showinfo('Trop tard!', 'La couleur sélectionnée a déjà été choisie.')\n\n def gameHasBeenStarted(self):\n mb.showinfo('Erreur de connection', 'La partie a déjà débutée. Veuillez attendre sa fin.')\n \n def showGameIsFinished(self):\n mb.showinfo('Fin de la partie', 'L\\'administrateur de la partie a quitté prématurément la partie, la partie est donc terminée.')\n\n def serverCreated(self, serverIP):\n mb.showinfo('Serveur créé', 'Le serveur a été créé à l\\'adresse ' + serverIP + '.')\n \n def serverNotCreated(self):\n mb.showinfo('Serveur non créé', 'Une erreur est survenue lors de la création du serveur.\\nVeuillez vérifier que les informations entrées sont exactes.')\n #Methode pour dessiner la vue d'un planete\n def drawPlanetGround(self, planet):\n self.gameArea.delete('deletable')\n for i in planet.minerals:\n self.gameArea.create_image(i.position[0], i.position[1], image=self.mineral, tag='deletable')\n for i in planet.gaz:\n self.gameArea.create_oval(i.position[0]-12, i.position[1]-12, i.position[0]+12, i.position[1]+12, fill='green', tag='deletable')\n\n def changeBackground(self, type):\n self.gameArea.delete('background')\n if type == 'PLANET':\n self.gameArea.create_image(0,0,image=self.planetBackground, anchor=NW, tag='background')\t\t\n else:\n self.gameArea.create_image(0,0,image=self.galaxyBackground, anchor=NW, tag='background')\n\n #Methode pour dessiner la galaxie\n def drawWorld(self):\n self.gameArea.delete('deletable')\n sunList = self.parent.galaxy.solarSystemList\n players = self.parent.players \n id = self.parent.playerId\n for i in sunList:\n if self.parent.players[self.parent.playerId].inViewRange(i.sunPosition):\n if not i.discovered:\n i.discovered = True\n self.redrawMinimap()\n self.drawSun(i.sunPosition, players[id], True)\n else:\n if i.discovered:\n self.drawSun(i.sunPosition, players[id], False)\n for j in i.planets:\n if self.parent.players[self.parent.playerId].inViewRange(j.position):\n if not j.discovered:\n j.discovered = True\n self.redrawMinimap()\n self.drawPlanet(j, players[id], True)\n else:\n if j.discovered:\n self.drawPlanet(j, players[id], False)\n for j in i.nebulas:\n if self.parent.players[self.parent.playerId].inViewRange(j.position):\n if not j.discovered:\n j.discovered = True\n self.redrawMinimap()\n self.drawNebula(j, players[id], True)\n else:\n if j.discovered:\n self.drawNebula(j, players[id], False)\n for j in i.asteroids:\n if self.parent.players[self.parent.playerId].inViewRange(j.position):\n if not j.discovered:\n j.discovered = True\n self.redrawMinimap()\n self.drawAsteroid(j, players[id], True)\n else:\n if j.discovered:\n self.drawAsteroid(j, players[id], False)\n for i in players:\n for j in i.units:\n if j.isAlive:\n if self.parent.players[self.parent.playerId].inViewRange(j.position):\n if j.name == 'Mothership':\n j.discovered = True\n self.drawUnit(j, i, False)\n if self.dragging:\n self.drawSelectionBox()\n self.drawMinimap()\n \n #Pour dessiner un soleil \n def drawSun(self, sunPosition, player, isInFOW):\n if player.camera.isInFOV(sunPosition):\n distance = player.camera.calcDistance(sunPosition)\n if isInFOW:\n self.gameArea.create_image(distance[0],distance[1], image=self.sun, tag='deletable')\n else:\n self.gameArea.create_image(distance[0],distance[1], image=self.sunFOW, tag='deletable')\n #self.gameArea.create_oval(distance[0]-20, distance[1]-20, distance[0]+20, distance[1]+20, fill='RED')\n \n #pour dessiner une planete \n def drawPlanet(self, planet, player, isInFOW):\n planetPosition = planet.position\n if player.camera.isInFOV(planetPosition):\n distance = player.camera.calcDistance(planetPosition)\n if isInFOW:\n if planet in player.selectedObjects:\n self.gameArea.create_oval(distance[0]-10, distance[1]-10, distance[0]+10, distance[1]+10,outline=\"green\", tag='deletable')\n mVariable = \"Mineral :\" + str(planet.mineralQte)\n gVariable = \"Gaz :\" + str(planet.gazQte)\n self.gameArea.create_text(distance[0]-20, distance[1]-25,fill=\"cyan\",text=mVariable, tag='deletable')\n self.gameArea.create_text(distance[0]-20, distance[1]-40,fill=\"green\",text=gVariable, tag='deletable')\n self.gameArea.create_image(distance[0],distance[1],image=self.planet, tag='deletable')\n else:\n self.gameArea.create_image(distance[0], distance[1], image=self.planetFOW, tag='deletable')\n #self.gameArea.create_oval(distance[0]-10, distance[1]-10, distance[0]+10, distance[1]+10, fill='BLUE', tag=\"planet\")\n\n def drawNebula(self,nebula,player, isInFOW):\n nebulaPosition = nebula.position\n if player.camera.isInFOV(nebulaPosition):\n distance = player.camera.calcDistance(nebulaPosition)\n if isInFOW:\n if nebula in player.selectedObjects:\n self.gameArea.create_oval(distance[0]-10, distance[1]-10, distance[0]+10, distance[1]+10,outline=\"green\", tag='deletable')\n mVariable = \"Gaz :\" + str(nebula.gazQte)\n self.gameArea.create_text(distance[0]-20, distance[1]-25,fill=\"green\",text=mVariable, tag='deletable')\n self.gameArea.create_image(distance[0],distance[1],image=self.nebula, tag='deletable')\n else:\n self.gameArea.create_image(distance[0], distance[1], image=self.nebulaFOW, tag='deletable')\n \n def drawAsteroid(self,asteroid,player, isInFOW):\n asteroidPosition = asteroid.position\n if player.camera.isInFOV(asteroidPosition):\n distance = player.camera.calcDistance(asteroidPosition)\n if isInFOW:\n if asteroid in player.selectedObjects:\n self.gameArea.create_oval(distance[0]-10, distance[1]-10, distance[0]+10, distance[1]+10,outline=\"green\", tag='deletable')\n mVariable = \"Mineral :\" + str(asteroid.mineralQte)\n self.gameArea.create_text(distance[0]-20, distance[1]-25,fill=\"cyan\",text=mVariable, tag='deletable')\n self.gameArea.create_image(distance[0],distance[1],image=self.asteroid, tag='deletable')\n else:\n self.gameArea.create_image(distance[0],distance[1],image=self.asteroidFOW, tag='deletable')\n \n #pour dessiner un vaisseau \n def drawUnit(self, unit, player, isInFOW):\n unitPosition = unit.position\n if self.parent.players[self.parent.playerId].camera.isInFOV(unitPosition):\n distance = self.parent.players[self.parent.playerId].camera.calcDistance(unitPosition)\n if not isInFOW:\n if unit.name.find('Scout') != -1:\n if unit in player.selectedObjects:\n self.gameArea.create_oval(distance[0]-8,distance[1]-8,distance[0]+8,distance[1]+8, outline=\"green\", tag='deletable')\n self.gameArea.create_image(distance[0]+1, distance[1], image=self.scoutShips[player.colorId],tag='deletable')#On prend l'image dependamment du joueur que nous sommes\n if unit.name.find('Attack') != -1:\n if unit.attackcount <= 5:\n d2 = self.parent.players[self.parent.playerId].camera.calcDistance(unit.flag.finalTarget.position)\n self.gameArea.create_line(distance[0],distance[1], d2[0], d2[1], fill=\"yellow\", tag='deletable')\n if unit in player.selectedObjects:\n self.gameArea.create_oval(distance[0]-13,distance[1]-13,distance[0]+13,distance[1]+13, outline=\"green\", tag='deletable')\n self.gameArea.create_image(distance[0]+1, distance[1], image=self.attackShips[player.colorId], tag='deletable')#On prend l'image dependamment du joueur que nous sommes\n elif unit.name == 'Mothership':\n if unit in player.selectedObjects:\n self.gameArea.create_oval(distance[0]-65,distance[1]-65,distance[0]+65,distance[1]+65, outline=\"green\", tag='deletable')\n self.gameArea.create_image(distance[0]+1, distance[1], image = self.motherShips[player.colorId], tag='deletable')\n elif unit.name == 'Transport':\n if unit in player.selectedObjects:\n self.gameArea.create_oval(distance[0]-18,distance[1]-18,distance[0]+18,distance[1]+18, outline=\"green\", tag='deletable')\n self.gameArea.create_image(distance[0]+1, distance[1], image = self.trasportShips[player.colorId], tag='deletable')\n if unit.hitpoints <= 5:\n self.gameArea.create_image(distance[0]+1, distance[1], image=self.explosion, tag='deletable')\n if self.hpBars:\n self.drawHPBars(distance, unit)\n else:\n self.drawHPHoverUnit(unit, distance)\n \n def drawHPHoverUnit(self, unit, distance):\n posSelected=self.parent.players[self.parent.playerId].camera.calcPointInWorld(self.positionMouse[0],self.positionMouse[1])\n if unit.position[0] >= posSelected[0]-8 and unit.position[0] <= posSelected[0]+8:\n if unit.position[1] >= posSelected[1]-8 and unit.position[1] <= posSelected[1]+8:\n hpLeft=((unit.hitpoints/unit.maxHP)*30)-15\n hpLost=(hpLeft+(((unit.maxHP-unit.hitpoints)/unit.maxHP)*30))\n self.gameArea.create_rectangle(distance[0]-15,distance[1]-11,distance[0]+hpLeft,distance[1]-11, outline=\"green\", tag='deletable')\n if int(unit.hitpoints) != int(unit.maxHP):\n self.gameArea.create_rectangle(distance[0]+hpLeft,distance[1]-11,distance[0]+hpLost,distance[1]-11, outline=\"red\", tag='deletable')\n \n def drawHPBars(self, distance, unit):\n hpLeft=((unit.hitpoints/unit.maxHP)*30)-15\n hpLost=(hpLeft+(((unit.maxHP-unit.hitpoints)/unit.maxHP)*30))\n self.gameArea.create_rectangle(distance[0]-15,distance[1]-11,distance[0]+hpLeft,distance[1]-11, outline=\"green\", tag='deletable')\n if int(unit.hitpoints) != int(unit.maxHP):\n self.gameArea.create_rectangle(distance[0]+hpLeft,distance[1]-11,distance[0]+hpLost,distance[1]-11, outline=\"red\", tag='deletable')\n \n \n #Dessine la minimap\n def drawMinimap(self):\n self.minimap.delete('deletable')\n sunList = self.parent.galaxy.solarSystemList\n players = self.parent.players\n if self.firstTime:\n for i in sunList:\n self.drawMiniSun(i)\n for j in i.planets:\n self.drawMiniPlanet(j)\n for n in i.nebulas:\n self.drawMiniNebula(n)\n for q in i.asteroids:\n self.drawMiniAsteroid(q)\n self.firstTime = False\n for i in players:\n for j in i.units:\n if j.isAlive:\n if players[self.parent.playerId].inViewRange(j.position):\n self.drawMiniUnit(j)\n self.drawMiniFOV()\n \n def redrawMinimap(self):\n self.minimap.delete(ALL)\n sunList = self.parent.galaxy.solarSystemList\n players = self.parent.players\n for i in sunList:\n self.drawMiniSun(i)\n for j in i.planets:\n self.drawMiniPlanet(j)\n for n in i.nebulas:\n self.drawMiniNebula(n)\n for q in i.asteroids:\n self.drawMiniAsteroid(q)\n for i in players:\n for j in i.units:\n if j.isAlive:\n if players[self.parent.playerId].inViewRange(j.position):\n self.drawMiniUnit(j)\n self.drawMiniFOV()\n\n #Dessine le carrer de la camera dans la minimap \n def drawMiniFOV(self):\n cameraX = (self.parent.players[self.parent.playerId].camera.position[0]-(self.taille/2) + self.parent.galaxy.width/2) / self.parent.galaxy.width * 200\n cameraY = (self.parent.players[self.parent.playerId].camera.position[1]-((self.taille/2)-self.taille/8) + self.parent.galaxy.height/2) / self.parent.galaxy.height * 200\n width = self.taille / self.parent.galaxy.width * 200\n height = self.taille / self.parent.galaxy.height * 150\n self.minimap.create_rectangle(cameraX, cameraY, cameraX+width, cameraY+height, outline='GREEN', tag='deletable')\n\n #Dessine un soleil dans la minimap \n def drawMiniSun(self, sun):\n sunPosition = sun.sunPosition\n sunX = (sunPosition[0] + self.parent.galaxy.width/2) / self.parent.galaxy.width * 200\n sunY = (sunPosition[1] + self.parent.galaxy.height/2) / self.parent.galaxy.height * 200\n if sun.discovered:\n self.minimap.create_oval(sunX-3, sunY-3, sunX+3, sunY+3, fill='ORANGE')\n\n #Dessine une planete dans la minimap \n def drawMiniPlanet(self, planet):\n planetPosition = planet.position\n planetX = (planetPosition[0] + self.parent.galaxy.width/2) / self.parent.galaxy.width * 200\n planetY = (planetPosition[1] + self.parent.galaxy.height/2) / self.parent.galaxy.height * 200\n if planet.discovered:\n self.minimap.create_oval(planetX-1, planetY-1, planetX+1, planetY+1, fill='LIGHT BLUE')\n \n #dessine une nebula dans la minimap\n def drawMiniNebula(self, nebula):\n nebulaPosition = nebula.position\n nebulaX = (nebulaPosition[0] + self.parent.galaxy.width/2) / self.parent.galaxy.width * 200\n nebulaY = (nebulaPosition[1] + self.parent.galaxy.height/2) / self.parent.galaxy.height * 200\n if nebula.discovered:\n self.minimap.create_oval(nebulaX-1, nebulaY-1, nebulaX+1, nebulaY+1, fill='PURPLE')\n \n #dessine un asteroid dans la minimap\n def drawMiniAsteroid(self, asteroid):\n asteroidPosition = asteroid.position\n asteroidX = (asteroidPosition[0] + self.parent.galaxy.width/2) / self.parent.galaxy.width * 200\n asteroidY = (asteroidPosition[1] + self.parent.galaxy.height/2) / self.parent.galaxy.height * 200\n if asteroid.discovered:\n self.minimap.create_oval(asteroidX-1, asteroidY-1, asteroidX+1, asteroidY+1, fill='CYAN')\n \n #Dessine une unite dans la minimap \n def drawMiniUnit(self, unit):\n unitX = (unit.position[0] + self.parent.galaxy.width/2) / self.parent.galaxy.width * 200\n planetY = (unit.position[1] + self.parent.galaxy.height/2) / self.parent.galaxy.height * 200\n if unit.name != \"Mothership\":\n if unit in self.parent.players[self.parent.playerId].units:\n self.minimap.create_polygon((unitX-2, planetY+2, unitX, planetY-2, unitX+2, planetY+2),fill='GREEN', tag='deletable')\n else:\n self.minimap.create_polygon((unitX-2, planetY+2, unitX, planetY-2, unitX+2, planetY+2),fill='RED', tag='deletable')\n else:\n if unit in self.parent.players[self.parent.playerId].units:\n self.minimap.create_polygon((unitX-4, planetY+2, unitX, planetY-2, unitX+4, planetY+2),fill='WHITE', tag='deletable')\n else:\n self.minimap.create_polygon((unitX-4, planetY+2, unitX, planetY-2, unitX+4, planetY+2),fill='RED', tag='deletable')\n\n #Dessine la boite de selection lors du clic-drag\t\n def drawSelectionBox(self):\n self.gameArea.create_rectangle(self.selectStart[0], self.selectStart[1], self.selectEnd[0], self.selectEnd[1], outline='WHITE', tag='deletable')\n\n #Actions quand on clic sur les fleches du clavier\n def keyPressUP(self, eve):\n if 'UP' not in self.parent.players[self.parent.playerId].camera.movingDirection:\n if self.parent.players[self.parent.playerId].currentPlanet == None:\n self.parent.players[self.parent.playerId].camera.movingDirection.append('UP')\n self.drawWorld()\n\n def keyPressDown(self, eve):\n if 'DOWN' not in self.parent.players[self.parent.playerId].camera.movingDirection:\n if self.parent.players[self.parent.playerId].currentPlanet == None:\n self.parent.players[self.parent.playerId].camera.movingDirection.append('DOWN')\n self.drawWorld()\n\n def keyPressLeft(self, eve):\n if 'LEFT' not in self.parent.players[self.parent.playerId].camera.movingDirection:\n if self.parent.players[self.parent.playerId].currentPlanet == None:\n self.parent.players[self.parent.playerId].camera.movingDirection.append('LEFT')\n self.drawWorld()\n\n def keyPressRight(self, eve):\n if 'RIGHT' not in self.parent.players[self.parent.playerId].camera.movingDirection:\n if self.parent.players[self.parent.playerId].currentPlanet == None:\n self.parent.players[self.parent.playerId].camera.movingDirection.append('RIGHT')\n self.drawWorld()\n\n #Actions quand on lache les touches\n def keyReleaseUP(self, eve):\n if self.parent.players[self.parent.playerId].currentPlanet == None:\n self.parent.players[self.parent.playerId].camera.movingDirection.remove('UP')\n self.drawWorld()\n\n def keyReleaseDown(self, eve):\n if self.parent.players[self.parent.playerId].currentPlanet == None:\n self.parent.players[self.parent.playerId].camera.movingDirection.remove('DOWN')\n self.drawWorld()\n\n def keyReleaseLeft(self, eve):\n if self.parent.players[self.parent.playerId].currentPlanet == None:\n self.parent.players[self.parent.playerId].camera.movingDirection.remove('LEFT')\n self.drawWorld()\n\n def keyReleaseRight(self, eve):\n if self.parent.players[self.parent.playerId].currentPlanet == None:\n self.parent.players[self.parent.playerId].camera.movingDirection.remove('RIGHT')\n self.drawWorld()\n\n #Actions avec la souris \n def rightclic(self, eve):\n self.attacking = False\n x = eve.x\n y = eve.y\n canva = eve.widget\n if x > 0 and x < self.taille:\n if y > 0 and y < self.taille-200:\n if canva == self.gameArea:\n pos = self.parent.players[self.parent.playerId].camera.calcPointInWorld(x,y)\n self.parent.rightClic(pos)\n elif canva == self.minimap and self.parent.players[self.parent.playerId].currentPlanet == None:\n pos = self.parent.players[self.parent.playerId].camera.calcPointMinimap(x,y)\n self.parent.setMovingFlag(pos[0], pos[1])\n self.drawWorld()\n\n #Quand on fait un clic gauche (peu importe ou)\n def leftclic(self, eve):\n x = eve.x\n y = eve.y\n canva = eve.widget\n if canva == self.gameArea:\n pos = self.parent.players[self.parent.playerId].camera.calcPointInWorld(x,y)\n if self.attacking:\n self.parent.setAttackFlag(pos[0],pos[1])\n else:\n if not self.selectAllUnits:\n self.parent.select(pos)\n else:\n self.parent.selectAll(pos)\n elif canva == self.minimap:\n self.parent.quickMove(x,y,canva)\n\n def selectAll(self, eve):\n self.selectAllUnits = True\n def unSelectAll(self, eve):\n self.selectAllUnits = False\n\n #Quand on fait un clic gauche et qu'on bouge\n def clicDrag(self,eve):\n self.attacking = False\n if self.dragging == False:\n self.selectStart = [eve.x, eve.y]\n self.selectEnd = [eve.x, eve.y]\n self.dragging = True\n else:\n self.selectEnd = [eve.x, eve.y]\n\n #Quand on clicDrag et qu'on lache la souris\n def endDrag(self, eve):\n self.attacking = False\n if self.dragging:\n self.dragging = False\n self.selectEnd = [eve.x, eve.y]\n self.parent.boxSelect(self.selectStart, self.selectEnd)\n\n def posMouse(self, eve):\n self.positionMouse[0] = eve.x\n self.positionMouse[1] = eve.y\n \n def ctrlPressed(self, eve):\n self.hpBars=True\n \n def ctrlDepressed(self, eve):\n self.hpBars=False\n\n #methode test attack\n def attack(self,eve):\n self.attacking = True\n \n #Quand on appui sur enter dans le chat\t\t\n def enter(self, eve):\n self.parent.sendMessage(self.menuModes.entryMess.get())\n self.menuModes.entryMess.delete(0,END)\n self.gameArea.focus_set()\n\n #Quand on appui sur enter dans le login\n def lobbyEnter(self, eve, login=\"\", server=\"\"):\n if login==\"\" and server==\"\":\n login = self.entryLogin.get()\n server = self.entryServer.get()\n self.parent.connectServer(login,server)\n\t\t\t\n def stop(self, eve):\n self.attacking = False\n self.parent.setStandbyFlag()\n\n def delete(self, eve):\n self.attacking = False\n self.parent.eraseUnit()\n \n #Pour la selection multiple\t\n def shiftPress(self, eve):\n self.parent.multiSelect = True\n\n def shiftRelease(self, eve):\n self.parent.multiSelect = False\n\t\n def checkMotherSip(self, eve):\n self.parent.players[self.parent.playerId].currentPlanet = None\n self.changeBackground('GALAXY')\n self.drawWorld()\n cam = self.parent.players[self.parent.playerId].camera\n cam.position = cam.defaultPos\n \n \n def clickMenuModes(self,eve):\n Button_pressed = (eve.widget.gettags(eve.widget.find_withtag('current')))[0]\n if (Button_pressed == \"bouton_chat\"):\n print('do some shit nigga 1')\n self.menuChat(self.gameFrame)\n elif (Button_pressed == \"bouton_trade\"):\n print('do some shit nigga 2')\n self.menuTrade()\n elif (Button_pressed == \"bouton_team\"):\n print('do some shit nigga 3')\n self.menuTeam()\n\n #Assignation des controles\t\n def assignControls(self):\n self.gameArea.focus_set()\n #Bindings des fleches\n self.gameArea.bind (\"\", self.keyPressUP)\n self.gameArea.bind(\"\", self.keyPressDown)\n self.gameArea.bind(\"\", self.keyPressLeft)\n self.gameArea.bind(\"\", self.keyPressRight)\n self.gameArea.bind (\"\", self.keyReleaseUP)\n self.gameArea.bind (\"\", self.keyReleaseDown)\n self.gameArea.bind (\"\", self.keyReleaseLeft)\n self.gameArea.bind (\"\", self.keyReleaseRight)\n #Bindings de shift pour la multiselection\n self.gameArea.bind(\"\", self.shiftPress)\n self.gameArea.bind(\"\", self.shiftRelease)\n #BINDINGS POUR LES SHORTCUTS CLAVIERS\n self.gameArea.bind(\"s\", self.stop)\n self.gameArea.bind(\"S\", self.stop)\n self.gameArea.bind(\"\", self.delete)\n self.gameArea.bind(\"a\",self.attack)\n self.gameArea.bind(\"A\",self.attack)\n self.gameArea.bind(\"c\", self.selectAll)\n self.gameArea.bind(\"\", self.unSelectAll)\n self.gameArea.bind(\"1\", self.checkMotherSip)\n self.gameArea.bind(\"\",self.ctrlPressed)\n self.gameArea.bind(\"\",self.ctrlDepressed)\n #Bindings des boutons de la souris\n self.gameArea.bind(\"\", self.rightclic)\n self.gameArea.bind(\"\", self.rightclic)\n self.minimap.bind(\"\", self.rightclic)\n self.gameArea.bind(\"\", self.leftclic)\n self.minimap.bind(\"\",self.leftclic)\n self.minimap.bind(\"\",self.leftclic)\n self.gameArea.bind(\"\", self.clicDrag)\n self.gameArea.bind(\"\", self.endDrag)\n self.gameArea.bind(\"\", self.posMouse)\n self.menuModes.entryMess.bind(\"\",self.enter)\n self.menuModes.bind(\"\",self.clickMenuModes)\n\n","sub_path":"src/Aghi/View.py","file_name":"View.py","file_ext":"py","file_size_in_byte":39670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"20576701","text":"import cv2 \r\nimport sys\r\n\r\nif not sys.warnoptions:\r\n import warnings\r\n warnings.simplefilter(\"ignore\")\r\nimport keras\r\nfrom keras.models import load_model\r\nimport frame_enhancer as fe\r\nmodel=load_model('val96p.h5')\r\n\r\ncap=cv2.VideoCapture('Fire video 1.mp4')\r\nwhile True:\r\n\tret,frame=cap.read()\r\n\tif not ret:\r\n\t\tbreak;\r\n\tframe1=fe.enhance(frame)\r\n\ta=cv2.resize(frame,(50,50))\r\n\ta=a.reshape(1,50,50,3)\r\n\tp=model.predict(a)\r\n\tcv2.imshow('Original video',frame);\r\n\tcv2.imshow('Enhanced video',frame1);\r\n\ts=p[0]\r\n\tif s[0]>s[1]:\r\n\t\tprint(\"No Fire detected\",end=\" \")\r\n\t\tprint(p);\r\n\telse:\r\n\t\tprint(\"FIRE!!!\",end=\" \")\r\n\t\tprint(p);\r\n\tif cv2.waitKey(1000//24) & 0xFF == ord('q'):\r\n\t\tbreak\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n","sub_path":"Video_test.py","file_name":"Video_test.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"449757182","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n\tpath('directoryreport', views.listpage, name='listpage'),\n\tpath('errorreport', views.errpage, name = 'errpage'),\n\tpath('home', views.homepage, name = 'home'),\n\tpath('', views.hierarch, name = \"hierarch\"),\n]","sub_path":"reportapp/reperrapp/listpage/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"498513957","text":"\"\"\"\nDate: 16.06.2015\nAuthor: Can Mekik\n\nUnit tests datautils.LabelMe module.\n\nNeeds to be run from top-level datautils folder.\n\"\"\"\n\nfrom datautils.processors.LabelMe import LabelMe2Visuo, LabelMe3D2Visuo\nfrom collections import defaultdict\nfrom numpy import array, sqrt, allclose\nfrom copy import deepcopy\nfrom os import remove\nimport unittest\n\n\nclass LabelMe2VisuoPreprocessTestCase(unittest.TestCase):\n\n def setUp(self):\n\n def rm_polygon(entries):\n for entry in entries:\n entries[entry].pop('polygon', None)\n return entries\n\n def add_stuff(x):\n out = {}\n for item in x:\n out[item] = defaultdict(dict, {'added': 'stuff'})\n return out\n\n labelme2visuo = LabelMe2Visuo(rm_polygon, add_stuff)\n labelme2visuo.destination = './test/processors/LabelMe/'\n labelme2visuo.filename = 'out'\n test = './test/processors/LabelMe/test_db/Annotations/test/test.xml'\n with open(test) as f:\n self.preprocessed = labelme2visuo.preprocess(f)\n #Need to copy preprocessed as dicts are mutable.\n self.processed = labelme2visuo.process(\n deepcopy(self.preprocessed))\n labelme2visuo.publish(self.processed)\n\n def tearDown(self):\n\n del self.preprocessed, self.processed\n remove('./test/processors/LabelMe/out.visuo')\n\n def test_preprocess(self):\n \"\"\"Tests preprocess with artificial data.\"\"\"\n\n radius = 0.5*sqrt(2)*512.0\n expected = {0: defaultdict(dict,\n {'name': 'triangle',\n 'polygon': array([[0, 0],\n [0, 1/radius],\n [1/radius, 0]])})}\n for key in self.preprocessed:\n self.assertEqual(self.preprocessed[key]['name'],\n expected[key]['name'])\n self.assertTrue(allclose(self.preprocessed[key]['polygon'],\n expected[key]['polygon']))\n\n def test_process(self):\n \"\"\"Tests process with some simple processes.\"\"\"\n\n expected = {0: defaultdict(dict,\n {'name': 'triangle',\n 'added': 'stuff'})}\n for index in range(len(self.processed)):\n self.assertEqual(self.processed[index]['name'],\n expected[index]['name'])\n self.assertEqual(self.processed[index]['added'],\n expected[index]['added'])\n\n def test_publish(self):\n \"\"\"Test publish with artificial data and simple processes.\"\"\"\n\n expected = 'name = triangle\\nadded = stuff\\n\\n'\n with open('./test/processors/LabelMe/out.visuo') as f:\n lines = ''.join(f.readlines())\n self.assertEqual(lines, expected)\n\n\nclass LabelMe3D2VisuoTestCase(unittest.TestCase):\n\n def setUp(self):\n\n labelme3d2visuo = LabelMe3D2Visuo()\n test = './test/processors/LabelMe/test_db/Annotations/test/test.xml'\n with open(test) as f:\n self.preprocessed = labelme3d2visuo.preprocess(f)\n\n def tearDown(self):\n\n del self.preprocessed\n\n def test_preprocess(self):\n\n expected = {0: defaultdict(dict,\n {'name': 'triangle',\n 'polygon': array([[0., 0., 0.],\n [0., 1., 0.],\n [1., 0., 0.]])})}\n for key in self.preprocessed:\n self.assertEqual(self.preprocessed[key]['name'],\n expected[key]['name'])\n self.assertTrue(allclose(self.preprocessed[key]['polygon'],\n expected[key]['polygon']))","sub_path":"datautils/test/processors/LabelMe/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"591454838","text":"#!/usr/bin/env python\n# coding=utf-8\n'''\nAuthor: wjm\nDate: 2020-10-20 16:40:30\nLastEditTime: 2021-08-22 10:48:55\n@Description: batch_size=16, patch_size=48, L1 loss, lr=1e-4, epoch=500, ADAM, decay=150, n_feats = 128, depth = 12\n'''\nimport os\nimport torch.nn as nn\nimport torch.optim as optim\nfrom model.base_net import *\nfrom torchvision.transforms import *\nimport torch\nimport numpy as np\nfrom PIL import Image\nimport torch.nn.functional as F\n\nclass Net(nn.Module):\n def __init__(self, args):\n super(Net, self).__init__()\n \n self.args = args\n num_channels = self.args['data']['n_colors']\n scale_factor = self.args['data']['upsacle']\n \n n_feats = 128\n self.depth = 12\n kernel_size = 3 \n scale = scale_factor \n self.scale = scale_factor\n # rgb_mean = (0.4488, 0.4371, 0.4040)\n # rgb_std = (1.0, 1.0, 1.0)\n # self.sub_mean = common.MeanShift(args.rgb_range, rgb_mean, rgb_std)\n \n # define head module\n m_head = [ConvBlock(num_channels, n_feats, 3, 1, 1, activation='prelu', bias=True, norm=None),\n ConvBlock(n_feats, n_feats, 3, 1, 1, activation='prelu', bias=True, norm=None)]\n\n # define Self-Exemplar Mining Cell\n self.SEM = RecurrentProjection(n_feats, scale = scale)\n\n # define tail module\n m_tail = [\n nn.Conv2d(\n n_feats*self.depth, num_channels, kernel_size,\n padding=(kernel_size//2)\n )\n ]\n\n # self.add_mean = common.MeanShift(args.rgb_range, rgb_mean, rgb_std, 1)\n\n self.head = nn.Sequential(*m_head)\n self.tail = nn.Sequential(*m_tail)\n\n def forward(self,input):\n # x = self.sub_mean(input)\n x = self.head(input)\n bag = []\n for i in range(self.depth):\n x, h_estimate = self.SEM(x)\n bag.append(h_estimate)\n h_feature = torch.cat(bag,dim=1)\n h_final = self.tail(h_feature)\n # return self.add_mean(h_final)\n return h_final\n \nclass CrossScaleAttention(nn.Module):\n def __init__(self, channel=128, reduction=2, ksize=3, scale=3, stride=1, softmax_scale=10, average=True):\n super(CrossScaleAttention, self).__init__()\n \n self.ksize = 3\n self.stride = 1\n self.softmax_scale = 10\n \n self.scale = scale\n self.average = True\n escape_NaN = torch.FloatTensor([1e-4])\n self.register_buffer('escape_NaN', escape_NaN)\n self.base_filter = channel\n\n self.conv_match_1 = ConvBlock(self.base_filter, self.base_filter // 2, 1, 1, 0, activation='prelu', bias=True, norm=None)\n self.conv_match_2 = ConvBlock(self.base_filter, self.base_filter // 2, 1, 1, 0, activation='prelu', bias=True, norm=None)\n self.conv_assembly = ConvBlock(self.base_filter, self.base_filter, 1, 1, 0, activation='prelu', bias=True, norm=None)\n\n def forward(self, input):\n #get embedding\n embed_w = self.conv_assembly(input)\n match_input = self.conv_match_1(input)\n \n # b*c*h*w\n shape_input = list(embed_w.size()) # b*c*h*w\n input_groups = torch.split(match_input,1,dim=0)\n # kernel size on input for matching \n kernel = self.scale*self.ksize\n \n # raw_w is extracted for reconstruction \n raw_w = extract_image_patches(embed_w, ksizes=[kernel, kernel],\n strides=[self.stride*self.scale,self.stride*self.scale],\n rates=[1, 1],\n padding='same') # [N, C*k*k, L]\n # raw_shape: [N, C, k, k, L]\n raw_w = raw_w.view(shape_input[0], shape_input[1], kernel, kernel, -1)\n raw_w = raw_w.permute(0, 4, 1, 2, 3) # raw_shape: [N, L, C, k, k]\n raw_w_groups = torch.split(raw_w, 1, dim=0)\n \n \n # downscaling X to form Y for cross-scale matching\n ref = F.interpolate(input, scale_factor=1./self.scale, mode='bilinear')\n ref = self.conv_match_2(ref)\n w = extract_image_patches(ref, ksizes=[self.ksize, self.ksize],\n strides=[self.stride, self.stride],\n rates=[1, 1],\n padding='same')\n shape_ref = ref.shape\n # w shape: [N, C, k, k, L]\n w = w.view(shape_ref[0], shape_ref[1], self.ksize, self.ksize, -1)\n w = w.permute(0, 4, 1, 2, 3) # w shape: [N, L, C, k, k]\n w_groups = torch.split(w, 1, dim=0)\n\n\n y = []\n scale = self.softmax_scale \n # 1*1*k*k\n #fuse_weight = self.fuse_weight\n\n for xi, wi, raw_wi in zip(input_groups, w_groups, raw_w_groups):\n # normalize\n wi = wi[0] # [L, C, k, k]\n max_wi = torch.max(torch.sqrt(reduce_sum(torch.pow(wi, 2),\n axis=[1, 2, 3],\n keepdim=True)),\n self.escape_NaN)\n wi_normed = wi/ max_wi\n\n # Compute correlation map\n xi = same_padding(xi, [self.ksize, self.ksize], [1, 1], [1, 1]) # xi: 1*c*H*W\n yi = F.conv2d(xi, wi_normed, stride=1) # [1, L, H, W] L = shape_ref[2]*shape_ref[3]\n\n yi = yi.view(1,shape_ref[2] * shape_ref[3], shape_input[2], shape_input[3]) # (B=1, C=32*32, H=32, W=32)\n # rescale matching score\n yi = F.softmax(yi*scale, dim=1)\n if self.average == False:\n yi = (yi == yi.max(dim=1,keepdim=True)[0]).float()\n \n # deconv for reconsturction\n wi_center = raw_wi[0] \n yi = F.conv_transpose2d(yi, wi_center, stride=self.stride*self.scale, padding=self.scale)\n \n yi =yi/6.\n y.append(yi)\n \n y = torch.cat(y, dim=0)\n return y\n\n#in-scale non-local attention\nclass NonLocalAttention(nn.Module):\n def __init__(self, channel=128, reduction=2, ksize=3, scale=3, stride=1, softmax_scale=10, average=True):\n super(NonLocalAttention, self).__init__()\n self.conv_match_1 = ConvBlock(channel, channel // 2, 1, 1, 0, activation='prelu', bias=True, norm=None)\n self.conv_match_2 = ConvBlock(channel, channel // 2, 1, 1, 0, activation='prelu', bias=True, norm=None)\n self.conv_assembly = ConvBlock(channel, channel, 1, 1, 0, activation='prelu', bias=True, norm=None)\n \n def forward(self, input):\n x_embed_1 = self.conv_match_1(input)\n x_embed_2 = self.conv_match_2(input)\n x_assembly = self.conv_assembly(input)\n\n N,C,H,W = x_embed_1.shape\n x_embed_1 = x_embed_1.permute(0,2,3,1).view((N,H*W,C))\n x_embed_2 = x_embed_2.view(N,C,H*W)\n score = torch.matmul(x_embed_1, x_embed_2)\n score = F.softmax(score, dim=2)\n x_assembly = x_assembly.view(N,-1,H*W).permute(0,2,1)\n x_final = torch.matmul(score, x_assembly)\n return x_final.permute(0,2,1).view(N,-1,H,W)\n \ndef extract_image_patches(images, ksizes, strides, rates, padding='same'):\n \"\"\"\n Extract patches from images and put them in the C output dimension.\n :param padding:\n :param images: [batch, channels, in_rows, in_cols]. A 4-D Tensor with shape\n :param ksizes: [ksize_rows, ksize_cols]. The size of the sliding window for\n each dimension of images\n :param strides: [stride_rows, stride_cols]\n :param rates: [dilation_rows, dilation_cols]\n :return: A Tensor\n \"\"\"\n assert len(images.size()) == 4\n assert padding in ['same', 'valid']\n batch_size, channel, height, width = images.size()\n \n if padding == 'same':\n images = same_padding(images, ksizes, strides, rates)\n elif padding == 'valid':\n pass\n else:\n raise NotImplementedError('Unsupported padding type: {}.\\\n Only \"same\" or \"valid\" are supported.'.format(padding))\n\n unfold = torch.nn.Unfold(kernel_size=ksizes,\n dilation=rates,\n padding=0,\n stride=strides)\n patches = unfold(images)\n return patches # [N, C*k*k, L], L is the total number of such blocks\n\ndef reduce_mean(x, axis=None, keepdim=False):\n if not axis:\n axis = range(len(x.shape))\n for i in sorted(axis, reverse=True):\n x = torch.mean(x, dim=i, keepdim=keepdim)\n return x\n\n\ndef reduce_std(x, axis=None, keepdim=False):\n if not axis:\n axis = range(len(x.shape))\n for i in sorted(axis, reverse=True):\n x = torch.std(x, dim=i, keepdim=keepdim)\n return x\n\n\ndef reduce_sum(x, axis=None, keepdim=False):\n if not axis:\n axis = range(len(x.shape))\n for i in sorted(axis, reverse=True):\n x = torch.sum(x, dim=i, keepdim=keepdim)\n return x\n\ndef same_padding(images, ksizes, strides, rates):\n assert len(images.size()) == 4\n batch_size, channel, rows, cols = images.size()\n out_rows = (rows + strides[0] - 1) // strides[0]\n out_cols = (cols + strides[1] - 1) // strides[1]\n effective_k_row = (ksizes[0] - 1) * rates[0] + 1\n effective_k_col = (ksizes[1] - 1) * rates[1] + 1\n padding_rows = max(0, (out_rows-1)*strides[0]+effective_k_row-rows)\n padding_cols = max(0, (out_cols-1)*strides[1]+effective_k_col-cols)\n # Pad the input\n padding_top = int(padding_rows / 2.)\n padding_left = int(padding_cols / 2.)\n padding_bottom = padding_rows - padding_top\n padding_right = padding_cols - padding_left\n paddings = (padding_left, padding_right, padding_top, padding_bottom)\n images = torch.nn.ZeroPad2d(paddings)(images)\n return images\n\n#projection between attention branches\nclass MultisourceProjection(nn.Module):\n def __init__(self, in_channel,kernel_size = 3,scale=2):\n super(MultisourceProjection, self).__init__()\n deconv_ksize, stride, padding, up_factor = {\n 2: (6,2,2,2),\n 3: (9,3,3,3),\n 4: (6,2,2,2)\n }[scale]\n self.up_attention = CrossScaleAttention(channel=in_channel, scale = up_factor)\n self.down_attention = NonLocalAttention(channel=in_channel)\n self.upsample = nn.Sequential(*[nn.ConvTranspose2d(in_channel,in_channel,deconv_ksize,stride=stride,padding=padding),nn.PReLU()])\n self.encoder = ResnetBlock(in_channel, 3, 1, 1, 1, activation='prelu', norm=None)\n \n def forward(self,x):\n down_map = self.upsample(self.down_attention(x))\n up_map = self.up_attention(x)\n\n err = self.encoder(up_map-down_map)\n final_map = down_map + err\n \n return final_map\n\n#projection with local branch\nclass RecurrentProjection(nn.Module):\n def __init__(self, in_channel,kernel_size = 3, scale = 2):\n super(RecurrentProjection, self).__init__()\n self.scale = scale\n stride_conv_ksize, stride, padding = {\n 2: (6,2,2),\n 3: (9,3,3),\n 4: (6,2,2)\n }[scale]\n\n self.multi_source_projection = MultisourceProjection(in_channel,kernel_size=kernel_size,scale = scale)\n self.down_sample_1 = nn.Sequential(*[nn.Conv2d(in_channel,in_channel,stride_conv_ksize,stride=stride,padding=padding),nn.PReLU()])\n if scale != 4:\n self.down_sample_2 = nn.Sequential(*[nn.Conv2d(in_channel,in_channel,stride_conv_ksize,stride=stride,padding=padding),nn.PReLU()])\n self.error_encode = nn.Sequential(*[nn.ConvTranspose2d(in_channel,in_channel,stride_conv_ksize,stride=stride,padding=padding),nn.PReLU()])\n self.post_conv = ConvBlock(in_channel, in_channel, 3, 1, 1, activation='prelu', bias=True, norm=None)\n if scale == 4:\n self.multi_source_projection_2 = MultisourceProjection(in_channel,kernel_size=kernel_size,scale = scale)\n self.down_sample_3 = nn.Sequential(*[nn.Conv2d(in_channel,in_channel,8,stride=4,padding=2),nn.PReLU()])\n self.down_sample_4 = nn.Sequential(*[nn.Conv2d(in_channel,in_channel,8,stride=4,padding=2),nn.PReLU()])\n self.error_encode_2 = nn.Sequential(*[nn.ConvTranspose2d(in_channel,in_channel,8,stride=4,padding=2),nn.PReLU()])\n\n\n def forward(self, x):\n x_up = self.multi_source_projection(x)\n x_down = self.down_sample_1(x_up)\n error_up = self.error_encode(x-x_down)\n h_estimate = x_up + error_up\n if self.scale == 4:\n x_up_2 = self.multi_source_projection_2(h_estimate)\n x_down_2 = self.down_sample_3(x_up_2)\n error_up_2 = self.error_encode_2(x-x_down_2)\n h_estimate = x_up_2 + error_up_2\n x_final = self.post_conv(self.down_sample_4(h_estimate))\n else:\n x_final = self.post_conv(self.down_sample_2(h_estimate))\n\n return x_final, h_estimate","sub_path":"model/csnla.py","file_name":"csnla.py","file_ext":"py","file_size_in_byte":12854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"245034459","text":"\"\"\"wtf\n\nRevision ID: 85664cd33531\nRevises: e032cee1827b\nCreate Date: 2020-04-22 15:44:45.018749\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '85664cd33531'\ndown_revision = 'e032cee1827b'\nbranch_labels = None\ndepends_on = None\n\n\n# Enum 'type' for PostgreSQL\nenum_name = 'genderderenum'\n# Set temporary enum 'type' for PostgreSQL\ntmp_enum_name = 'tmp_' + enum_name\n\n# Options for Enum\nold_options = ('hombre', 'mujer')\nnew_options = ('nulo', 'hombre', 'mujer')\n\n# Create enum fields\nold_type = sa.Enum(*old_options, name=enum_name)\nnew_type = sa.Enum(*new_options, name=enum_name)\n\ndef upgrade():\n # Rename current enum type to tmp_\n op.execute('ALTER TYPE ' + enum_name + ' RENAME TO ' + tmp_enum_name)\n # Create new enum type in db\n new_type.create(op.get_bind())\n # Update column to use new enum type\n op.execute('ALTER TABLE public.\"user\" ALTER COLUMN gender TYPE ' + enum_name + ' USING gender::text::' + enum_name)\n # Drop old enum type\n op.execute('DROP TYPE ' + tmp_enum_name)\n\n\ndef downgrade():\n # Instantiate db query\n audit = sa.sql.table('user', sa.Column('gender', new_type, nullable=False))\n # Rename enum type to tmp_\n op.execute('ALTER TYPE ' + enum_name + ' RENAME TO ' + tmp_enum_name)\n # Create enum type using old values\n old_type.create(op.get_bind())\n # Set enum type as type for event_type column\n op.execute('ALTER TABLE public.\"user\" ALTER COLUMN gender TYPE ' + enum_name + ' USING gender::text::' + enum_name)\n # Drop temp enum type\n op.execute('DROP TYPE ' + tmp_enum_name)\n\n","sub_path":"migrations/versions/85664cd33531_wtf.py","file_name":"85664cd33531_wtf.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"545657326","text":"# -*- coding: UTF-8 -*- \nimport urllib.request\nimport urllib.parse\nimport geohash\nimport threading\nimport ogr, osr, gdal\nimport os\nimport subprocess\nimport numpy as np\nfrom PIL import Image\n\ndef makeimagegcp(image_height, image_width, corners):\n pixels = image_width - 1\n lines = image_height - 1\n imagegcp = \" \".join( [\"-gcp 0 0 \" + str(corners['leftup'][0]) + \" \" + str(corners['leftup'][1]),\n \"-gcp \" + str(pixels) + \" 0 \" + str(corners['rightup'][0]) + \" \" + str(corners['rightup'][1]), \n \"-gcp 0 \" + str(lines) + \" \" + str(corners['leftdown'][0]) + \" \" + str(corners['leftdown'][1]), \n \"-gcp \" + str(pixels) + \" \" + str(lines) + \" \" + str(corners['rightdown'][0]) + \" \" + str(corners['rightdown'][1])] )\n print(\"make gcp done.\")\n return imagegcp\n\ndef gdal_translate(image, imagegcp, temptiff):\n cmd = \" \".join([\"gdal_translate\", imagegcp, \"-a_srs EPSG:4326\", image, temptiff]) \n os.system(cmd)\n print(\"gdal_translate done.\")\n return\n\ndef gdalwarp(temptiff, outtiff):\n cmd = \" \".join([\"gdalwarp\", \"-tps\", \"-r bilinear\", temptiff, outtiff])\n print(cmd)\n os.system(cmd)\n print(\"gdalwarp done.\")\n return\n\ndef __GetGeometryGeohashes(geom, precision = 5):\n lon_step = geohash.decode_exactly(geohash.encode(40, 120, precision))[3]\n lat_step = geohash.decode_exactly(geohash.encode(40, 120, precision))[2]\n simply_range = lon_step / 2 if lat_step > lon_step else lat_step / 2\n geohashnumbers = []\n geohashnumbersandcoveragepercent = {}\n minx, maxx, miny, maxy = geom.GetEnvelope()\n simplygeom = geom.Buffer(simply_range).Simplify(simply_range)\n min_centery, min_centerx, lat_err, lon_err = geohash.decode_exactly(geohash.encode(miny, minx, precision))\n lonstepnum = int((maxx - minx) / lon_step + 1)\n latstepnum = int((maxy - miny) / lat_step + 1)\n for i in range(lonstepnum + 2):\n for j in range(latstepnum + 2):\n current_centerx = i * lon_step + min_centerx\n current_centery = j * lat_step + min_centery\n geohashnumber = geohash.encode(current_centery, current_centerx, precision)\n if not geohashnumber in geohashnumbers:\n # Create ring\n ring = ogr.Geometry(ogr.wkbLinearRing)\n result = geohash.decode_exactly(geohashnumber)\n ring.AddPoint_2D(result[1] - result[3], result[0] - result[2])\n ring.AddPoint_2D(result[1] - result[3], result[0] + result[2])\n ring.AddPoint_2D(result[1] + result[3], result[0] + result[2])\n ring.AddPoint_2D(result[1] + result[3], result[0] - result[2])\n ring.AddPoint_2D(result[1] - result[3], result[0] - result[2]) \n # Create polygon\n poly = ogr.Geometry(ogr.wkbPolygon)\n poly.AddGeometry(ring) \n if poly.Intersect(simplygeom):\n geohashnumbers.append(geohashnumber)\n geohashnumbersandcoveragepercent[geohashnumber] = poly.Intersection(geom).GetArea() / poly.GetArea()\n print(geohashnumbersandcoveragepercent)\n return geohashnumbersandcoveragepercent\n\ndef __WriteGeoHash2Shapefile(geohashnumber, outshapefile):\n if len(geohashnumber) < 1:\n return\n srs = osr.SpatialReference()\n srs.ImportFromEPSG(4326)\n # Create the output shapefile\n shpDriver = ogr.GetDriverByName(\"ESRI Shapefile\")\n if os.path.exists(outshapefile):\n shpDriver.DeleteDataSource(outshapefile)\n outDataSource = shpDriver.CreateDataSource(outshapefile)\n outLayer = outDataSource.CreateLayer('layername', srs)\n outLayer.CreateField(ogr.FieldDefn(\"geohash\", ogr.OFTString))\n \n outFeature = ogr.Feature(outLayer.GetLayerDefn())\n outFeature.SetField(\"geohash\", geohashnumber)\n # Create ring\n ring = ogr.Geometry(ogr.wkbLinearRing)\n result = geohash.decode_exactly(geohashnumber)\n ring.AddPoint_2D(result[1] - result[3], result[0] - result[2])\n ring.AddPoint_2D(result[1] - result[3], result[0] + result[2])\n ring.AddPoint_2D(result[1] + result[3], result[0] + result[2])\n ring.AddPoint_2D(result[1] + result[3], result[0] - result[2])\n ring.AddPoint_2D(result[1] - result[3], result[0] - result[2]) \n # Create polygon\n poly = ogr.Geometry(ogr.wkbPolygon)\n poly.AddGeometry(ring) \n outFeature.SetGeometry(poly)\n outLayer.CreateFeature(outFeature)\n return\n\ndef __clipbygeohashgird(inputtiff, outfolder, geohashnumber):\n geohashgridshp = os.path.join(outfolder, geohashnumber + '.shp')\n geohashgridtiff = os.path.join(outfolder, '#' + geohashnumber + '.tiff')\n geohashgridimg = os.path.join(outfolder, '#' + geohashnumber + '.jpg')\n geohashgridimgxml = geohashgridimg + \".aux.xml\"\n __WriteGeoHash2Shapefile(geohashnumber, geohashgridshp)\n args = [\"gdalwarp\",\n '--config', 'GDAL_FILENAME_IS_UTF8', 'NO',\n '--config', 'CPL_DEBUG', 'NO',\n \"-r\", \"bilinear\",\n \"-cutline\", geohashgridshp,\n '-crop_to_cutline',\n \"-dstnodata\", \"0\",\n \"-s_srs\", \"EPSG:4326\",\n \"-t_srs\", \"EPSG:4326\",\n #'-ts', '256', '256',\n inputtiff, geohashgridtiff ]\n if not os.path.exists(geohashgridimg):\n newp = subprocess.Popen(args)\n newp.wait()\n args2 = [\"gdal_translate\",\n \"-of\", \"JPEG\",\n #'-ts', '256', '256',\n geohashgridtiff, geohashgridimg ]\n newp2 = subprocess.Popen(args2)\n newp2.wait()\n\n shpDriver = ogr.GetDriverByName(\"ESRI Shapefile\")\n if os.path.exists(geohashgridshp):\n shpDriver.DeleteDataSource(geohashgridshp)\n if os.path.exists(geohashgridtiff):\n os.remove(geohashgridtiff)\n if os.path.exists(geohashgridimgxml):\n os.remove(geohashgridimgxml)\n return geohashgridimg\n\ndef geogridise(corners, inputtiff, outfolder, precision= 1):\n # Create ring\n ring = ogr.Geometry(ogr.wkbLinearRing)\n ring.AddPoint(corners['leftup'][0], corners['leftup'][1])\n ring.AddPoint(corners['rightup'][0], corners['rightup'][1])\n ring.AddPoint(corners['rightdown'][0], corners['rightdown'][1])\n ring.AddPoint(corners['leftdown'][0], corners['leftdown'][1])\n ring.AddPoint(corners['leftup'][0], corners['leftup'][1])\n\n # Create polygon\n geom = ogr.Geometry(ogr.wkbPolygon)\n geom.AddGeometry(ring)\n\n geohashnumbersandcoveragepercent = __GetGeometryGeohashes(geom, precision)\n gridimagesandcoveragepercent = {}\n for geohashnumber, coveragepercent in geohashnumbersandcoveragepercent.items():\n gridimage = __clipbygeohashgird(inputtiff, outfolder, geohashnumber)\n gridimagesandcoveragepercent[gridimage] = coveragepercent\n print(\"geogridise done.\")\n return gridimagesandcoveragepercent\n\nif __name__ == \"__main__\":\n testimage = \"e:/mortal/data/GeoHash_0.jpg\"\n corners = {\n \"leftup\": [-180, 90],\n \"rightup\": [180, 90],\n \"rightdown\": [180, -90],\n \"leftdown\": [-180, -90]\n }\n jpggcp = makeimagegcp(1024, 2048, corners)\n print(jpggcp)\n temptiff = \"e:/mortal/test/temp.tiff\"\n outtiff = \"e:/mortal/test/out.tiff\"\n gdal_translate(testimage, jpggcp, temptiff)\n gdalwarp(temptiff, outtiff)\n outfolder = 'e:/mortal/test' \n geohashgridimages = geogridise(corners, outtiff, outfolder)\n if os.path.exists(temptiff):\n os.remove(temptiff)\n if os.path.exists(outtiff):\n os.remove(outtiff)","sub_path":"experiment003.py","file_name":"experiment003.py","file_ext":"py","file_size_in_byte":7576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"114688470","text":"# Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.\n#\n# For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees\n# of every node never differ by more than 1.\n#\n# Example:\n#\n# Given the sorted linked list: [-10,-3,0,5,9],\n#\n# One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:\n#\n# 0\n# / \\\n# -3 9\n# / /\n# -10 5\n\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n def sortedListToBST(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: TreeNode\n \"\"\"\n if not head:\n return None\n return self.createBST(head, None)\n\n def createBST(self, head, tail):\n sp = head\n fp = head\n if head == tail:\n return None\n\n while fp != tail and fp.next != tail:\n fp = fp.next.next\n sp = sp.next\n\n root = TreeNode(sp.val)\n root.left = self.createBST(head, sp)\n root.right = self.createBST(sp.next, tail)\n\n return root\n\n# Note:\n# We find middle element of linked list which is root using fast pointer slow pointer mechanism. After that we recurse\n# to set left and right node of the root node on each step\n","sub_path":"LeetCode/109-M-ConvertSortedListToBinarySearchTree.py","file_name":"109-M-ConvertSortedListToBinarySearchTree.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"137915643","text":"def datetime_from_timestamp(timestamp):\n\tx = datetime.datetime.fromtimestamp(int(timestamp)).strftime('%Y-%m-%d %H:%M:%S')\n\treturn x\n\n\ndef writeData2csv(filename, pair='BTC_ZEC', period=300, days=230):\n\tfrom poloniex import Poloniex\n\timport time, datetime\n\n\tcsvfile = open(filename, \"a\")\n\tconn = Poloniex()\n\n\tstartTime = time.time() - (86400 * days)\n\t#startTime = time.time() - (period * 50)\n\tendTime = time.time() #End at current time\n\n\tdata = conn.returnChartData(pair, period, startTime, endTime)\n\n\n\tfor tick in data:\n\t\t#print(str(datetime_from_timestamp(tick['date'])) + \",\" + tick['close'], file=csvfile)\n\t\tprint(tick['close'], file=csvfile)\n\treturn\n\n\nwriteData2csv('test.csv')","sub_path":"Experimental/getData.py","file_name":"getData.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"296703152","text":"from AccessControl import getSecurityManager\nfrom AccessControl.Permissions import view as View\nfrom OFS.interfaces import IApplication\nfrom Products.CMFCore.permissions import ManagePortal\nfrom Products.CMFPlone.factory import _DEFAULT_PROFILE\nfrom Products.CMFPlone.factory import addPloneSite\nfrom Products.CMFPlone.interfaces import INonInstallable\nfrom Products.CMFPlone.interfaces import IPloneSiteRoot\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\nfrom Products.GenericSetup import BASE, EXTENSION\nfrom Products.GenericSetup import profile_registry\nfrom Products.GenericSetup.upgrade import normalize_version\nfrom ZPublisher.BaseRequest import DefaultPublishTraverse\nfrom operator import itemgetter\nfrom plone.i18n.locales.interfaces import IContentLanguageAvailability\nfrom plone.keyring.interfaces import IKeyManager\nfrom plone.protect.authenticator import check as checkCSRF\nfrom plone.protect.interfaces import IDisableCSRFProtection\nfrom zope.component import adapts\nfrom zope.component import getAllUtilitiesRegisteredFor\nfrom zope.component import getUtility\nfrom zope.component import queryMultiAdapter\nfrom zope.component import queryUtility\nfrom zope.i18n.interfaces import IUserPreferredLanguages\nfrom zope.i18n.locales import locales, LoadLocaleError\nfrom zope.interface import Interface\nfrom zope.interface import alsoProvides\nfrom zope.publisher.browser import BrowserView\nfrom zope.publisher.interfaces import IRequest\nfrom zope.schema.interfaces import IVocabularyFactory\n\nimport logging\nLOGGER = logging.getLogger('Products.CMFPlone')\n\n\nclass AppTraverser(DefaultPublishTraverse):\n adapts(IApplication, IRequest)\n\n def publishTraverse(self, request, name):\n if name == 'index_html':\n view = queryMultiAdapter(\n (self.context, request), Interface, 'plone-overview')\n if view is not None:\n return view\n return DefaultPublishTraverse.publishTraverse(self, request, name)\n\n\nclass Overview(BrowserView):\n\n def sites(self, root=None):\n if root is None:\n root = self.context\n\n result = []\n secman = getSecurityManager()\n for obj in root.values():\n if obj.meta_type is 'Folder':\n result = result + self.sites(obj)\n elif IPloneSiteRoot.providedBy(obj):\n if secman.checkPermission(View, obj):\n result.append(obj)\n elif obj.getId() in getattr(root, '_mount_points', {}):\n result.extend(self.sites(root=obj))\n return result\n\n def outdated(self, obj):\n mig = obj.get('portal_migration', None)\n if mig is not None:\n return mig.needUpgrading()\n return False\n\n def can_manage(self):\n secman = getSecurityManager()\n return secman.checkPermission(ManagePortal, self.context)\n\n def upgrade_url(self, site, can_manage=None):\n if can_manage is None:\n can_manage = self.can_manage()\n if can_manage:\n return site.absolute_url() + '/@@plone-upgrade'\n else:\n return self.context.absolute_url() + '/@@plone-root-login'\n\n\nclass RootLoginRedirect(BrowserView):\n \"\"\" @@plone-root-login\n\n This view of the Zope root forces authentication via the root\n acl_users and then redirects elsewhere.\n \"\"\"\n\n def __call__(self, came_from=None):\n if came_from is None:\n came_from = self.context.absolute_url()\n self.request.response.redirect(came_from)\n\n\nclass RootLogout(BrowserView):\n \"\"\" @@plone-root-logout \"\"\"\n\n logout = ViewPageTemplateFile('templates/plone-logged-out.pt')\n\n def __call__(self):\n response = self.request.response\n realm = response.realm\n response.setStatus(401)\n response.setHeader('WWW-Authenticate', 'basic realm=\"%s\"' % realm, 1)\n response.setBody(self.logout())\n return\n\n\nclass FrontPage(BrowserView):\n\n index = ViewPageTemplateFile('templates/plone-frontpage.pt')\n\n\nclass AddPloneSite(BrowserView):\n\n # Profiles that are installed by default,\n # but can be removed later.\n default_extension_profiles = (\n 'plone.app.caching:default',\n 'plonetheme.barceloneta:default',\n )\n\n def profiles(self):\n base_profiles = []\n extension_profiles = []\n\n # profiles available for install/uninstall, but hidden at the time\n # the Plone site is created\n not_installable = [\n 'Products.CMFPlacefulWorkflow:CMFPlacefulWorkflow',\n ]\n utils = getAllUtilitiesRegisteredFor(INonInstallable)\n for util in utils:\n not_installable.extend(util.getNonInstallableProfiles())\n\n for info in profile_registry.listProfileInfo():\n if info.get('type') == EXTENSION and \\\n info.get('for') in (IPloneSiteRoot, None):\n profile_id = info.get('id')\n if profile_id not in not_installable:\n if profile_id in self.default_extension_profiles:\n info['selected'] = 'selected'\n extension_profiles.append(info)\n\n def _key(v):\n # Make sure implicitly selected items come first\n selected = v.get('selected') and 'automatic' or 'manual'\n return '%s-%s' % (selected, v.get('title', ''))\n extension_profiles.sort(key=_key)\n\n for info in profile_registry.listProfileInfo():\n if info.get('type') == BASE and \\\n info.get('for') in (IPloneSiteRoot, None):\n base_profiles.append(info)\n\n return dict(\n base=tuple(base_profiles),\n default=_DEFAULT_PROFILE,\n extensions=tuple(extension_profiles),\n )\n\n def browser_language(self):\n language = 'en'\n pl = IUserPreferredLanguages(self.request)\n if pl is not None:\n languages = pl.getPreferredLanguages()\n for httplang in languages:\n parts = (httplang.split('-') + [None, None])[:3]\n if parts[0] == parts[1]:\n # Avoid creating a country code for simple languages codes\n parts = [parts[0], None, None]\n elif parts[0] == 'en':\n # Avoid en-us as a language\n parts = ['en', None, None]\n try:\n locale = locales.getLocale(*parts)\n language = locale.getLocaleID().replace('_', '-').lower()\n break\n except LoadLocaleError:\n # Just try the next combination\n pass\n return language\n\n def languages(self, default='en'):\n util = queryUtility(IContentLanguageAvailability)\n if '-' in default:\n available = util.getLanguages(combined=True)\n else:\n available = util.getLanguages()\n languages = [(code, v.get(u'native', v.get(u'name'))) for\n code, v in available.items()]\n languages.sort(key=itemgetter(1))\n return languages\n\n def timezones(self):\n tz_vocab = getUtility(\n IVocabularyFactory,\n 'plone.app.vocabularies.CommonTimezones'\n )(self.context)\n tz_list = [it.value for it in tz_vocab]\n return tz_list\n\n def __call__(self):\n context = self.context\n form = self.request.form\n submitted = form.get('form.submitted', False)\n if submitted:\n site_id = form.get('site_id', 'Plone')\n\n # CSRF protect. DO NOT use auto CSRF protection for adding a site\n alsoProvides(self.request, IDisableCSRFProtection)\n\n # check if keyring is installed on root, disable CSRF protection\n # if it is because it is not installed until a plone site\n # is created\n if queryUtility(IKeyManager) is None:\n LOGGER.info('CSRF protection disabled on initial site '\n 'creation')\n else:\n # we have a keymanager, check csrf protection manually now\n checkCSRF(self.request)\n site = addPloneSite(\n context, site_id,\n title=form.get('title', ''),\n profile_id=form.get('profile_id', _DEFAULT_PROFILE),\n extension_ids=form.get('extension_ids', ()),\n setup_content=form.get('setup_content', False),\n default_language=form.get('default_language', 'en'),\n portal_timezone=form.get('portal_timezone', 'UTC')\n )\n self.request.response.redirect(site.absolute_url())\n\n return self.index()\n\n\nclass Upgrade(BrowserView):\n\n def upgrades(self):\n ps = getattr(self.context, 'portal_setup')\n return ps.listUpgrades(_DEFAULT_PROFILE)\n\n def versions(self):\n pm = getattr(self.context, 'portal_migration')\n result = {}\n result['instance'] = pm.getInstanceVersion()\n result['fs'] = pm.getFileSystemVersion()\n result['equal'] = result['instance'] == result['fs']\n instance_version = normalize_version(result['instance'])\n fs_version = normalize_version(result['fs'])\n result['instance_gt'] = instance_version > fs_version\n result['instance_lt'] = instance_version < fs_version\n result['corelist'] = pm.coreVersions()\n return result\n\n def __call__(self):\n form = self.request.form\n submitted = form.get('form.submitted', False)\n if submitted:\n # CSRF protect. DO NOT use auto CSRF protection for upgrading sites\n alsoProvides(self.request, IDisableCSRFProtection)\n\n pm = getattr(self.context, 'portal_migration')\n report = pm.upgrade(\n REQUEST=self.request,\n dry_run=form.get('dry_run', False),\n )\n qi = getattr(self.context, 'portal_quickinstaller')\n pac_installed = qi.isProductInstalled('plone.app.contenttypes')\n pac_installable = qi.isProductInstallable('plone.app.contenttypes')\n advertise_dx_migration = pac_installable and not pac_installed\n\n return self.index(\n report=report,\n advertise_dx_migration=advertise_dx_migration\n )\n\n return self.index()\n","sub_path":"buildout-cache/eggs/Products.CMFPlone-5.0b2-py2.7.egg/Products/CMFPlone/browser/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":10387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"333295702","text":"import dash_bootstrap_components as dbc\nimport dash_html_components as html\n\nitems = [\n dbc.DropdownMenuItem(\"First\"),\n dbc.DropdownMenuItem(divider=True),\n dbc.DropdownMenuItem(\"Second\"),\n]\n\ndropdown = html.Div(\n [\n dbc.DropdownMenu(\n label=\"large dropdown\",\n bs_size=\"lg\",\n children=items,\n className=\"mb-3\",\n ),\n dbc.DropdownMenu(\n label=\"normal dropdown\", children=items, className=\"mb-3\"\n ),\n dbc.DropdownMenu(label=\"small dropdown\", bs_size=\"sm\", children=items),\n ]\n)\n","sub_path":"docs/components_page/components/dropdown/size.py","file_name":"size.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"246158833","text":"# -*- coding: utf-8 -*-\n\nimport simple_draw as sd\n\n# Шаг 1: Реализовать падение снежинки через класс. Внести в методы:\n# - создание снежинки с нужными параметрами\n# - отработку изменений координат\n# - отрисовку\n\nsd.resolution = (1200, 800)\n\n\nclass Snowflake:\n down_snowflakes = []\n\n def __init__(self):\n self.length = sd.random_number(5, 15)\n self.x = sd.random_number(0, sd.resolution[0])\n self.y = 700\n self.factor_a = sd.random_number(1, 10) / 10\n self.factor_b = sd.random_number(1, 10) / 10\n self.factor_c = sd.random_number(10, 120)\n\n def clear_previous_picture(self):\n self.draw(color=sd.background_color)\n\n def move(self):\n self.x += sd.random_number(0, 2)\n self.y -= self.length + sd.random_number(-5, 5)\n\n def draw(self, color=sd.COLOR_WHITE):\n start_point = sd.get_point(x=self.x, y=self.y)\n sd.snowflake(center=start_point,\n length=self.length,\n color=color,\n factor_a=self.factor_a,\n factor_b=self.factor_b,\n factor_c=self.factor_c)\n\n def can_fall(self):\n if self.y > 0:\n return True\n\n\n# flake = Snowflake()\n#\n# while True:\n# flake.clear_previous_picture()\n# flake.move()\n# flake.draw()\n# if not flake.can_fall():\n# break\n# sd.sleep(0.1)\n# if sd.user_want_exit():\n# break\n\n# шаг 2: создать снегопад - список объектов Снежинка в отдельном списке, обработку примерно так:\n# flakes = get_flakes(count=N) # создать список снежинок\n# while True:\n# for flake in flakes:\n# flake.clear_previous_picture()\n# flake.move()\n# flake.draw()\n# fallen_flakes = get_fallen_flakes() # подчитать сколько снежинок уже упало\n# if fallen_flakes:\n# append_flakes(count=fallen_flakes) # добавить еще сверху\n# sd.sleep(0.1)\n# if sd.user_want_exit():\n# break\n\ndef get_flakes(count):\n _flakes = {}\n for i in range(count):\n _flakes[i + 1] = Snowflake()\n return _flakes\n\n\nN = 20\nfallen_flakes = []\n\nflakes = get_flakes(count=N)\n\n\ndef get_fallen_flakes(flakes):\n for number, flake_parameter in flakes.items():\n if flake_parameter.y < 0:\n fallen_flakes.append(number)\n return fallen_flakes\n\n\ndef append_flakes(fallen_flakes=fallen_flakes):\n for fallen in fallen_flakes:\n flakes[fallen] = Snowflake()\n fallen_flakes.clear()\n return fallen_flakes\n\n\nwhile True:\n for num, flake in flakes.items():\n flake.clear_previous_picture()\n flake.move()\n flake.draw()\n if not flake.can_fall():\n break\n fallen_flakes = get_fallen_flakes(flakes=flakes) # подчитать сколько снежинок уже упало\n if fallen_flakes:\n append_flakes(fallen_flakes=fallen_flakes) # добавить еще сверху\n sd.sleep(0.1)\n if sd.user_want_exit():\n break\n","sub_path":"lesson_007/01_snowfall.py","file_name":"01_snowfall.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"452901844","text":"from collections import defaultdict\n\n\ndef numMatchingSubseq(S, words):\n # keys of this map are individual chars and the value is a list of words\n map = defaultdict(list)\n count = 0\n\n # build map with initial words\n for word in words:\n map[word[0]].append(word)\n\n # loop through large string\n for char in S:\n # grab all the current words that start with the char\n wordsExpectingChar = map[char]\n\n # we've stored the words so you can empty the list here\n map[char] = []\n\n # go through the words that start with char\n for word in wordsExpectingChar:\n # its a full word\n if len(word) == 1:\n count += 1\n else:\n # slice the word minues the first char and put it in the map\n map[word[1]].append(word[1:])\n\n return count\n\n\nprint(numMatchingSubseq(\"abcde\", [\"a\", \"bb\", \"acd\", \"ace\"])) # 3\n","sub_path":"Hashmaps/NumberOfMatchingSubsequences.py","file_name":"NumberOfMatchingSubsequences.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"409534870","text":"import os.path\nimport logging\nimport sys\nimport inspect\nimport mitmproxy.websocket\n\n# This file is executed by `mitmdump' with `execfile'. Therefore, in\n# order to import submodules under the directory where this file exists,\n# we need some tricks. See http://stackoverflow.com/questions/3718657\n# for the details of the tricks used in the following lines.\nTHIS_FILENAME = inspect.getframeinfo(inspect.currentframe()).filename\nTHIS_DIR_PATH = os.path.dirname(os.path.abspath(THIS_FILENAME))\nsys.path.append(THIS_DIR_PATH)\nimport mahjongsoul_sniffer.logging as logging_\nfrom mahjongsoul_sniffer.redis_mirroring import RedisMirroring\n\n\nlogging_.initialize(\n module_name='game_abstract_crawler', service_name='sniffer')\n\n\n_REDIS_MIRRORING_CONFIG = {\n 'websocket': {\n '.lq.Lobby.loginBeat': {\n 'request_direction': 'outbound',\n 'action': {\n 'command': 'SET',\n 'key': 'login-beat'\n }\n },\n '.lq.Lobby.fetchGameLiveList': {\n 'request_direction': 'outbound',\n 'action': {\n 'command': 'RPUSH',\n 'key': 'game-abstract-list'\n }\n }\n }\n}\n\n\nredis_mirroring = RedisMirroring(\n module_name='game_abstract_crawler', config=_REDIS_MIRRORING_CONFIG)\n\n\ndef websocket_message(flow: mitmproxy.websocket.WebSocketFlow) -> None:\n try:\n redis_mirroring.on_websocket_message(flow)\n except Exception as e:\n logging.exception(\n '`RedisMirroring.on_websocket_message` threw an exception.')\n","sub_path":"game-abstract-crawler/sniffer.py","file_name":"sniffer.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"579690378","text":"# Import some useful libraries\nimport nibabel as nib \nimport numpy as np\nimport os.path\n\n\n# Function to read *.nii files and store as 3D arrays in a list\n# \n# input:\tdata_path: string with path to file folder. usually \"data/set_test/\" or \"data_/set_train/\"\n# \n# return:\tdata: array with some length. The entries of data are numpy arrays with shape (176, 208, 176, 1)\n# \t\t\t-1: if data_path doesn't exist\ndef read_image_data(data_path):\n\t# Assert path\n\tif data_path != \"data/set_train/\" and data_path != \"data/set_test/\":\n\t\tprint(\"Error: Couldn't find path \" + data_path)\n\t\treturn -1\n\n\t# Allocate data\n\tdata = []\n\n\t# Differ between training and test data set\n\tif data_path == \"data/set_train/\":\n\t\t# Load each file in the folder\n\t\tprint(\"Loading files\")\n\t\tfile_number = 1\n\t\twhile os.path.isfile(data_path + \"train_\" + str(file_number) + \".nii\"):\n\t\t\t# Construct file path and load file\n\t\t\tfile = data_path + \"train_\" + str(file_number) + \".nii\"\n\t\t\timg = nib.load(file)\n\t\t\tprint(\" Load file: \" + file)\n\n\t\t\t# Add imgage data to data list\n\t\t\tdata.append(np.squeeze(img.get_data()))\n\n\t\t\t# Increase counter\n\t\t\tfile_number += 1\n\n\telif data_path == \"data/set_test/\":\n\t\t# Load each file in the folder\n\t\tprint(\"Loading files\")\n\t\tfile_number = 1\n\t\twhile os.path.isfile(data_path + \"test_\" + str(file_number) + \".nii\"):\n\t\t\t# Construct file path and load file\n\t\t\tfile = data_path + \"test_\" + str(file_number) + \".nii\"\n\t\t\timg = nib.load(file)\n\t\t\tprint(\" Load file: \" + file)\n\n\t\t\t# Add imgage data to data list\n\t\t\tdata.append(np.squeeze(img.get_data()))\n\n\t\t\t# Increase counter\n\t\t\tfile_number += 1\n\n\t# Return list with data\n\treturn data\n\n\n# Function to read the target values from .csv file\n# \n# input:\tfile_path: string with name of target file\n# \n# output: \tfile_values: numpy array with target values\n# \t\t\t-1: If file is not found\ndef read_file(file_path):\n\t# Assert if the file is in folder\n\tif not os.path.isfile(file_path):\n\t\tprint(\"Error: Couldn't find file \" + file_path)\n\t\treturn -1\n\n\t# Read values from file\n\tfile_values = np.genfromtxt(file_path, delimiter=\",\")\n\n\t# Return the array\n\treturn file_values","sub_path":"project1/src/readData.py","file_name":"readData.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"911448","text":"#!/usr/bin/env python\n\"\"\"\nAn OSX tool to automate downloads from showRSS\n\"\"\"\n\nfrom dateutil import parser\nfrom os import path\nfrom subprocess import call\nfrom xml.dom import minidom\n\ntry:\n from urllib2 import build_opener\nexcept ImportError:\n from urllib.request import build_opener\n\n\nRSS_FEED_URL = \"\"\"FEED_URL_CONFIG\"\"\"\n\nSTAMP_FILE = path.join(path.expanduser(\"~\"), '.showrss')\n\n\ndef read_url(url):\n opener = build_opener()\n opener.addheaders = [('User-agent', 'Mozilla/5.0')]\n return opener.open(url, timeout=10).read()\n\n\ndef parse_feed(feed):\n get = minidom.parseString(feed).getElementsByTagName\n dates = (parser.parse(z.firstChild.nodeValue) for z in get('pubDate'))\n links = (z.firstChild.nodeValue for z in get('link')[1:])\n return zip(dates, links)\n\n\ndef get_timestamp():\n dt = '2000-01-01 00:00:00+00:00'\n if path.exists(STAMP_FILE):\n with open(STAMP_FILE, 'r') as stamp_file:\n dt = stamp_file.read()\n return parser.parse(dt)\n\n\ndef write_timestamp(dt):\n with open(STAMP_FILE, 'w') as stamp_file:\n stamp_file.write(str(dt))\n\n\nif __name__ == '__main__':\n timestamp = get_timestamp()\n all_shows = parse_feed(read_url(RSS_FEED_URL))\n new_shows = [x for x in all_shows if x[0] > timestamp]\n\n for _, link in new_shows:\n call(['open', '-g', link])\n\n if new_shows:\n times, _ = zip(*new_shows)\n write_timestamp(max(times))\n","sub_path":"showrss_helper.py","file_name":"showrss_helper.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"24368080","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2019-2020 CERN.\n#\n# CDS Books is free software; you can redistribute it and/or modify it under\n# the terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"Literature covers.\"\"\"\n\nimport os\nfrom functools import partial\n\nfrom invenio_app_ils.literature.covers_builder import build_placeholder_urls\n\n\ndef is_record_with_cover(record):\n \"\"\"Check if this type of record has cover.\"\"\"\n if '$schema' in record:\n schema = record[\"$schema\"]\n if schema.endswith(\"document-v1.0.0.json\") or schema.endswith(\n \"series-v1.0.0.json\"\n ):\n return True\n return False\n\n\ndef has_already_cover(record):\n \"\"\"Check if record has already valid cover in cover_metadata.\"\"\"\n cover_metadata = record.get(\"cover_metadata\", {})\n return cover_metadata.get(\"ISBN\", False) or cover_metadata.get(\n \"ISSN\", False\n )\n\n\ndef preemptively_set_first_isbn_as_cover(sender, *args, **kwargs):\n \"\"\"Update cover metadata of the record with identifier.\"\"\"\n record = kwargs.get(\"record\", {})\n if not is_record_with_cover(record):\n return\n\n if has_already_cover(record):\n return\n\n identifiers = record.get(\"identifiers\")\n if not identifiers:\n return\n\n record.setdefault(\"cover_metadata\", {})\n schema = record.get(\"$schema\")\n\n if schema.endswith(\"series-v1.0.0.json\"):\n for ident in identifiers:\n if ident[\"scheme\"] == \"ISSN\":\n record[\"cover_metadata\"][\"ISSN\"] = ident[\"value\"]\n return\n\n for ident in identifiers:\n if ident[\"scheme\"] == \"ISBN\":\n record[\"cover_metadata\"][\"ISBN\"] = ident[\"value\"]\n return\n\n\ndef build_syndetic_cover_urls(metadata):\n \"\"\"Decorate literature with cover urls for all sizes.\"\"\"\n client = os.environ.get(\"SYNDETIC_CLIENT\")\n url = \"https://secure.syndetics.com/index.aspx\"\n\n cover_metadata = metadata.get(\"cover_metadata\", {})\n\n issn = cover_metadata.get(\"ISSN\", \"\")\n if issn:\n scheme = \"ISSN\"\n scheme_value = issn\n\n isbn = cover_metadata.get(\"ISBN\", \"\")\n if isbn:\n scheme = \"ISBN\"\n scheme_value = isbn\n\n if issn or isbn:\n _url = \"{url}?client={client}&{sheme}={value}/{size}.gif\"\n partial_url = partial(\n _url.format,\n url=url,\n client=client,\n sheme=scheme,\n value=scheme_value,\n )\n return {\n \"is_placeholder\": False,\n \"small\": partial_url(size=\"SC\"),\n \"medium\": partial_url(size=\"MC\"),\n \"large\": partial_url(size=\"LC\"),\n }\n return build_placeholder_urls()\n","sub_path":"cds_books/literature/covers.py","file_name":"covers.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"543354373","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 ('products', '0002_topic_in_aaq'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='product',\n name='image_alternate',\n field=models.ImageField(help_text='Used everywhere except the home page. Must be 96x96.', max_length=250, null=True, upload_to=b'uploads/products/', blank=True),\n ),\n migrations.AlterField(\n model_name='product',\n name='image',\n field=models.ImageField(help_text='Used on the the home page. Must be 484x244.', max_length=250, null=True, upload_to=b'uploads/products/', blank=True),\n ),\n ]\n","sub_path":"kitsune/products/migrations/0003_auto_20181001_1347.py","file_name":"0003_auto_20181001_1347.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"189996609","text":"from typing import Tuple, Dict, Any, List, Union\n\nPropName = str\nPropValue = str\nPropFuncParamName = str\nPropFuncParamValue = Any\nPropFuncParams = Dict[PropFuncParamName, PropFuncParamValue]\nPropFuncBody = str\nPropFuncResult = Tuple[PropFuncParams, PropFuncBody]\nPropDef = Tuple[PropValue, PropFuncParams, PropFuncBody]\n\nTypeName = str\nTypeDef = Dict[PropName, PropDef]\nTypeDefs = Dict[TypeName, TypeDef]\n\nVarName = str\nVarDefs = Dict[VarName, TypeName]\n\nRule = str\nRules = List[Rule]\n","sub_path":"dectree/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"280269287","text":"###################################################################################################\n# Cerebri AI CONFIDENTIAL\n# Copyright (c) 2017-2020 Cerebri AI Inc., All Rights Reserved.\n#\n# NOTICE: All information contained herein is, and remains the property of Cerebri AI Inc.\n# and its subsidiaries, including Cerebri AI Corporation (together “Cerebri AI”).\n# The intellectual and technical concepts contained herein are proprietary to Cerebri AI\n# and may be covered by U.S., Canadian and Foreign Patents, patents in process, and are\n# protected by trade secret or copyright law.\n# Dissemination of this information or reproduction of this material is strictly\n# forbidden unless prior written permission is obtained from Cerebri AI. Access to the\n# source code contained herein is hereby forbidden to anyone except current Cerebri AI\n# employees or contractors who have executed Confidentiality and Non-disclosure agreements\n# explicitly covering such access.\n#\n# The copyright notice above does not evidence any actual or intended publication or\n# disclosure of this source code, which includes information that is confidential and/or\n# proprietary, and is a trade secret, of Cerebri AI. ANY REPRODUCTION, MODIFICATION,\n# DISTRIBUTION, PUBLIC PERFORMANCE, OR PUBLIC DISPLAY OF OR THROUGH USE OF THIS SOURCE\n# CODE WITHOUT THE EXPRESS WRITTEN CONSENT OF CEREBRI AI IS STRICTLY PROHIBITED, AND IN\n# VIOLATION OF APPLICABLE LAWS AND INTERNATIONAL TREATIES. THE RECEIPT OR POSSESSION OF\n# THIS SOURCE CODE AND/OR RELATED INFORMATION DOES NOT CONVEY OR IMPLY ANY RIGHTS TO\n# REPRODUCE, DISCLOSE OR DISTRIBUTE ITS CONTENTS, OR TO MANUFACTURE, USE, OR SELL\n# ANYTHING THAT IT MAY DESCRIBE, IN WHOLE OR IN PART.\n###################################################################################################\n#!/usr/bin/env python3\n\"\"\"\n@author:\n@version: 1.2\nConfidential and Proprietary (c) Copyright 2015-2019 Cerebri AI Inc. and Cerebri AI Corporation\n\"\"\"\nmodule_name = 'Recursive Feature Elimination'\nversion_name = '1.2'\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_selection import RFE\n\nfrom base_pd.base_feature_selection_pd import PdBaseFeatureSelect as BaseFeatureSelect\n\n\nclass RFE_TE(BaseFeatureSelect):\n \"\"\"\n This is a class for Recursive Feature Elimination (RFE) feature selection.\n\n Attributes:\n rack_order (int): the order of the rack (i.e. 7).\n data_plus_meta (dict): dictionary contining data and meta data.\n racks_map (dict): dictionary of all racks and their orders.\n \"\"\"\n\n def __init__(self, rack_order, data_plus_meta, racks_map):\n \"\"\"\n Constructor for RFE feature selection.\n\n Parameters:\n rack_order (int): the order of the rack (i.e. 7).\n data_plus_meta (dict): dictionary contining data and meta data.\n racks_map (dict): dictionary of all racks and their orders.\n\n Returns:\n ises none\n \"\"\"\n\n super(RFE_TE, self).__init__(module_name, version_name, rack_order, data_plus_meta, racks_map)\n\n\n def fit(self, df, cfg):\n \"\"\"\n Perfomrs RFE feature selection.\n\n Parameters:\n df (dataframe): dataframe.\n cfg (dict): configuration dictionary.\n\n Returns:\n selected_features: list of selected variable names.\n \"\"\"\n\n date_cols = [col for col in df.columns if df[col].dtype == 'datetime64[ns]']\n\n all_features = [x for x in df.columns if x not in cfg['drop_cols']+[cfg['ID_COL'], cfg['CTU_COL']]+date_cols]\n\n for i in all_features:\n if sum(df[i].isnull()) > 0:\n df[i] = df[i].fillna(0)\n\n X = df[all_features]\n y = df[cfg['TE_TARGET_COL']]\n\n if (sum(y)/len(y)) < 0.1:\n class_ratio = (len(y) - sum(y))/sum(y)\n print (\"Class Ratio:\", class_ratio)\n class_weight = dict({1:class_ratio, 0:1.5})\n max_depth = 4\n n_estimators = 100\n else:\n class_weight = None\n max_depth = 4\n n_estimators = 100\n\n param = {\n 'bootstrap':True,\n 'class_weight':class_weight,\n 'criterion':'gini',\n 'max_depth': max_depth, 'max_features':'auto', 'max_leaf_nodes':None,\n 'min_impurity_decrease' :0.0, 'min_impurity_split':None,\n 'min_samples_leaf':2, 'min_samples_split':10,\n 'min_weight_fraction_leaf':0.0, 'n_estimators':n_estimators,\n 'oob_score':False,\n 'random_state':121,\n 'verbose':0,\n 'warm_start':False\n }\n\n\n estimator = RandomForestClassifier(**param)\n\n feat_selector = RFE(estimator, cfg['n_features'], cfg['n_step'])\n feat_selector.fit(X, y)\n\n selected_features = [col for (col, id_bool) in zip(all_features, feat_selector.support_) if id_bool]\n\n return selected_features\n\n\n def transform(self, df, selected_feature):\n \"\"\"\n Removes variables in selected_feature from dataframe.\n\n Parameters:\n df (dataframe): dataframe.\n selected_feature (list): list of variable names to be removed.\n\n Returns:\n filtered_data: dataframe excluding the variables in selected_feature.\n \"\"\"\n\n feature_name = selected_feature\n filtered_data = df[feature_name]\n\n return filtered_data\n","sub_path":"te_code_v_2_7/terminal/ATLAS_1.2/feature_selection/RFE.py","file_name":"RFE.py","file_ext":"py","file_size_in_byte":5553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"446742015","text":"import codecs\nimport cStringIO\nimport logging\nimport os\n\nfrom celery.task.control import inspect\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.core.servers.basehttp import FileWrapper\nfrom django.core.urlresolvers import reverse\nfrom django.db import transaction\nfrom django.db.models import Q\nfrom django.http import HttpResponse\n\nfrom sparky.api import ExceptionMixin\nfrom sparky.api.serializers import (ProjectSerializer, ResourceSerializer, EntrySerializer, TermSerializer,\n HistorySerializer, TodoSerializer)\nfrom sparky.translation import service, sizeof_fmt, checksum\nfrom sparky.translation.exporters import create_exporter\nfrom sparky.translation.models import Locale, Project, Resource, Term, Entry, Todo, Conflict, History\nfrom sparky.translation.service import calculate_project_stats\n\nfrom rest_framework import views, status, viewsets, mixins\nfrom rest_framework.parsers import MultiPartParser, JSONParser\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom time import time\nfrom zipfile import ZipFile, ZIP_DEFLATED\n\nlogger = logging.getLogger(__name__)\n\n\nclass IndexView(ExceptionMixin, views.APIView):\n \"\"\"\n Simple foobar index page\n \"\"\"\n def get(self, request):\n data = {'msg': 'A question that sometimes drives me hazy: am I or are the others crazy?'}\n return Response(data=data)\n\n def post(self, request):\n data = {'msg': 'The important thing is not to stop questioning; curiosity has its own reason for existing.'}\n return Response(data=data)\n\n\nclass ProjectListView(views.APIView):\n permission_classes = (IsAuthenticated, )\n\n def get(self, request):\n projects = Project.objects.all()\n serializer = ProjectSerializer(projects, many=True)\n data = {'projects': serializer.data}\n return Response(data)\n\n\nclass ProjectView(ExceptionMixin, views.APIView):\n \"\"\"\n \"\"\"\n permission_classes = (IsAuthenticated, )\n\n def get(self, request, project_slug):\n project = Project.objects.get(slug=project_slug)\n serializer = ProjectSerializer(project, many=False)\n return Response(serializer.data)\n\n def post(self, request, project_slug):\n try:\n Project.objects.get(slug=project_slug)\n return Response(data={'detail': 'Object already exists'}, status=status.HTTP_400_BAD_REQUEST)\n except Project.DoesNotExist:\n pass\n\n serializer = ProjectSerializer(data=request.POST, many=False)\n\n if serializer.is_valid():\n # Fix for the source_locale, could be fixed in the serializer maybe?\n source_locale_slug = request.DATA.get('source_locale', 'en')\n source_locale = Locale.objects.get(iso=source_locale_slug)\n\n project = serializer.object\n project.slug = project_slug\n project.user = request.user\n project.source_locale = source_locale\n project.save()\n\n # Add the source locale of this resource as a locale to the project\n service.bind_locale(source_locale.iso, project=project)\n\n if 'locales' in request.POST:\n for slug in request.POST.getlist('locales'):\n try:\n project.locales.add(Locale.objects.get(iso=slug))\n except Locale.DoesNotExist:\n pass\n project.save()\n return Response(data=ProjectSerializer(project, many=False).data, status=status.HTTP_201_CREATED)\n\n logger.debug(\"POST: Project errors: %s\", serializer.errors)\n data = {'detail': 'Invalid project data'}\n return Response(data=data, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass ProjectDownloadView(ExceptionMixin, views.APIView):\n permission_classes = (IsAuthenticated, )\n\n def get(self, request, project_slug):\n project = Project.objects.get(slug=project_slug)\n # Create po file here\n response = HttpResponse(content_type='Content-Type: application/zip')\n response['Content-Disposition'] = 'attachment; filename=%s.zip' % project.slug\n\n # Create a zip file, the output will be written to StringIO stream\n fobj = cStringIO.StringIO()\n zipfile = ZipFile(fobj, 'w', ZIP_DEFLATED)\n exporter = create_exporter('po')\n\n # Add all the resources of all languages\n for resource in project.resources:\n for locale in resource.locales.all():\n fdr, pathr = exporter.create_resource(resource, locale)\n zipfile.write(pathr, '%s/%s/%s/LC_MESSAGES/%s.po' % (project.slug, resource.slug.replace('-js', ''),\n locale.iso, resource.get_filename()))\n exporter.cleanup(fdr, pathr)\n\n # Create the source resource file\n fdr, pathr = exporter.create_source_resource(resource)\n zipfile.write(pathr, '%s/%s/en/LC_MESSAGES/%s.po' % (project.slug, resource.slug.replace('-js', ''),\n resource.get_filename()))\n exporter.cleanup(fdr, pathr)\n\n zipfile.close() # Close the zipfile\n response.write(fobj.getvalue()) # write the the output of the StringIO stream\n fobj.close() # close the StringIO Stream\n\n # Okido, the zip is created let's serve a nice download\n return response\n\n\nclass ProjectStatsView(ExceptionMixin, views.APIView):\n permission_classes = (IsAuthenticated,)\n\n def get(self, request, project_slug, locale_slug):\n \"\"\"\n Returns the current progress of translations\n\n :param request:\n :param project_slug:\n :param locale_slug:\n :return:\n \"\"\"\n project = Project.objects.get(slug=project_slug)\n locale = Locale.objects.get(iso=locale_slug)\n return Response(data=calculate_project_stats(project, locale))\n\n\nclass ResourceView(ExceptionMixin, views.APIView):\n \"\"\"\n Fetches the info of a resource or creates/updates one.\n \"\"\"\n permission_classes = (IsAuthenticated,)\n parser_classes = (MultiPartParser, JSONParser, ) # support multipart/form-data and application/json bodies\n\n def get(self, request, project_slug, resource_slug):\n \"\"\"\n Returns a serialized view of a resource and all its available languages\n\n :param request:\n :param project_slug:\n :param resource_slug:\n :return:\n \"\"\"\n project = Project.objects.get(slug=project_slug)\n resource = Resource.objects.get(slug=resource_slug, project__id=project.id)\n data = ResourceSerializer(resource, many=False).data\n return Response(data=data)\n\n def post(self, request, project_slug, resource_slug):\n \"\"\"\n If the resource object doesn't exist yet, it will be created. It will return status 400 if it already exists.\n To upload a file with terms, you'll have to invoke a PUT request.\n\n :param request:\n :param project_slug:\n :param resource_slug:\n :return:\n \"\"\"\n try:\n Resource.objects.get(project__slug=project_slug, slug=resource_slug)\n return Response(data={'detail': 'Object already exists'}, status=status.HTTP_400_BAD_REQUEST)\n except Resource.DoesNotExist:\n pass\n\n project = Project.objects.get(slug=project_slug)\n serializer = ResourceSerializer(data=request.DATA, many=False)\n\n if serializer.is_valid():\n resource = serializer.object\n resource.slug = resource_slug\n resource.project = project\n resource.save()\n\n if 'locales' in request.DATA:\n # for slug in request.DATA.getlist('locales'):\n if hasattr(request.DATA, 'getlist'):\n # Works for posting form data\n arr = request.DATA.getlist('locales')\n else:\n # works for posting json data\n arr = request.DATA['locales']\n\n for slug in arr:\n try:\n resource.locales.add(Locale.objects.get(iso=slug))\n except Locale.DoesNotExist:\n pass\n resource.save()\n return Response(data=ResourceSerializer(resource, many=False).data, status=status.HTTP_201_CREATED)\n\n logger.debug(\"POST: Resource errors: %s\", serializer.errors)\n data = {'detail': 'Invalid resource data', 'errors': serializer.errors}\n return Response(data=data, status=status.HTTP_400_BAD_REQUEST)\n\n @transaction.autocommit\n def put(self, request, project_slug, resource_slug):\n \"\"\"\n The uploaded file with terms will be processed. The actual Resource record won't be updated.\n\n Activate the autocommit to avoid race conditions with celery tasks,\n\n :param request:\n :param project_slug:\n :param resource_slug:\n :return:\n \"\"\"\n logger.debug(\"Uploading terms %s/%s\", project_slug, resource_slug)\n project = Project.objects.get(slug=project_slug)\n resource = Resource.objects.get(project=project, slug=resource_slug)\n\n if 'file' in request.FILES:\n _file = request.FILES['file']\n logger.debug(\"File uploaded %s (%s), filename=%s\", _file.name, sizeof_fmt(_file.size), _file.name)\n content = codecs.EncodedFile(_file, \"utf-8\").read()\n # The user should be authenticated, cfr authentication_classes\n user = request.user\n task_id = service.process_upload_terms(content, resource, user, filename=_file.name)\n logger.debug(\"Uploaded the shizzle %s/%s\", project_slug, resource_slug)\n\n # state = status.HTTP_200_OK\n state = status.HTTP_202_ACCEPTED\n return Response(status=state, headers={'Location': reverse('api.queue.task', kwargs={'task_id': task_id})})\n\n data = {'detail': 'Bummer, no file uploaded'}\n return Response(data=data, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass ResourceTermsView(ExceptionMixin, views.APIView):\n model = Term\n permission_classes = (IsAuthenticated, )\n serializer_class = TermSerializer\n\n def post(self, request, project_slug, resource_slug):\n project = Project.objects.get(slug=project_slug)\n resource = Resource.objects.get(project=project, slug=resource_slug)\n msgid = request.DATA.get('msgid', None)\n msgctxt = request.DATA.get('msgctxt', None)\n\n if msgid:\n term = Term()\n term.resource = resource\n term.msgid = msgid\n term.msgctxt = msgctxt\n term.checksum = checksum(msgid, msgctxt)\n term.user = request.user\n term.save()\n\n for locale in resource.locales.all():\n Entry.objects.get_or_create(term=term, locale=locale, defaults={\n 'user': request.user\n })\n\n data = TermSerializer(term, context={'request': request}, many=False).data\n return Response(status=status.HTTP_201_CREATED, data=data)\n\n return Response(status=status.HTTP_400_BAD_REQUEST, data={'msg': \"'msgid' is required\"})\n\n\nclass ResourceTodosView(ExceptionMixin, views.APIView):\n permission_classes = (IsAuthenticated,)\n\n def get(self, request, project_slug, resource_slug):\n project = Project.objects.get(slug=project_slug)\n resource = Resource.objects.get(slug=resource_slug, project__id=project.id)\n todos = Todo.objects.filter(term__resource=resource).exclude(state=Todo.SOLVED)\n data = TodoSerializer(todos, many=True).data\n return Response(data=data)\n\n\nclass ResourceTranslationView(ExceptionMixin, views.APIView):\n \"\"\"\n The PUT requests allows to upload a translation file. This will create the resource if doesn't exist, otherwise it\n will be updated.\n\n It's better to use the MultiPartParser, better support for web-base clients.\n http://django-rest-framework.org/api-guide/parsers.html#multipartparser\n http://django-rest-framework.org/api-guide/parsers.html#fileuploadparser\n \"\"\"\n permission_classes = (IsAuthenticated,)\n # parser_classes = (FileUploadParser,)\n parser_classes = (MultiPartParser,)\n\n def get(self, request, project_slug, resource_slug, locale_slug=None):\n project = Project.objects.get(slug=project_slug)\n resource = Resource.objects.get(slug=resource_slug, project__id=project.id)\n locale = Locale.objects.get(iso=locale_slug)\n resource.assert_locale(locale)\n resource_serializer = ResourceSerializer(resource, many=False)\n\n data = {\n 'resource': resource_serializer.data,\n 'locale': locale.iso,\n }\n return Response(data=data)\n\n @transaction.autocommit\n def put(self, request, project_slug, resource_slug, locale_slug):\n \"\"\"\n Activate the autocommit to avoid race conditions with celery tasks,\n\n Troubleshooting with utf-8\n http://stackoverflow.com/questions/4729832/proccessing-a-django-uploadedfile-as-utf-8-with-universal-newlines\n \"\"\"\n logger.debug(\"Project: %s \", project_slug)\n logger.debug(\"Resource: %s\", resource_slug)\n logger.debug(\"Locale: %s\", locale_slug)\n\n if 'file' in request.FILES:\n _file = request.FILES['file']\n logger.debug(\"File uploaded %s (%s), filename=%s\", _file.name, sizeof_fmt(_file.size), _file.name)\n content = codecs.EncodedFile(_file, \"utf-8\").read()\n locale = Locale.objects.get(iso=locale_slug)\n\n project = Project.objects.get(slug=project_slug)\n resource = Resource.objects.get(slug=resource_slug, project=project)\n # Add the locale to the project and resource\n service.bind_locale(locale_slug, project=project, resource=resource)\n\n if locale not in resource.locales.all():\n resource.locales.add(locale)\n resource.save()\n\n # The user should be authenticated, cfr authentication_classes\n user = request.user\n\n logging.debug(\"Processing upload: %s, %s, %s\", project_slug, resource_slug, locale_slug)\n task_id = service.process_upload_translation(content, resource, locale, user, filename=_file.name)\n\n # state = status.HTTP_200_OK if not created else status.HTTP_201_CREATED\n state = status.HTTP_202_ACCEPTED\n return Response(status=state, headers={'Location': reverse('api.queue.task', kwargs={'task_id': task_id})})\n\n data = {'error': 'Unprocessable Entity, not a valid po file'}\n return Response(data=data, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass QueueView(ExceptionMixin, views.APIView):\n permission_classes = (IsAuthenticated, )\n\n def get(self, request, task_id=None):\n i = inspect()\n reserved = i.reserved()\n active = i.active()\n\n # Get an overview of the current running and reserved tasks\n if not task_id:\n data = {\n 'reserved': reserved,\n 'active': active\n }\n return Response(data=data, status=status.HTTP_200_OK)\n else:\n def _iter(resultset):\n for k, v in resultset.iteritems():\n for task in v:\n if task_id == task['id']:\n return task\n return None\n\n if active:\n task = _iter(active)\n if not task:\n task = _iter(reserved)\n\n if task:\n data = task\n return Response(data=data, status=status.HTTP_200_OK)\n\n return Response(data={'detail': 'Task not found'}, status=status.HTTP_404_NOT_FOUND)\n\n # raw = ResourceRaw.objects.get(id=task_id)\n # data = {\n # 'project': raw.resource.project.slug,\n # 'resource': raw.resource.slug,\n # 'processed': raw.processed,\n # 'created': raw.created,\n # 'locale': raw.locale.iso,\n # 'user': raw.user.username\n # }\n #\n # if raw.processed:\n # data['stats'] = raw.stats\n #\n # return Response(data=data, status=status.HTTP_200_OK)\n\n\nclass ResourceDownloadView(ExceptionMixin, views.APIView):\n \"\"\"\n Download a resource. With the optional parameter you can change the filename of the downloaded file.\n \"\"\"\n permission_classes = (IsAuthenticated, )\n\n def get(self, request, project_slug, resource_slug, locale_slug):\n \"\"\"\n # text/x-gettext-translation\n \"\"\"\n project = Project.objects.get(slug=project_slug)\n resource = Resource.objects.get(slug=resource_slug, project__id=project.id)\n locale = Locale.objects.get(iso=locale_slug)\n\n exporter_type = request.GET.get('type', 'po')\n exporter = create_exporter(exporter_type)\n\n if locale_slug != 'en':\n resource.assert_locale(locale)\n fd, path = exporter.create_resource(resource, locale)\n else:\n fd, path = exporter.create_source_resource(resource)\n\n # Create po file here\n response = HttpResponse(FileWrapper(file(path, 'r')), content_type=exporter.get_content_type())\n response['Content-Disposition'] = 'attachment; filename=%s' % \\\n exporter.get_filename(resource, request.GET.get('filename', None))\n response['Content-Length'] = os.path.getsize(path)\n #exporter.cleanup(fd, path)\n return response\n\n\nclass TermViewSet(mixins.RetrieveModelMixin,\n mixins.CreateModelMixin,\n mixins.UpdateModelMixin,\n viewsets.GenericViewSet):\n model = Term\n permission_classes = (IsAuthenticated, )\n serializer_class = TermSerializer\n queryset = Term.objects.all()\n\n def update(self, request, *args, **kwargs):\n data = request.DATA\n msgid = data.get('msgid', None)\n self.object = self.get_object_or_none()\n\n check1 = checksum(msgid)\n check2 = checksum(self.object.msgid)\n\n if check1 == check2:\n logger.debug(\"Just update\")\n request.DATA['checksum'] = check2\n\n # If the new value has been changed and equal to the original, delete the existing Todo object attached\n # to it\n try:\n Todo.objects.get(term=self.object).delete()\n except:\n pass\n else:\n logger.debug(\"TODO update\")\n request.DATA['msgid'] = self.object.msgid\n request.DATA['checksum'] = check2\n\n # Create an update for the Term\n todo, created = Todo.objects.get_or_create(term=self.object,\n defaults={'user': request.user})\n todo.term = self.object\n todo.state = Todo.CHANGE_SOURCE\n todo.value = msgid\n todo.user = request.user\n todo.save()\n\n return super(TermViewSet, self).update(request, *args, **kwargs)\n\n\nclass MessageViewSet(mixins.RetrieveModelMixin,\n mixins.UpdateModelMixin,\n viewsets.GenericViewSet):\n model = Entry\n permission_classes = (IsAuthenticated, )\n serializer_class = EntrySerializer\n queryset = Entry.objects.all()\n\n def pre_save(self, obj):\n \"\"\"\n Will set the authentication user as author for an entry before it is created/updated\n \"\"\"\n obj.user = self.request.user\n super(MessageViewSet, self).pre_save(obj)\n\n def update(self, request, *args, **kwargs):\n #/api/terms//\tsparky.api.views.TermViewSet\tterm-detail\n # A workaround, for updating an entry without specifying the term in request.DATA\n _object = self.get_object_or_none()\n if _object is not None and 'term' not in request.DATA:\n from rest_framework.reverse import reverse as reverse_rest\n term_url = reverse_rest('term-detail', args=[_object.term_id], request=request)\n request.DATA['term'] = term_url\n\n return super(MessageViewSet, self).update(request, args, kwargs)\n\n\nclass MessageHistoryView(ExceptionMixin, views.APIView):\n permission_classes = (IsAuthenticated, )\n\n def get(self, request, message_id):\n entry = Entry.objects.get(id=message_id)\n histories = History.objects.filter(entry=entry).order_by('-created')\n data = HistorySerializer(histories, many=True).data\n return Response(data=data, status=status.HTTP_200_OK)\n\n\nclass SolveConflictView(ExceptionMixin, views.APIView):\n permission_classes = (IsAuthenticated, )\n\n def post(self, request, conflict_id):\n which = request.DATA.get('which', None)\n conflict = Conflict.objects.get(id=conflict_id)\n\n if which == 'current':\n conflict.delete()\n return Response(data={'status': 'done'}, status=status.HTTP_200_OK)\n elif which == 'new':\n entry = conflict.entry\n entry.value = conflict.value\n entry.user = request.user\n entry.save()\n conflict.delete()\n return Response(data={'status': 'done'}, status=status.HTTP_200_OK)\n\n return Response(data={'detail': 'The status field \\'which\\' has to be \\'current\\' or \\'new\\''},\n status=status.HTTP_400_BAD_REQUEST)\n\n\nclass TodoView(ExceptionMixin, views.APIView):\n permission_classes = (IsAuthenticated, )\n\n def delete(self, request, todo_id):\n try:\n Todo.objects.get(id=int(todo_id)).delete()\n except Todo.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n def put(self, request, todo_id):\n # Only support to update the done field\n if 'done' in request.DATA:\n todo = Todo.objects.get(pk=todo_id)\n todo.done = request.DATA.get('done', False)\n todo.save()\n return Response(status=status.HTTP_200_OK)\n\n\nclass SearchView(ExceptionMixin, views.APIView):\n \"\"\"\n Possible filters:\n\n - Text search\n - only translated\n - only not translated\n - fuzzy\n - obsolete\n - ignored\n\n Useful links:\n\n - http://www.niwi.be/2012/10/09/postgresql-fulltextsearch-integration-with-django/\n - https://django-orm.readthedocs.org/en/latest/orm-pg-fulltext.html\n\n TODO:\n\n - full text search\n - stats in the result set\n \"\"\"\n permission_classes = (IsAuthenticated, )\n\n RESULTS_PER_PAGE = 50\n\n def get(self, request):\n parse_bool = lambda request, param: request.GET.get(param) in ['True', 'true', 1]\n\n q = request.GET.get('q')\n is_fuzzy = parse_bool(request, 'fuzzy')\n is_ignored = parse_bool(request, 'ignored')\n is_obsolete = parse_bool(request, 'obsolete') # XXX: we don't use this one??\n is_translated = parse_bool(request, 'translated')\n is_not_translated = parse_bool(request, 'not_translated')\n reference = request.GET.get('reference', None)\n results_per_page = request.GET.get('count', self.RESULTS_PER_PAGE)\n\n project = Project.objects.get(slug=request.GET.get('p'))\n locale = Locale.objects.get(iso=request.GET.get('l'))\n\n query = Q(term__resource__project=project) & Q(locale=locale)\n query_category = Q()\n\n if q:\n # Making queries\n # https://docs.djangoproject.com/en/1.6/topics/db/queries/\n #query = query & Q(term__msgid__contains=q) # Case insensitive\n #query = query & Q(term__msgid__istartswith=q) # Case insensitive\n query = query & (Q(term__msgid__icontains=q) | Q(value__icontains=q))\n\n # We have 4 different categories: not translated, translated, fuzzy, ignored. They are all optional.\n if is_not_translated:\n query_category = query_category | (Q(value__isnull=True) | Q(value__exact=''))\n\n if is_translated:\n query_category = query_category | Q(value__isnull=False)\n\n if is_fuzzy:\n query_category = query_category | Q(fuzzy=True)\n\n if is_ignored:\n query_category = query_category | Q(ignore=True)\n else:\n query = query & Q(ignore=False)\n\n # Filter per reference\n if reference:\n query = query & Q(term__references__filename=reference)\n\n # Do the search\n start = time()\n #entries = Entry.objects.filter(query).order_by('term__msgid')\n entries = Entry.objects.filter(query & (query_category)).order_by('-novelty_date', '-created', '-modified')\n count = entries.count()\n paginator = Paginator(entries, results_per_page)\n logger.info(\"Query %2.2f sec\" % (time() - start))\n logger.debug(\"Query: %s \" % entries.query)\n\n # Do the pagination\n try:\n # defaults to the first page if the 'page' param is not specified\n page_param = int(request.GET.get('page', 1))\n page = paginator.page(page_param)\n except (ValueError, PageNotAnInteger, EmptyPage):\n page_param = -1\n page = None\n\n paging = {\n 'page': page_param,\n 'per_page': self.RESULTS_PER_PAGE,\n 'num_pages': paginator.num_pages,\n 'total': count,\n }\n\n if page:\n results = EntrySerializer(page.object_list, many=True, context={'request': request}).data\n full_path = request.build_absolute_uri(None)\\\n .replace('&page=%s' % request.GET.get('page'), '')\n\n if not page.has_previous():\n url_previous = None\n else:\n url_previous = full_path + \"&page=%s\" % page.previous_page_number()\n\n if not page.has_next():\n url_next = None\n else:\n url_next = full_path + \"&page=%s\" % page.next_page_number()\n\n paging.update({\n 'previous': url_previous,\n 'next': url_next,\n 'count': len(page.object_list)\n })\n else:\n results = []\n paging.update({\n 'previous': None,\n 'next': None\n })\n\n data = {\n 'results': results,\n 'paging': paging\n }\n\n return Response(data=data)\n","sub_path":"translations/sparky/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":26767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"252036902","text":"#anime news network rss feed to channel\n#Need to make it start by itself somehow.\nimport feedparser\nfrom datetime import datetime\nimport time\n\ndef parse(now):\n new = []\n allnew = ''\n url = 'http://www.animenewsnetwork.com/news/rss.xml'\n x = feedparser.parse(url)\n for items in x.entries:\n if now < items.published_parsed:\n if items.title == 'Daily Briefs' or 'Ranking' in items.title:\n continue\n else:\n new.append(items.title)\n if new:\n allnew = \" | \".join(new)\n return allnew\n\ndef rss(phenny, input):\n now = time.gmtime()\n time.sleep(3600)\n while True:\n time.sleep(7200)\n out = parse(now)\n if out:\n phenny.say(out)\n now = time.gmtime()\nrss.commands = ['startrss']\nrss.priority = 'medium'\n","sub_path":"modules/annrss.py","file_name":"annrss.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"316262503","text":"# Programa para leer un archivo de texto sin importar si contiene saltos de\r\n# linea o no y cuenta la cantidad de palabras que contiene\r\n\r\n# Librerias\r\nimport argparse\r\nimport time\r\nfrom tabulate import tabulate\r\n\r\n# == Variables ==\r\n# Globales\r\n# args / Objeto con los parámetros que se indican al ejecutar el programa\r\n# args.nombre / Dirección del archivo de texto\r\n# args.time / Indica si se reproduce o no el tiempo de ejecución\r\n# palabra / Lista que va a contener las palabas del archivo que se selecciona\r\n# cantElementos / Lista que contiene el número de repetición de las palabras\r\n# ordenPalabra / Lista que contiene todas las palabras del archivo\r\n# Local de la funcion leerArchivo\r\n# nombre / Dirección del archivo .txt a leer\r\n# tiempo / Booleana para indicar si se indica o no el tiempo de ejecución\r\n# archivo / Objeto donde se almacena la información del archivo\r\n# palabra / Lista temporal donde se almacena una palabra por elemento de lista\r\n# cantPalabras / Permite indicar si ya se analizaron todas las palabras\r\n# del archivo y salir de un ciclo while\r\n# numPalabra / Variable temporal para almacenar el número de repeticiones\r\n# de una palabra en la lista palabra\r\n# t1 / Almacena el tiempo inicial de ejecución\r\n# t2 / Almacena el tiempo final de ejecución\r\n\r\npalabra = list()\r\ncantElementos = list()\r\nordenPalabra = list()\r\n\r\n\r\n# Funcion encargada de leer el archivo contar las palabras en el archivo\r\n# y luego imprimirlas como una tabla con su respectiva frecuencia\r\n# Parámetros de entrada:\r\n# nombre / Dirección del archivo .txt a analizar\r\n# tiempo / Indica si se imprime el tiempo de ejecución\r\ndef leerArchivo(nombre, tiempo):\r\n if(tiempo):\r\n t1 = time.time()\r\n archivo = open(nombre, \"r\")\r\n for lineas in archivo:\r\n palabra.extend(lineas.split())\r\n for i in range(len(palabra)):\r\n palabra[i] = palabra[i].replace(\",\", \"\")\r\n palabra[i] = palabra[i].replace(\".\", \"\")\r\n palabra[i] = palabra[i].lower()\r\n cantPalabras = len(palabra)\r\n while (cantPalabras > 0):\r\n delPalabra = palabra[0]\r\n numPalabra = palabra.count(palabra[0])\r\n cantElementos.append(numPalabra)\r\n ordenPalabra.append(palabra[0])\r\n for i in range(numPalabra):\r\n palabra.remove(delPalabra)\r\n cantPalabras = len(palabra)\r\n print(tabulate({\"Palabra\": ordenPalabra, \"Frecuencia\": cantElementos},\r\n headers=\"keys\"))\r\n if (tiempo):\r\n t2 = time.time() - t1\r\n print(\"Tiempo de ejecucion:\", t2, \"segundos\")\r\n\r\n\r\n# Parte del argparse\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"nombre\", help=\"Nombre del archivo .txt\", type=str)\r\nparser.add_argument(\"-t\", \"--time\", help=\"Indica si se ocupa el tiempo de ejecucion\",\r\n action=\"store_true\")\r\nargs = parser.parse_args()\r\n\r\n# Inicio del programa\r\ndef contTexto():\r\n # Se llama a la función que lee el archivo\r\n leerArchivo(args.nombre, args.time)\r\n\r\nif __name__ == '__main__':\r\n contTexto()\r\n","sub_path":"tarea3/contTexto.py","file_name":"contTexto.py","file_ext":"py","file_size_in_byte":3016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"579333307","text":"import FDBA\nimport numpy\nimport matplotlib.pyplot as plt\nfrom tslearn.datasets import CachedDatasets\nfrom tslearn.preprocessing import TimeSeriesScalerMeanVariance, TimeSeriesResampler\nimport timeit\n'''\npoly1=numpy.polynomial.polynomial.Polynomial((3,4,1,-1,0.5,1,-1/3,1))\npoly2=numpy.polynomial.polynomial.Polynomial((-1,-3,2,0.1,0.7,-2))\nX_train=[]\n\nfor i in range(0,40):\n X_train.append(poly1.linspace(3000,(i,i+20))[1])\n X_train.append(poly2.linspace(3000,(i,i+20))[1])\n\nX_train=numpy.array(X_train)\nprint (X_train.shape)\nseed = 0\nnumpy.random.seed(seed)\n'''\nseed = 0\nnumpy.random.seed(seed)\nX_train, y_train, X_test, y_test = CachedDatasets().load_dataset(\"Trace\")\nX_train = X_train[y_train < 4] # Keep first 3 classes\nnumpy.random.shuffle(X_train)\nX_train = TimeSeriesScalerMeanVariance().fit_transform(X_train[:50]) # Keep only 50 time series\nX_train = TimeSeriesResampler(sz=40).fit_transform(X_train) # Make time series shorter\nX_train=numpy.squeeze(X_train)\n\nsz = X_train.shape[1]\n\ndef main():\n centers = FDBA.FDBA_clustering(X_train,n_iterations=6,k=2,verbose=False)\n y_pred=FDBA.assign(centers,X_train)\n print (y_pred)\n '''for yi in range(2):\n #plt.subplot(3, 3, 4 + yi)\n for xx in X_train[y_pred == yi]:\n plt.plot(xx.ravel(), \"k-\", alpha=.2)\n plt.plot(centers[yi].ravel(), \"r-\")\n plt.xlim(0, sz)\n plt.ylim(-4, 4)\n if yi == 1:\n plt.title(\"FDBA $k$-means\")\n\n #plt.tight_layout()\n plt.show()'''\n\nif __name__== \"__main__\":\n #timeit.timeit(\"main()\",number=3)\n main()\n","sub_path":"dtw_stuff/testing_clustering_python.py","file_name":"testing_clustering_python.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"540683963","text":"import inspect\nimport tkinter\nfrom tkinter.filedialog import askopenfilename\nimport configparser\nimport re\nfrom loguru import logger\n\ndef assign_config(config, section, val):\n \n val = {}\n\n if not section in config.keys():\n logger.error(f\"No {section} in config => {config.keys()}\")\n return None\n for key, value in config[section].items():\n x = re.search(\"^example-\", key)\n if x:\n logger.warning(\"Fill your paths for the programm into \"\n f\"[{section}]\")\n return None\n try:\n val[key] = value\n except ValueError as err:\n logger.error(f\"Wrong value in config for => {key} : {value}\")\n\n return val\n\n\ndef create_config(path: str):\n \"\"\"\n Parameter:\n path [str] - Path to the config file\n\n Create a empty config and ask user for input to fill values\n \"\"\"\n\n config = configparser.ConfigParser()\n config['PATH'] = {\n 'example-path' : 'example/string'\n }\n config['EMAIL'] = {\n 'example-email':'example-string'\n }\n\n\n with open(path, 'w') as configfile:\n config.write(configfile)\n\n logger.info(\"Fill out the Path and Email field of the config\")\n\n return config","sub_path":"Test/packages/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"366664978","text":"import numpy as np\n\n\n\n# This is our initial data; one entry per \"sample\"\n# (in this toy example, a \"sample\" is just a sentence, but\n# it could be an entire document).\nsamples = ['The cat sat on the mat.', 'The dog ate my homework.']\n\n\n\n\n# First, build an index of all tokens in the data.\ntoken_index = {}\nfor sample in samples:\n # We simply tokenize the samples via the `split` method.\n # in real life, we would also strip punctuation and special characters\n # from the samples.\n for word in sample.split():\n if word not in token_index:\n # Assign a unique index to each unique word\n token_index[word] = len(token_index) + 1\n# Note that we don't attribute index 0 to anything.\n\n\n\n\n\n# Next, we vectorize our samples. We will change each token index into a N vector!\n# We will only consider the first `max_length` words in each sample. (Assume we only consider the first max_length in this case)\nmax_length = 10\n\n\n# This is where we store our results:\nresults = np.zeros((len(samples), max_length, max(token_index.values()) + 1)) # why the last one +1 because we do not assign 0 to any token\nresults_shape = results.shape\n\n\n\nfor i, sample in enumerate(samples):\n for j, word in list(enumerate(sample.split()))[:max_length]:\n index = token_index.get(word)\n results[i, j, index] = 1\n\n\n# Therefore, after one-hot encoding, each sample will become : 10 times N matrix.\n\n","sub_path":"deeplearning/oneHotEncoding.py","file_name":"oneHotEncoding.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"303353155","text":"import tensorflow as tf\nimport numpy as np,sys\nfrom sklearn import datasets\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \nnp.random.seed(789)\ntf.set_random_seed(789)\n\nclass TF_PCA():\n \n def __init__(self,data,label):\n \n self.data = data\n self.dtype = tf.float32\n self.target = label \n\n def fit(self):\n self.graph = tf.Graph()\n with self.graph.as_default():\n self.X = tf.placeholder(self.dtype, shape=self.data.shape)\n # Perform SVD\n singular_values, u, v = tf.svd(self.X,full_matrices=False)\n # Create sigma matrix\n sigma = tf.diag(singular_values)\n\n print('singular_values:',singular_values.shape)\n print('u:',u.shape)\n print('v:',v.shape)\n print('sigma:',sigma.shape)\n\n # sigma1 = tf.slice(sigma, [0, 0], [self.data.shape[1], 512])\n # print('-------f1------')\n # print(u.shape)\n # print(sigma1.shape)\n # print('-------f1------')\n # pca = tf.matmul(u,sigma1)\n\n with tf.Session(graph=self.graph) as session:\n self.u, self.v,self.singular_values, self.sigma = session.run([u,v, singular_values, sigma],feed_dict={self.X: self.data})\n\n\n def reduce(self, n_dimensions=None, keep_info=None):\n\n with self.graph.as_default():\n # Cut out the relevant part from sigma\n sigma = tf.slice(self.sigma, [0, 0], [self.data.shape[1], n_dimensions])\n # PCA\n pca = tf.matmul(self.u, sigma)\n with tf.Session(graph=self.graph) as session:\n return session.run(pca, feed_dict={self.X: self.data})\n\n\n\n\n\n\n# x = tf.placeholder(shape=[50,32,32,3],dtype=tf.float32)\n# ss = tf.reshape(x,[50,-1])\n\n# ff = tf_pca(ss)\n\n# with tf.Session() as sess:\n\n# sess.run(tf.global_variables_initializer())\n \n# s = sess.run([ff],feed_dict={x:np.random.randn(50,32,32,3).astype(np.float32)})\n\n# print(s[0].shape)\n\n# sys.exit()\n\niris_dataset = datasets.load_iris()\nrow = 250\n# cal = 16 * 16 * 4\ncal = 8 * 8 * 3\n# cal = 8*8*16 \n# cal = 4*4*64 \ntemp = np.random.randn(row,cal)\n# temp = np.random.randn(cal,row)\n# 8 8 4 = 256\n# 4 4 4 = 64\ntemps = np.ones((row,) )\nprint(iris_dataset.data.shape)\nprint(iris_dataset.target.shape)\nprint(temp.shape)\nprint(temps.shape)\n\n\n\n\nprint('------------------------------------')\n\ntf_pca2 = TF_PCA(temp, temps)\n# tf_pca2 = TF_PCA(iris_dataset.data, iris_dataset.target)\ntf_pca2.fit()\npca = tf_pca2.reduce(n_dimensions=cal//4) # Results in 2 dimensions\n\nprint(temp.shape)\nprint(pca.shape)\n\nsys.exit()\n\nprint('------------------------------------')\nprint('------------------------------------')\nprint('------------------------------------')\nprint('------------------------------------')\nprint('------------------------------------')\nprint('------------------------------------')\ntf_pca = TF_PCA(temp, temps)\ntf_pca.fit()\npca = tf_pca.reduce(n_dimensions=64) # Results in 2 dimensions\nsys.exit()\n\npca = tf_pca.reduce(keep_info=0.5) # Results in 2 dimensions\n\nsys.exit()\n\ncolor_mapping = {0: sns.xkcd_rgb['bright purple'], 1: sns.xkcd_rgb['lime'], 2: sns.xkcd_rgb['ochre']}\ncolors = list(map(lambda x: color_mapping[x], tf_pca.target))\nplt.scatter(pca[:, 0], pca[:, 1], c=colors)\nplt.show()\n\n\n\n\n\n\n# -- end code --","sub_path":"NeuralNetwork/IPCA/z.py","file_name":"z.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"303685969","text":"#Bài 13: Input và Đọc ghi file trong Python\r\n\r\n'''\r\n1, Input.\r\n- Trong Python có cung cấp cho chúng ta hàm input để nhận dữ liệu từ người dùng nhập vào trong commandline. Sử dụng với cú pháp như sau:\r\n input(something)\r\n\r\n'''\r\n\r\nname = input(\"What is your name ?\")\r\nprint(\"Name: \"+name)\r\n\r\n'''\r\n2, Đọc ghi file.\r\n- File là một thứ rất cần thiết trong các dự án, ví dụ như chúng ta cần phải ghi log ra một file để sau này có thể kiểm soát được....\r\n- Và ngôn ngữ lập trình nào cũng hỗ trợ chúng ta làm việc với file.\r\n\r\nMở file.\r\nĐể mở file trong Python chúng ta sử dụng hàm open với cú pháp như sau:\r\n\r\nopen(filePath, mode, buffer)\r\n Trong đó:\r\n\r\n- filePath là đường dẫn đến địa chỉ của file.\r\n- mode là thông số thiết lập chế độ chúng ta mở file được cấp những quyền gì? Mặc địn mode sẽ bằng r (xem các mode ở dưới).\r\n- buffer là thông số đệm cho file mặc định thì nó sẽ là 0.\r\n\r\n Các chế độ mode.\r\n\r\nMode\tChú thích\r\nr\tChế độ chỉ được phép đọc.\r\nrb\tChế độ chỉ được phép đọc nhưng cho định dạn nhị phân.\r\nr+\tChế độ này cho phép đọc và ghi file, con trỏ nó sẽ nằm ở đầu file.\r\nrb+\tChế độ này cho phép đọc và ghi file ở dạng nhị phân, con trỏ sẽ nằm ở đầu file.\r\nw\tChế độ ghi file, nếu như file không tồn tại thì nó sẽ tạo mới file và ghi nội dung, còn nếu như file đã tồn tại nó sẽ ghi đè nội dung lên file cũ.\r\nwb\tTương tự chế độ w nhưng đối với nhị phân.\r\nw+\tMở file trong chế độ đọc và ghi. còn lại như w.\r\nwb+\tGiống chế độ w+ nhưng đối với nhị phân\r\na\tMở file trong chế độ ghi tiếp. Nếu file đã tồn tại rồi thì nó sẽ ghi tiếp nội dung, và nếu như file chưa tồn tại thì nó sẽ tạo một file mới và ghi nội dung vào đó.\r\nab\tTương tự a nhưng đối với nhị phân.\r\na+\tMở file trong chế độ đọc và ghi tiếp nội dung, còn lại cơ chế giống chế độ a.\r\nab+\tTương tự chế độ a+ nhưng đối với nhị phân.\r\n\r\n\r\n\r\n'''\r\n\r\nfopen = open(r\"test.txt\")\r\nfor i in fopen :\r\n print(i)\r\nfopen.close()\r\n\r\n'''\r\nĐóng file.\r\n- Để đóng một file đang được mở, thì chúng ta sử dụng phương thức close() với cú pháp như sau:\r\n\r\nfileObject.close()\r\n- Trong đó, fileObject là đối tượng mà chúng ta thu được khi sử dụng hàm open().\r\n\r\n- Để đảm bảo quy chế đóng mở và giải phóng bộ nhớ cho chương trình thì các bạn phải luôn nhớ đống file khi kết thúc phiên làm việc.\r\n'''\r\n\r\n\r\n'''\r\nĐọc file.\r\n- Sau khi đã mở được file ra rồi, để đọc được file thì chúng ta sử dụng phương thức read với cú pháp:\r\n\r\n fileObject.read(length);\r\n-Trong đó:\r\n\r\n- fileObject là đối tượng mà chúng ta thu được khi sử dụng hàm open().\r\n- length là dung lượng của dữ liệu mà chúng ta muốn đọc, nếu để trống tham số này thì nó sẽ đọc hết file hoặc nếu file lớn quá thì nó sẽ đọc đến khi giới hạn của bộ nhớ cho phép.\r\n'''\r\n\r\nfw = open(\"test.txt\",\"w\")\r\n\r\nfw.write(\"Mai Dac Viet\")\r\n\r\nfw.close()","sub_path":"B13.py","file_name":"B13.py","file_ext":"py","file_size_in_byte":3469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"259547064","text":"from django.utils.translation import ugettext_lazy as _\nfrom rest_framework import serializers\nfrom rest_framework.exceptions import ValidationError\n\n\nclass HasCreateRequired(serializers.ModelSerializer):\n default_error_message = _('{field_name} is required.')\n\n def check_create_required_fields(self, attrs):\n error_list = {}\n for field in self.create_required_fields:\n parsed_field, data = self._get_data(field, attrs)\n if not data:\n error_list[parsed_field] = self.default_error_message.format(field_name=parsed_field)\n if error_list:\n raise ValidationError(error_list)\n\n def _get_data(self, field, attrs):\n keys = field.split('.')\n parsed_field = keys[0]\n parent = attrs.get(keys[0], None)\n if len(keys) == 2:\n parsed_field = keys[1]\n if parent:\n return parsed_field, parent.get(keys[1], None)\n else:\n return parsed_field, None\n return parsed_field, parent\n\n def validate(self, attrs):\n super(HasCreateRequired, self).validate(attrs)\n if not self.instance:\n self.check_create_required_fields(attrs)\n return attrs","sub_path":"mobile_framework/core/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"291395172","text":"from states.BaseState import *\nfrom states.StartState import StartState\nfrom states.PlayState import PlayState\n\nclass StateMachine:\n def __init__(self, states):\n self.states = states\n self.current = None\n self.returnButton = pygame.Rect(0, 10, 80, 30)\n self.returnText = fonts[\"small\"].render(u\"\\u25c4 BACK\", True, GRAY)\n self.returnTextRect = self.returnText.get_rect(center = self.returnButton.center)\n\n\n def current_state(self):\n return str(self.current)\n\n\n def change(self, state, args=None):\n self.current = self.states[state]\n\n if self.current_state() == \"PlayState\":\n self.current.enter(args)\n\n\n def update(self, mouse, click):\n screen.fill(DARK_GRAY)\n\n # return button\n if self.current_state() != \"StartState\":\n if self.returnButton.collidepoint(mouse):\n if click:\n self.current.exit()\n self.change(\"StartState\")\n else:\n pygame.draw.rect(screen, WHITE, self.returnButton, border_top_right_radius = 7, border_bottom_right_radius = 7)\n screen.blit(self.returnText, self.returnTextRect)\n else:\n pygame.draw.rect(screen, DARK_GRAY, self.returnButton)\n screen.blit(self.returnText, self.returnTextRect)\n\n self.current.update(self, mouse, click)\n","sub_path":"StateMachine.py","file_name":"StateMachine.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"244925479","text":"#Linear Logistic Regresssion\r\n\r\n#inporting libraries\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n#importing dataset\r\ndataset = pd.read_csv(\"Social_Network_Ads.csv\")\r\nX = pd.DataFrame(dataset.iloc[:, [2, 3]])\r\nY = pd.DataFrame(dataset.iloc[:, 4])\r\n\r\n#adding X_0\r\n#X.insert(0, \"X_0\", 1) #not required, handled by the package.\r\n\r\n#performing feature scaling\r\nfrom sklearn.preprocessing import StandardScaler\r\nX_sc = StandardScaler()\r\nX = X.astype('float')\r\nX = pd.DataFrame(X_sc.fit_transform(X))\r\n\r\n#splitting the data\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, random_state = 0, test_size = 0.25)\r\n\r\n#fitting the Logistic Regression\r\nfrom sklearn.linear_model import LogisticRegression\r\nregressor = LogisticRegression(random_state = 0, solver = 'liblinear')\r\nregressor.fit(X_train, Y_train.values.ravel())\r\n\r\n#visualising Logistic Regression\r\nY_train = Y_train.values\r\nfor i in range(0, len(Y_train)):\r\n if Y_train[i] == 1:\r\n Y_train[i] = 25\r\n else:\r\n Y_train[i] = -25\r\nclass_no = np.ma.masked_where(Y_train > 0, Y_train) # important class_yes and class_no appear to be interchanged.\r\nclass_yes = np.ma.masked_where(Y_train < 0, Y_train)\r\nplt.scatter(X_train[0], X_train[1], marker = 'o', s = abs(class_yes), color = \"blue\")\r\nplt.scatter(X_train[0], X_train[1], marker = 'x', s = abs(class_no), color = \"red\")\r\nplt.title(\"Social Network training data\")\r\nplt.xlabel(\"Age\")\r\nplt.ylabel(\"Salary\")\r\n\r\n#ploting the regression line\r\ntemp = regressor.coef_ #returns two values, thea_0 and theta_1\r\nslope, intercept = temp[0][0], temp[0][1]\r\nx = np.arange(min(X_train[0]), max(X_train[0]), 0.1)\r\ny = -slope*x + intercept #values for slope and intercept were unfortunately found using trial and error.\r\nplt.plot(x, y)\r\nplt.show()\r\n\r\n#predicting values\r\nY_pred = regressor.predict(X_test)\r\n\r\n#confusion matrix\r\nfrom sklearn.metrics import confusion_matrix\r\nprint(confusion_matrix(Y_test, Y_pred))\r\n\r\n#visualising Logistic Regression on test data\r\nY_test = Y_test.values\r\nfor i in range(0, len(Y_test)):\r\n if Y_test[i] == 1:\r\n Y_test[i] = 25\r\n else:\r\n Y_test[i] = -25\r\nclass_no = np.ma.masked_where(Y_test > 0, Y_test) # important class_yes and class_no appear to be interchanged.\r\nclass_yes = np.ma.masked_where(Y_test < 0, Y_test)\r\nplt.scatter(X_test[0], X_test[1], marker = 'o', s = abs(class_yes), color = \"blue\")\r\nplt.scatter(X_test[0], X_test[1], marker = 'x', s = abs(class_no), color = \"red\")\r\nplt.title(\"Social Network test data\")\r\nplt.xlabel(\"Age\")\r\nplt.ylabel(\"Salary\")\r\n\r\n#ploting the regression line\r\ntemp = regressor.coef_ #returns two values, thea_0 and theta_1\r\nslope, intercept = temp[0][0], temp[0][1]\r\nx = np.arange(min(X_train[0]), max(X_train[0]), 0.1)\r\ny = -slope*x + intercept #values for slope and intercept were unfortunately found using trial and error.\r\nplt.plot(x, y) #line can be varified from the confusion matrix.\r\nplt.show()","sub_path":"1.) Logistic_Regression.py","file_name":"1.) Logistic_Regression.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"146174941","text":"lookingFor = set()\nlookingFor.add(\"shiny gold bag\")\nfullSet = set()\n\ndef recursiveBagSearcher(myList, LFSet):\n newLFSet = set()\n for i in myList:\n for j in LFSet:\n if j in i.split(\"s contain\")[1]:\n newLFSet.add(i.split(\"s contain\")[0])\n helpSet = newLFSet.difference(fullSet)\n if len(helpSet) == 0:\n return\n fullSet.update(helpSet)\n recursiveBagSearcher(myList, helpSet)\n return\n\ndef calculateNoOfBags(myList, bag):\n counter = 0\n for i in myList:\n if bag in i.split(\"s contain\")[0]:\n bagsLine = i.split(\"s contain \")[1]\n bagsLine = bagsLine.replace('.','')\n bagsList = bagsLine.split(\", \")\n if \"no other bag\" in bagsLine:\n return 1\n for j in bagsList:\n number = int(j.split(\" \", 1)[0])\n newBag = j.split(\" \", 1)[1]\n newBag = newBag.replace(\"bags\", \"bag\")\n print(newBag)\n nob = int(calculateNoOfBags(myList, newBag))\n if nob == 1 and number == 1:\n counter += number+nob\n continue\n counter += number*nob\n return counter\n return 1\n\n\nf = open(\"D:\\Documents\\AoCinputs\\inputday7a.txt\")\nlista = list(map(lambda x: x.rstrip(), f.readlines()))\nrecursiveBagSearcher(lista, lookingFor)\nprint(len(fullSet))\nprint(calculateNoOfBags(lista, \"shiny gold bag\"))\n","sub_path":"AoC7PY/AoC7PY.py","file_name":"AoC7PY.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"308363944","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nimport time\n\nR = 1.0\ntestdir = sys.argv[1]\nfilebase= sys.argv[2]\nwallfile = sys.argv[3]\ntsave = int(sys.argv[4])\ntfinal = int(sys.argv[5])\n\nNT = tfinal/tsave;\ntheta = np.linspace(0,2*np.pi,100);\nxcirc = R*np.cos(theta);\nycirc = R*np.sin(theta);\n\nxyw = np.genfromtxt(testdir + wallfile, delimiter=',');\nfig = plt.figure(1);\nplt.ion();\nplt.show()\nfor i in range(NT):\n xy = np.genfromtxt(testdir + filebase + str(tsave*(i+1)) + '.csv', delimiter=',')\n for j in range(xy.shape[0]):\n plt.plot(xcirc + xy[j,0] , ycirc + xy[j,1] , 'b');\n for j in range(xyw.shape[0]):\n plt.plot(xcirc + xyw[j,0] , ycirc + xyw[j,1] , 'r');\n plt.gca().set_aspect('equal');\n plt.xlim([-40,40])\n plt.ylim([-4,76])\n fig.canvas.draw()\n time.sleep(0.01)\n plt.clf()\n\nplt.ioff(); plt.show();\nfig = plt.figure(2);\nfor i in range(NT):\n em = np.genfromtxt(testdir + filebase + \"EM_\" + str(tsave*(i+1)) + '.csv', delimiter=',')\n plt.plot(i,em[0],'bo'); plt.plot(i,em[1],'ro'); plt.plot(i,em[2],'go');\n\nplt.show();\n","sub_path":"CPP/vis/plotSim.py","file_name":"plotSim.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"515777667","text":"#Import Flask\nfrom flask import Flask, jsonify\nimport pandas as pd\nimport numpy as np\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func, inspect, desc\nfrom datetime import datetime as DateTime, timedelta as TimeDelta\nfrom datetime import date\nfrom dateutil.parser import parse\n\n\n\n\n\n\n\n\n\n\n# 2. Create an app\napp = Flask(__name__)\n\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)\n\n# Save references to each table\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n\n# 3. Define Menu\n@app.route(\"/\")\ndef index():\n return (\n f\"Welcome to Mustafa's Weather API Services\"\n\t\tf\"/api/v1.0/precipitation
\" \n\t\tf\"/api/v1.0/stations
\"\n\t\tf\"/api/v1.0/tobs
\"\n f\"/api/v1.0/
\"\n\t)\n\n@app.route(\"/about\")\ndef about():\n name = \"Mustafa\"\n location = \"Houston, TX\"\n\n return f\"Hi, my name is {name}, I live in {location}.\"\n\n@app.route(\"/precipitation/\")\ndef precipitation():\n session = Session(engine)\n results = session.query(Measurement.date, Measurement.prcp).all()\n \n session.close()\n precipy = list(np.ravel(results))\n\n return jsonify(precipy)\n\n@app.route(\"/station/\")\ndef station():\n session = Session(engine)\n results2 =engine.execute('SELECT * FROM station LIMIT 5').fetchall()\n\n session.close()\n stationlist = list(np.ravel(results2))\n\n return jsonify(stationlist)\n\n@app.route(\"/tobs/\")\ndef tobs():\n session = Session(engine)\n results3 =session.query(Station.name, Measurement.station, Station.latitude, Station.longitude, Station.elevation, Measurement.prcp,)\\\n .filter(Measurement.date >= '2016-01-30', Measurement.date <= '2017-01-30')\\\n .order_by((Measurement.prcp).desc())\\\n .all()\n\n session.close()\n thetemps = list(np.ravel(results3))\n\n return jsonify(thetemps)\n\n\n@app.route(\"/api/v1.0/\")\ndef start_trip_temp(start_date):\n\tstart_trip = []\n\n\tresults_min = session.query(func.min(Measurement.tobs)).filter(Measurement.date == start_date).all()\n\tresults_max = session.query(func.max(Measurement.tobs)).filter(Measurement.date == start_date).all()\n\tresults_avg = session.query(func.avg(Measurement.tobs)).filter(Measurement.date == start_date).all()\n\n\tstart_trip = list(np.ravel(results_min,results_max, results_avg))\n\n\treturn jsonify(start_trip)\n\n\n\n@app.route(\"/\")\ndef firstoption(start):\n session = Session(engine)\n option1result = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start).all()\n \n session.close()\n option1temp = list(np.ravel(option1result))\n\n return jsonify(option1temp)\n\n\n@app.route(\"//\")\ndef secondoption(start,end):\n session = Session(engine)\n option2result = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start).filter(Measurement.date <= end).all()\n \n session.close()\n option2temp = list(np.ravel(option2result))\n \n return jsonify(option2temp)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n\n\n\n\n\n\n\n\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"117570145","text":"import sys, json, os\nfrom functions.clearing import clearing\nfrom functions.normalization import normalization\nfrom functions.translation import translation\nfrom functions.statistics import statistics\n\n\nfrom flask import Flask, render_template, redirect, jsonify\nfrom flask import session, request, url_for, flash, make_response\nfrom dicty import *\n\n\n@app.route('/')\n@app.route('/index')\ndef index():\n\n return render_template('index.html')\n\n\n@app.route(\"/download\", methods=['POST', 'GET'])\ndef download():\n\n words = request.values.get('input_text').split(' ')\n\n word_ranking = open('dicty/functions/eng_freq_55000_dict.txt')\n word_ranking = json.load(word_ranking)\n\n dictionary = open('dicty/functions/translation/muller_dict.txt')\n dictionary = json.load(dictionary)\n\n cleared_words = clearing.words_clearing(words)\n pos_tagged_words = normalization.pos_tagging(cleared_words)\n lemmatized_words = normalization.lemmatizing(pos_tagged_words)\n complexity_rank = statistics.complexity_rank(lemmatized_words, word_ranking)\n translated_words = dict(zip(lemmatized_words, translation.translating(lemmatized_words, dictionary)))\n\n ranked_words = statistics.word_ranking(translated_words, word_ranking)\n text_statistics = statistics.text_statistics(ranked_words)\n #return jsonify(a = text_statistics)\n\n text = '' \n text += 'Total number of words in raw text: {0}{1}' .format(str(len(cleared_words)), '\\n' )\n text += 'Total number of unique words: {0}{1}' .format(str(len(lemmatized_words)),'\\n' )\n text += 'Text complexity: {0}{1}{2}' .format(str(complexity_rank), '\\n','\\n')\n text += 'Easy words: {0}{1}' .format(str(text_statistics[0]), '\\n' )\n text += 'Difficult words: {0}{1}' .format(str(text_statistics[1]), '\\n' )\n text += 'Uncategorized words: {0}{1}{2}' .format(str(text_statistics[2]), '\\n','\\n')\n\n \n for i in ranked_words:\n\n text += '{0:10}{1:15}{2:15}' .format(str(i[2]), str(i[0]), str(i[1].encode('utf-8')))\n text += '\\n'\n\n response = make_response(text)\n response.headers['Content-Disposition'] = \"attachment; filename = books.txt\"\n \n return response","sub_path":"dicty/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"451348771","text":"from django.apps import AppConfig\nimport pandas as pd\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report, mean_absolute_error\nfrom sklearn import preprocessing\nimport pickle\n\n\nclass ServerConfig(AppConfig):\n name = 'server'\n\n def calcul_pertinence(self, row):\n temps_estime = int(row.pge_estimated_time)\n temps_passe = int(row.vst_time)\n pourcentage_pertinence = {\n 1: [20, 30, 40],\n 2: [20, 30, 40],\n 3: [20, 30, 40],\n 4: [20, 30, 40]\n }\n\n ecart = (temps_passe - temps_estime) / temps_estime * 100\n if ecart < 0:\n ecart = ecart * -1\n\n for i in range(3):\n if ecart <= pourcentage_pertinence[row.pge_type_id][i]:\n return i + 1\n return 3\n\n def ready(self):\n print(\"Début du ready()\")\n\n #Récupération des fichiers\n df_dataset = pd.read_csv(r\"C:\\Users\\trist\\Desktop\\IA\\dataset.csv\", sep=\";\")\n\n\n #Ajoute de features\n df_dataset['pertinence_computed'] = df_dataset.apply(self.calcul_pertinence, axis=1)\n\n features = [\n 'app_id',\n 'vst_time',\n 'pge_estimated_time',\n 'pge_type_id'\n ]\n # On n'ajoute pas pertinence_computed car c'est ce que l'on cherche à prédire.\n # J'ajoute pas la colonne pge_name car elle n'a pas d'intérêt pour l'apprentissage de l'IA\n\n train_features = df_dataset[features] # X_train\n\n label = ['pertinence_computed'] # ce que l'on cherche à prédire\n\n train_label = df_dataset[label] # y_train\n\n\n #découpage du jeux en 2\n train, test = train_test_split(df_dataset, test_size=0.3, random_state=42)\n\n #RandomForrest\n rf = RandomForestClassifier(n_estimators=100,\n max_depth=8,\n random_state=0)\n\n rf.fit(train_features, train_label) # apprentissage\n\n\n #sauvegarde\n filename = 'finalized_model.sav'\n pickle.dump(rf, open(filename, 'wb'))\n\n","sub_path":"REST_IA_Server/server/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"445718196","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nThis program implements Historical Value at Risk calculation for a \r\nportfolio of tickers with given weights. To simulate returns, it draws \r\n(with replacement) from historical returns for each ticker. \r\nChange tickers, weights, time for lookback at the top.\r\n\r\nCreated on Mon Feb 3 11:03:15 2020\r\n\r\n@author: mroll\r\n\"\"\"\r\n# import some packages and use some shorthand (data, plt, pd)\r\nfrom pandas_datareader import data \r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt \r\nimport numpy as np\r\nimport statistics as stats # need this to take standard deviations\r\nfrom random import choice # choice will select an item from list at random\r\n\r\ndef MR_get(tickers,s,e):\r\n stock_data = data.DataReader(tickers, data_source='yahoo', start = s, \r\n end = e)['Adj Close']\r\n \r\n return stock_data\r\n\r\n# Initialize all the stuff you might want to change later\r\ntickers = ['F', 'AAPL', 'GOOG'] # stock tickers go here\r\n# Need some weights for where we have our money\r\nweights = pd.Series(index = tickers, dtype = float)\r\nweights[tickers]=0.33333333\r\nstart_date = '2018-1-27' # start day for lookback\r\nend_date = '2020-1-27' # end day for lookback\r\n\r\n# Initialize some Monte Carlo paramters\r\nmonte_carlo_runs = 1000\r\ndays_to_simulate = 5\r\nloss_cutoff = 0.99 # count any losses larger than 5% (or -5%)\r\n\r\n# Call that simple function we wrote above\r\nwhat_we_got = MR_get(tickers, start_date, end_date)\r\n# Compute returns from those Adjusted Closes\r\nreturns = what_we_got[tickers].pct_change()\r\n # This is basically what bt.get returned, just the returns\r\n# Remove the NA from returns; we always get 1 fewer returns than data\r\nreturns = returns.dropna() # pretty easy command\r\n\r\n# Calculate mu and sigma\r\nmu = returns.mean() # mu was very easy using .mean method\r\n# sigma was harder, as I couldn't do it in one line\r\n# the statistics package didn't know what to do without the loop\r\n# So I copied the mu data structure and filled it in a loop\r\nsigma=mu.copy() # copy the mu series (a pandas datatype)\r\n# Loop over tickers and fill sigma up with the calculated standard deviation\r\nfor i in tickers: # python loops over tickers no problem\r\n sigma[i]=stats.stdev(returns[i]) # fill up sigma with stdev's\r\n# There is probably a cleaner way to do that \r\n'''sigma = np.std()\r\nprint(sigma)'''\r\n\r\n# Now we can start the Monte Carlo VaR loop\r\n\r\ncompound_returns = sigma.copy()\r\ntotal_simulations = 0\r\nbad_simulations = 0\r\nfor run_counter in range(0,monte_carlo_runs): # Loop over runs \r\n for i in tickers: # loop over tickers, below is done once per ticker\r\n # Loop over simulated days:\r\n compounded_temp = 1\r\n for simulated_day_counter in range(0,days_to_simulate): # loop over days\r\n simulated_return = choice(returns[i])\r\n compounded_temp = compounded_temp * (simulated_return + 1) \r\n compound_returns[i]=compounded_temp # store compounded returns\r\n # Now see if those returns are bad by combining with weights\r\n portfolio_return = compound_returns.dot(weights) # dot product\r\n if(portfolio_return 180.: h_vel = -h_vel\n del tmp_elev\n\n # if not isfile(image_name):\n print(image_name)\n\n rhi_plot(elev, rng_m, -h_vel, az, time, vmax=10, vmin=-10, xlim=(-500, 2000), ylim=(0, 1500),\n terrain_file=args.terrain, lat_0=lon, lon_0=lat)\n plt.savefig(image_name)\n plt.close()\n\n nc.close()\n","sub_path":"rhi_DLR_plot.py","file_name":"rhi_DLR_plot.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"132096249","text":"'''\nCreated on Mar 28, 2019\n@title: pure MCTS\n@tudo: Monte-Carlo Tree Search without machine learning\n@author: martha\n'''\nimport psutil\nimport os\nfrom math import sqrt, log\n# import numpy as np\n# from random import choice\nfrom play.play_rules import findNeighbor, possibleBlockLocation\nfrom play.board import Board\nfrom MCTS.AStar import eveluation_func\n\nclass TreeNode():\n \"\"\"\n BASIC class TreeNode\n initialization :\n instance: turn whose turn for this step\n parent: parent node for this node\n action: this node's action\n state: temp state related on this node\n \"\"\"\n def __init__(self, turn, parent, action, state):\n self._turn = turn\n self._action = action\n self._parent_node = parent\n self._child_action = [] # a map from action to TreeNode\n self._child_node = []\n self._wins = 0\n self._visits = 0\n self._state = state\n self._reset_piece_location = []\n\n def possible_moves(self):\n \"\"\"\n method: possible moves\n possible moves for this player\n continue with piece list with length of 2\n and block list with length of 3\n \"\"\"\n location = self._state._player[self._turn][:2]\n enemy_location = self._state._player[1-self._turn][:2]\n state = self._state\n piece_list = findNeighbor(location, state.board)\n block_list = possibleBlockLocation(enemy_location,\n state.board,\n state.block_list)\n self.move_list = piece_list + block_list\n# self.move_list = block_list\n\n def UCT_select_child(self):\n \"\"\" Use the UCB1 formula to select a child node.\n Often a constant UCTK is applied so we have\n lambda c: c.wins/c.visits + UCTK * sqrt(2*log(self.visits)/c.visits\n to vary the amount of\n exploration versus exploitation.\n \"\"\"\n max_value = -0x3f3f3f\n for temp_node in self._child_node:\n value = temp_node._wins/temp_node._visits \\\n + sqrt(2*log(self._visits)/temp_node._visits)\n if value > max_value:\n max_value = value\n action = temp_node._action\n select_node = temp_node\n self._state.get_move(self._turn, action)\n select_node._turn = 1-self._turn\n select_node._parent_node = self\n select_node._action = action\n return select_node\n\n def expend_child(self):\n \"\"\"\n if this node is leaf node than it should be expended:\n expend with possible_action within possible_moves list and not searched yet\n \"\"\"\n for possible_action in reversed(self.move_list):\n if possible_action not in self._child_action:\n expend_state = self._state\n if len(possible_action) == 3 and self._state._player[self._turn][2] == 0:\n self.move_list.remove(possible_action)\n continue\n expend_state.get_move(self._turn, possible_action)\n expend_node = TreeNode(1-self._turn,\n self, possible_action,\n expend_state)\n self._child_action.append(possible_action)\n self._child_node.append(expend_node)\n return expend_node\n# break\n\n def simulation_(self):\n \"\"\"\n simulation:\n board judge with enemy's step minus my step\n if it's enemy's turn than return -point\n \"\"\"\n point = eveluation_func(self._state)\n# return point\n if self._turn:\n return point\n else:\n return -point\n\n def update(self, value):\n \"\"\"\n update value to all parent's value \n \"\"\"\n if self._parent_node is not None:\n self._parent_node.update(value)\n self._visits += 1\n self._wins += value\n\n def reset_board(self, turn, reset_location, action):\n \"\"\"\n after simulation reset board as board before simulation\n \"\"\"\n if len(action) == 2:\n self._state.move_piece(turn, reset_location)\n else:\n self._state.remove_blocks(turn, action)\n\n def is_leaf(self):\n \"\"\"\n if this node is leaf node return 1 else return 0\n \"\"\"\n return self._child_action == []\n\n def is_root(self):\n \"\"\"\n if this node is root node return 1 else return 0\n \"\"\"\n return self._parent_node is None\n\n def is_full_expended(self):\n \"\"\"\n if this node is full expended(all possible moves have been calculated)\n return 1 else return 0)\n \"\"\"\n if len(self._child_action) == len(self.move_list):\n return 1\n else:\n return 0\n\n def remove_illegal_child(self, child_node):\n self._child_action.remove(child_node._action)\n self._child_node.remove(child_node)\n self.move_list.remove(child_node._action)\n\ndef my_MCTS_fun():\n \"\"\"\n function in\n \"\"\"\n testBoard = Board() # initialization board\n node = TreeNode(0, None, [6, 3], testBoard) # root node\n node.possible_moves() # find all possible moves of root node\n node._reset_piece_location = node._state._player[node._turn][:2]\n # save note node's origin location\n i = 0 # set timeout!\n while(i < 500):\n while node.is_full_expended(): \n # if all possible moves has been calculated\n # select node begin with root node\n i = i + 1\n# if i == 435:\n# print(\"break point\")\n while not node.is_root():\n action = node._action\n node = node._parent_node # located to root node\n node.reset_board(node._turn, node._reset_piece_location,\n action) # reset noard\n while not node.is_leaf(): # select child node until leaf node\n action = node._state._player[1-node._turn][:2]\n node = node.UCT_select_child()\n node._reset_piece_location = action\n node.possible_moves() # search possible moves for leaf node\n child_node = node.expend_child() # expended child\n child_node._reset_piece_location = node._reset_piece_location\n value = child_node.simulation_() # calculate board judge point\n if value == 1000 or value == -1000: # not root available illegal movement\n# print(\"need remove child node\")\n node.remove_illegal_child(child_node)\n child_node.reset_board(1-child_node._turn, child_node._reset_piece_location,\n child_node._action) # reset noard\n continue\n child_node.update(value) # update value\n child_node.reset_board(1-child_node._turn, child_node._reset_piece_location,\n child_node._action) # reset noard\n while not node.is_root():\n node = node._parent_node # located to root node\n node = node.UCT_select_child()\n print(node._action)\n\n\"\"\"\ntest Function in\n\"\"\"\nif __name__ == '__main__':\n my_MCTS_fun()\n info = psutil.virtual_memory()\n print('内存使用:', psutil.Process(os.getpid()).memory_info().rss)\n print('内存占比:',info.percent)","sub_path":"src/MCTS/pure_MCTS.py","file_name":"pure_MCTS.py","file_ext":"py","file_size_in_byte":7424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"330842091","text":"import os\nimport datetime\nimport requests\nimport json\nfrom flask import render_template, flash, redirect, request, url_for, jsonify\nfrom app import app, db, api\nfrom app.models import User, Staff, Pos, ValletTransaction, ValletProduct\nfrom config import Config\n# from app.addons import addon_purchase\nfrom app.farer import authorizestaff, authorize\nfrom werkzeug.utils import secure_filename\nfrom werkzeug.urls import url_parse\nfrom flask_restplus import Resource, Api\nfrom sqlalchemy.sql import func\nfrom sqlalchemy import or_\n\nvallet = api.namespace('vallet', description=\"Vallet service\")\n\ndef valletbalance(vid):\n topup = db.session.execute(\"select sum(amt) from vallet_transaction where vid=\"+str(vid)+\" and typ=1\").scalar()\n # topup = ValletTransaction.query.with_entities(func.sum(ValletTransaction.amt)).filter(ValletTransaction.vid==vid).filter(ValletTransaction.typ==1)\n spent = db.session.execute(\"select sum(amt) from vallet_transaction where vid=\"+str(vid)+\" and typ=2\").scalar()\n print(topup, spent)\n # spent = ValletTransaction.query.with_entities(func.sum(ValletTransaction.amt)).filter(ValletTransaction.vid==vid).filter(ValletTransaction.typ==2)\n if topup == None:\n topup = 0\n if spent == None:\n spent = 0\n balance = topup - spent\n return balance\n\n@vallet.route('/transaction/recharge')\nclass VTransaction(Resource):\n @authorize(request)\n def get(u, self):\n vt = ValletTransaction.query.filter_by(vid=u.vid).all()\n return jsonify(vt)\n\n @authorizestaff(request, \"pay\", 3)\n @api.doc(params={\n 'vid':'Vidyut ID of the staff',\n 'pos':'Point of sale ID',\n 'amt':'Transaction Amount (when pos < 100)'\n })\n def post(u, self):\n data = request.get_json()\n if data.get('amt') is None or data.get('vid') is None or data.get('pos') is None:\n responseObject = {\n 'status':'fail',\n 'message':'Inadequate data'\n }\n return jsonify(responseObject)\n try:\n vid = data.get('vid')\n truser = User.query.filter_by(vid=vid).first()\n if truser is None:\n responseObject = {\n 'status':'fail',\n 'message':'Invalid User'\n }\n return jsonify(responseObject)\n except Exception as e:\n print(e)\n responseObject = {\n 'status':'fail',\n 'message':'Error: '+str(e)\n }\n return jsonify(responseObject)\n try:\n pos = Pos.query.filter_by(posid=data.get('pos')).first()\n if pos is None:\n responseObject = {\n 'status':'fail',\n 'message':'Invalid point of sale'\n }\n return jsonify(responseObject)\n except Exception as e:\n print(e)\n try:\n typ = 2\n amt = data.get('amt')\n truser.balance = truser.balance + amt\n typ = 1\n vt = ValletTransaction(vid=data.get('vid'),\n typ=typ,\n pos=data.get('pos'),\n notes=data.get('notes'),\n amt=data.get('amt'),\n by=u.vid\n )\n db.session.add(vt)\n db.session.commit()\n except Exception as e:\n responseObject = {\n 'status':'fail',\n 'message':'No balance or database error. Error: '+str(e)\n }\n try:\n # mail the user and send message on the transaction\n payload = {\n # 'ip':\n 'key':'vidyuth1908030559',\n 'num':truser.phno,\n 'message':'Vallet Transaction of Rs. '+str(amt)+' at '+str(pos.title)+'.'\n }\n r = requests.get('http://sms.amrita.ac.in/', data=payload)\n # Uncomment only when needed\n except Exception as e:\n responseObject = {\n 'status':'success',\n 'message':'Transaction succesful with errors (message not sent). Please inform user the transaction is successful. Error: '+str(e)\n }\n return jsonify(responseObject)\n responseObject = {\n 'status':'success',\n 'tid':vt.tid\n }\n return jsonify(responseObject)\n\n@vallet.route('/transaction')\nclass TransactionManagement(Resource):\n @authorizestaff(request, \"pay\", 3)\n @api.doc(params={\n 'vid':'Vidyut ID of the staff',\n 'pos':'Point of sale ID (>=100)',\n 'products':'Products (ID) + count array. eg: {{1, 2}, {2, 1}, {3, 4}}'\n })\n def post(u, self):\n data = request.get_json()\n if data.get('vid') is None or data.get('pos') is None:\n responseObject = {\n 'status':'fail',\n 'message':'Inadequate data'\n }\n return jsonify(responseObject)\n try:\n vid = data.get('vid')\n truser = User.query.filter_by(vid=vid).first()\n if truser is None:\n responseObject = {\n 'status':'fail',\n 'message':'Invalid User'\n }\n return jsonify(responseObject)\n except Exception as e:\n print(e)\n responseObject = {\n 'status':'fail',\n 'message':'Error: '+str(e)\n }\n return jsonify(responseObject)\n try:\n pos = Pos.query.filter_by(posid=data.get('pos')).first()\n if pos is None:\n responseObject = {\n 'status':'fail',\n 'message':'Invalid point of sale'\n }\n return jsonify(responseObject)\n except Exception as e:\n print(e)\n try:\n typ = 2\n amt = data.get('amt')\n products \n vt = ValletTransaction(vid=data.get('vid'),\n typ=typ,\n pos=data.get('pos'),\n notes=data.get('notes'),\n amt=data.get('amt'),\n by=u.vid\n )\n db.session.add(vt)\n db.session.commit()\n except Exception as e:\n responseObject = {\n 'status':'fail',\n 'message':'No balance or database error. Error: '+str(e)\n }\n try:\n # mail the user and send message on the transaction\n payload = {\n # 'ip':\n 'key':'vidyuth1908030559',\n 'num':truser.phno,\n 'message':'Vallet Transaction of Rs. '+str(amt)+' at '+str(pos.title)+'.'\n }\n r = requests.get('http://sms.amrita.ac.in/', data=payload)\n # Uncomment only when needed\n except Exception as e:\n responseObject = {\n 'status':'success',\n 'message':'Transaction succesful with errors (message not sent). Please inform user the transaction is successful. Error: '+str(e)\n }\n return jsonify(responseObject)\n responseObject = {\n 'status':'success',\n 'transaction ID':vt.tid\n }\n return jsonify(responseObject)\n\n@vallet.route('/deliver/pos/')\nclass VDeliver(Resource):\n @authorizestaff(request)\n # Sends all undelivered transactions\n def get(u, self, id):\n if pos < 100:\n responseObject = {\n 'status':'fail',\n 'message':'No deliveries for recharge station'\n }\n return jsonify(responseObject)\n und = ValletTransaction.query.filter_by(pos=id, delivered=False).all()\n resp = []\n for i in und:\n resp.append({\n 'tid':i.tid,\n 'vid':i.vid,\n 'notes':i.notes,\n 'amt':i.amt,\n 'by':i.by\n })\n responseObject = {\n 'status':'success',\n 'data':jsonify(resp)\n }\n return jsonify(responseObject)\n\n@vallet.route('/products/')\nclass PosProducts(Resource):\n def get(self, id):\n p = ValletProduct.query.filter_by(pod=id).all()\n pr = []\n for i in p:\n pr.append({\n 'prodid':i.prodid,\n 'title':i.title,\n 'desc':i.desc,\n 'amount':i.amount\n })\n responseObject = {\n 'status':'success',\n 'response':jsonify(pr)\n }\n return jsonify(responseObject)\n\n @authorizestaff(request, \"pay\", 4)\n def post(u, self, id):\n try:\n data = request.get_json()\n product = ValletProduct(pos=id,\n title=data.get('title'),\n desc=data.get('desc'),\n amount=data.get('amount'),\n by=u.vid\n )\n db.session.add(product)\n db.session.commit()\n responseObject = {\n 'status':'success',\n 'message':'Product successfully added'\n }\n return jsonify(responseObject)\n except Exception as e:\n print(e)\n responseObject = {\n 'status':'fail',\n 'message':'Inadequate data / Database error',\n 'error':str(e)\n }\n return jsonify(responseObject)\n\n@vallet.route('/deliver')\nclass VDeliverNow(Resource):\n @authorizestaff(request)\n @api.doc(params={\n 'tid':'Transaction ID'\n })\n def post(u, self):\n try:\n data = request.get_json()\n tid = data.get('tid')\n except Exception as e:\n responseObject = {\n 'status':'fail',\n 'message':'Invalid data'\n }\n return jsonify(responseObject)\n try:\n t = ValletTransaction.query.filter_by(tid=tid).first()\n t.delivered = True\n db.session.commit()\n except Exception as e:\n print(e)\n responseObject = {\n 'status':'fail',\n 'message':'Error: '+str(e)\n }\n return jsonify(responseObject)\n responseObject = {\n 'status':'success',\n 'message':'Successfully delivered'\n }\n return jsonify(responseObject)\n\n@vallet.route('/balance')\nclass VBalance(Resource):\n @authorize(request)\n def get(u, self):\n try:\n balance = valletbalance(u.vid)\n except Exception as e:\n print(e)\n responseObject = {\n 'status':'fail',\n 'message':'Error: '+str(e)\n }\n return jsonify(responseObject)\n responseObject = {\n 'status':'success',\n 'balance':balance\n }\n return jsonify(responseObject)\n\n@vallet.route('/pos')\nclass ValletPOS(Resource):\n def get(self):\n try:\n pos = Pos.query.all()\n resp = []\n for i in pos:\n resp.append({\n 'posid':i.posid,\n 'title':i.title,\n 'descr':i.descr\n })\n except Exception as e:\n print(e)\n responseObject = {\n 'status':'fail',\n 'message':'Database error: '+str(e)\n }\n responseObject = {\n 'status':'success',\n 'data':jsonify(resp)\n }\n return jsonify(responseObject)\n\n @api.doc(params={\n 'title':'POS title',\n 'descr':'Description'\n })\n @authorizestaff(request, \"pay\", 4)\n def post(u, self):\n data = request.get_json()\n pos = Pos(title=data.get('title'), descr=data.get('descr'))\n db.session.add(pos)\n db.session.commit()\n responseObject = {\n 'status':'success',\n 'message':'POS added'\n }\n return jsonify(responseObject)\n","sub_path":"app/vallet.py","file_name":"vallet.py","file_ext":"py","file_size_in_byte":12299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"623895930","text":"# saa1_psb31_2\nfrom saa1_psb31_1 import *\n# Helper Funcitons#\ndef sequenceToindexList(seq):\n\t# Return a sequence of indeces seq (0-N)\n\tseq = np.array(seq)\n\treturn sequenceToindexArray(seq)\ndef sequenceToindexArray(seq):\n\t# Return a sequence of indeces seq (0-N)\n\tV = np.unique(seq)\n\tfor i,v in enumerate(V):\n\t\tindex = np.where(seq == v)[0]\n\t\tseq[index] = i \n\tseq.astype(int)\n\tseq = seq.tolist()\n\tseq = [int(i) for i in seq]\n\treturn seq\ndef followCount(tup,chain):\n\n\tx1 = tup[0]\n\tx2 = tup[1]\n\t# Count the of times that x2 follows x1 / number \n\t# getIndices of x1 and x2\n\ti1 = np.where(np.array(chain) == x1)[0]\n\ti2 = np.where(np.array(chain) == x2)[0]-1\n\tcommonIndeces = [item for item in i1 if item in i2]\t# how many i1 == i2\n\tif x1 == chain[-1]:\n\t\tpercentage = (float(len(commonIndeces)))/float(len(i1)-1)\n\telse:\n\t\tpercentage = (float(len(commonIndeces)))/float(len(i1))\n\treturn percentage\n# end helper functions#\ndef mlmChain(chain):\n# A function which reads a sequence of state indices (i.e. elements of\n# f1; : : : ;Kg) and infers a maximum likelihood Markov chain transition matrix and\n# initial distribution.\n\tS = list(set(chain))\n\t# Get set of states\n\tK = len(S)\n\t# Given a A trans matrix and mu init dist, calc the probability of the chain occuring\n\tmu = [0]*K # zeros \n\tmu[S.index(chain[0])] = 1\n\t# now MLE for A\n\tplist = []\n\tfor i in S:\n\t\tfor j in S:\n\t\t\tfc = followCount((i,j),chain)\n\t\t\tplist.append(fc)\n\t# Generate the matrix\n\tA = np.array(plist).reshape(K,K)\n\treturn A.tolist(),mu\n# print mlmChain(chain=mChain(muFile='initialDistribution.csv',Afile='transitionMatrix.csv',N=1000))\n# ([[0.8063492063492064, 0.19365079365079366], [0.09064327485380116, 0.9093567251461988]], [0, 1])\n\n","sub_path":"saa1_psb31_2.py","file_name":"saa1_psb31_2.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"207796159","text":"try:\n import neovim\n import os\n sock = os.environ.get('NVIM_LISTEN_ADDRESS')\n vim = neovim.attach('socket', sock)\nexcept:\n import vim\n\nfrom pudb.settings import load_breakpoints\nfrom pudb import NUM_VERSION\n\nfilename = vim.eval('expand(\"%:p\")')\n\nargs = () if NUM_VERSION >= (2013, 1) else (None,)\nbps = load_breakpoints(*args)\n\nfor bp in bps:\n if bp[0] != filename:\n continue\n\n sign_id = vim.eval(\"s:next_sign_id\")\n vim.command(\"sign place %s line=%s name=PudbBreakPoint file=%s\"\n % (sign_id, bp[1], filename))\n vim.eval(\"add(b:pudb_sign_ids, s:next_sign_id)\")\n vim.command(\"let s:next_sign_id += 1\")\n","sub_path":"plugin/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"555156388","text":"# -*- coding: utf-8 -*-\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom wagtail.contrib.settings.models import BaseSetting, register_setting\n\n\n@register_setting\nclass FaviconSettings(BaseSetting):\n favicon_small = models.ImageField(\n _('favicon small'),\n help_text=_(\"Your favicon, 32x32 .ico file\"),\n blank=True)\n favicon_large = models.ImageField(\n _('favicon large'),\n help_text=_(\"Your favicon, 128x128 .png file\"),\n blank=True)\n","sub_path":"wagtail_favicon/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"85035011","text":"from django.urls import reverse\nfrom rest_framework import status\nfrom posts.models import Post\nfrom users.models import CustomUser\nfrom .models import Comment\nfrom rest_framework.test import APITestCase\nimport json\n\n\nclass CommentTests(APITestCase):\n def setUp(self):\n self.user = CustomUser.objects.create(username='zach')\n self.post = Post.objects.create(title='', content='')\n self.client.force_authenticate(self.user)\n\n def test_create_comment(self):\n url = reverse('comments-list')\n data = {\n 'content': 'Test comment!',\n 'post': self.post.id\n }\n\n res = self.client.post(url, data=json.dumps(data), content_type='application/json')\n self.assertEqual(res.status_code, status.HTTP_201_CREATED, 'Unable to create comment!')\n\n comment_objects = Comment.objects.all()\n self.assertGreater(comment_objects.count(), 0, 'No comments in database!')\n\n def test_empty_comment(self):\n url = reverse('comments-list')\n data = {\n 'content': '',\n 'post': self.post.id\n }\n\n res = self.client.post(url, data=json.dumps(data), content_type='application/json')\n self.assertNotEqual(res.status_code, status.HTTP_201_CREATED, 'Why was this empty comment created??')\n\n comment_objects = Comment.objects.all()\n self.assertEqual(comment_objects.count(), 0, 'Should be zero comments')\n\n def test_invalid_post_comment(self):\n url = reverse('comments-list')\n data = {\n 'content': 'Test comment!',\n 'post': -1\n }\n\n res = self.client.post(url, data=json.dumps(data), content_type='application/json')\n self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST, 'Why was this shitty request accepted?')\n\n comment_objects = Comment.objects.all()\n self.assertEqual(comment_objects.count(), 0, \"There shouldn't be any comments in the database\")\n\n def test_delete_comment(self):\n # First, let's actually create the comment\n url = reverse('comments-list')\n data = {\n 'content': 'Test comment!',\n 'post': self.post.id\n }\n\n # Send the request\n res = self.client.post(url, data=json.dumps(data), content_type='application/json')\n self.assertEqual(res.status_code, status.HTTP_201_CREATED, 'Unable to create comment!')\n\n # Okay, now that we're created the comment, let's make sure it exists...\n comment_objects = Comment.objects.all()\n self.assertGreater(comment_objects.count(), 0, 'No comments in database!')\n\n # Let's get the specific comment we just created... pk of 1 should suffice\n detail_url = reverse('comments-detail', kwargs={'pk': 1})\n res = self.client.delete(detail_url)\n self.assertLess(res.status_code, 300, 'Unable to delete comment!')\n\n # Let's make sure that it's deleted now\n comment_objects = Comment.objects.all()\n self.assertEqual(comment_objects.count(), 0, 'There shouldn\\'t be any comments! But there are...')\n","sub_path":"comments/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"207769110","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 4 17:31:40 2019\r\n\r\n@author: jbgab\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 23 11:37:23 2018\r\n\r\n@author: jbgab\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\ndef spatial(x,y,c,title=''):\r\n maxX=max(x)\r\n minX=min(x)\r\n xdev=(maxX-minX)\r\n #xlim=xdev*.05\r\n xbound=xdev\r\n while xbound < 5:\r\n xbound+=xdev*(5-int(xbound))\r\n xbound=int(xbound)\r\n \r\n maxY=max(y)\r\n minY=min(y)\r\n ydev=(maxY-minY)\r\n #ylim=xdev*.05\r\n #ybound=ydev\r\n ybound=xbound*(ydev/xdev)\r\n ybound=int(ybound)\r\n \r\n figsize=(xbound,ybound)\r\n plt.title=(title)\r\n\r\n plt.figure(figsize=figsize,dpi=100)\r\n plt.xlim(minX-xdev,maxX+xdev)\r\n plt.ylim(minY-ydev,maxY+ydev)\r\n\r\n plt.scatter(x,y,s=10,c=c)\r\n plt.ticklabel_format(style='plain',axis='both', useOffset=False)\r\n \r\n plt.axis('equal')\r\n plt.grid(True)\r\n plt.show()\r\n\r\n\r\n#%% Example of use\r\n\r\n\r\nlonColumn='Lon'\r\nlatColumn='Lat'\r\n\r\nsoilsensors = pd.read_csv('eucfacesoilsensorfiles\\\\convertedLocations.csv',index_col=0)\r\nsoilsensors=soilsensors.rename(columns={'Latitude':latColumn,'Longitude':lonColumn})\r\n#soilsensorsCleaned=soilsensors.loc[[lonColumn,latColumn],:].values.astype(float)\r\nsoils = pd.read_csv('sensorLocations.csv_out.csv',index_col=0)\r\nringColler=pd.read_csv('out_EucFACE_exact_mapgrid_ring_coller.csv',index_col=0)\r\nlocations = pd.concat([soilsensors, soils,ringColler], ignore_index=True,sort=False)\r\nlocations.index=locations.UniqueID\r\n\r\nimport glob\r\nimport re\r\n#files like FACE_R1_B1_SoilVars_20180831.dat\r\nfilePath='eucfacesoilsensorfiles\\\\'\r\noutPath='eucfacesoilsensorFigures\\\\'\r\nfiles = glob.glob(filePath+'*SoilVars*.dat')#uses psuedo regex to access a list of files\r\nprint(files)\r\n\r\ntesting=True\r\n\r\ni=0\r\nwhile (i < len(files)):\r\n title=files[i].strip(filePath)\r\n file=pd.read_csv(files[i], header=[1],index_col=0)#read file i\r\n plotterVals=file.loc[file.index[2]:,file.columns[1]:].astype(float)\r\n plotterVals.index=pd.to_datetime(plotterVals.index)\r\n ring=float(re.findall('R([0-9])',title)[0])\r\n currentlocations=locations[locations.loc[:,'Ring']==ring]\r\n minimum=dict()\r\n maximum=dict()\r\n deviation=dict()\r\n for column in plotterVals:\r\n minimum[column]=plotterVals[column].min()\r\n maximum[column]=plotterVals[column].max()\r\n deviation[column]=plotterVals[column].max()-plotterVals[column].min()\r\n x=[]\r\n y=[]\r\n c=[]\r\n for timestamp,data in plotterVals.iterrows():\r\n i=0\r\n while i