diff --git "a/2160.jsonl" "b/2160.jsonl" new file mode 100644--- /dev/null +++ "b/2160.jsonl" @@ -0,0 +1,658 @@ +{"seq_id":"543349055","text":"#coding:UTF-8\n\"\"\"\nDataControllerクラスのテストプログラム\n\"\"\"\n\nimport os\nimport sys\nsys.path.append(os.pardir)\nfrom DataController import DataController\n\ndef main():\n \"\"\" テストのメイン処理 \"\"\"\n\n # 本番同様にファイル読み込みを行うため、1つ上の階層に移動する。\n os.chdir('../')\n dataobj = DataController()\n dataobj.get_base_unixtime()\n\nif __name__ == '__main__':\n main()\n","sub_path":"tests/test_data_controller.py","file_name":"test_data_controller.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"79087442","text":"from django.shortcuts import render, redirect, get_object_or_404\n\nfrom . models import OLT, Oltdown, Province\nfrom django.http import HttpResponse\nfrom django.db.models import Count, F\n\nimport os\nimport threading\nimport time\n\n\n# Create your views here.\n\n# def index(request):\n# olt_data = OvccData.objects.all()\n# return render(request, 'index.html',{'olt_data':olt_data})\n\ndef dashboard(request):\n pass\n\n\nfrom datetime import datetime\nfrom django.utils import timezone\n\ndef index(request):\n return HttpResponse('test')\n \n\nfrom .forms import OltDownForm, OltDownUpdate\n\ndef olt_update_form(request,id):\n context={}\n\n obj = get_object_or_404(Oltdown,id=id)\n form = OltDownForm(request.POST or None, instance=obj)\n\n if form.is_valid():\n form.save()\n return redirect('/')\n \n context[\"form\"] = form\n\n\n return render(request,\"update.html\",context)\n\ndef update_olt_data(request, id):\n if request.method == 'Post':\n pi = Oltdown.objects.get(pk=id)\n \n return render(request,'update.html',{'id':id})\n\ndef down_list(request):\n olt_down = Oltdown.objects.all()\n hostnames = OLT.objects.all()\n #if Oltdown.objects.filter(uptime__isnull = True):\n context = {\n 'olt_down':olt_down\n }\n #else:\n #pass\n return render(request, 'downlist.html',context)\n\n#FOR OPERATIONAL VIEW\n\ndef operational(request):\n olt_down = Oltdown.objects.filter(reason__exact='')\n context={\n 'olt_down':olt_down\n }\n return render(request, 'operational.html',context)\n\ndef add_down_data(request):\n context={}\n form = OltDownUpdate(request.POST or None)\n if form.is_valid():\n form.save()\n return('downlist')\n context['form'] = form\n return render(request, \"add.html\",context)\n\n\n ###################################################\n #CHARTS\n ###################################################\n\nfrom datetime import date\nfrom django.db.models.functions import TruncDay\ndef google_charts(request):\n oltdown = Oltdown.objects.all()\n province = Province.objects.all()\n t = Oltdown.objects.values('province_id').annotate(total=Count('id'))\n olt = OLT.objects.values('province_id').annotate(total=Count('id'))\n groupbydate = oltdown.filter(downtime__gte=date.today()).count()\n totaldownindate = oltdown.annotate(date=TruncDay('downtime')).values('date').annotate(created_count=Count('id')) \n dates = oltdown.annotate(date=TruncDay('downtime')).values('date').distinct() \n uplink_down = oltdown.filter(down_self = False).count()\n\n context = {\n 'oltdown':oltdown,\n 'province':province,\n 't':t,\n 'olt':olt,\n 'groupbydate':groupbydate,\n 'totaldownindate':totaldownindate,\n 'dates':dates,\n 'uplink_down':uplink_down\n }\n return render(request, 'charts.html',context)\n\n# \"\"\" def olt_down(request):\n# p = subprocess.Popen('ping 192.168.0.110')\n# print(p) \"\"\"\n\n# def insert_olt_down(request):\n# hostname=\"test\"\n# response = os.system(f\"ping -n 1 {hostname}\")\n# #print(p)\n# #print(type(response))\n# if response==0:\n# print(hostname + \" is up\")\n# else:\n# print(hostname + \" is down\")\n# olt_down = Oltdown.objects.create(name=hostname)\n# olt_down.save()\n\n\n\n\n#########################################################################################\n##################TEST CODE#################3\n\ndef orm_test(request):\n test_olt = OLT.objects.all()\n context = {\n \"test_olt\":test_olt\n }\n\n for test_olts in test_olt:\n print(test_olts.province)\n return render(request, 'test.html',context)","sub_path":"subisuhostcheck/oltcheck/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"565604963","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#\n# This file is subject to the terms and conditions defined in\n# file 'LICENSE.md', which is part of this source code package.\n#\n\n\nclass BaseUrls(object):\n \"\"\"\n Wrapper around a map of URL endpoints for each K8sObject type.\n\n \"\"\"\n\n def __init__(self, namespace='default', version='v1'):\n self.urls = dict()\n self.urls['Pod'] = '/api/{0}/namespaces/{1}/pods'.format(version, namespace)\n self.urls['ReplicationController'] = '/api/{0}/namespaces/{1}/replicationcontrollers'.format(version, namespace)\n self.urls['Service'] = '/api/{0}/namespaces/{1}/services'.format(version, namespace)\n self.urls['Secret'] = '/api/{0}/namespaces/{1}/secrets'.format(version, namespace)\n\n def get_base_url(self, object_type=None):\n if object_type is None or not isinstance(object_type, str) or object_type not in self.urls.keys():\n types = ', '.join(self.urls.keys())\n raise SyntaxError('Please specify object_type: [ {0} ] in: [ {1} ]'.format(object_type, types))\n return self.urls[object_type]\n","sub_path":"kubernetes/models/v1/BaseUrls.py","file_name":"BaseUrls.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"19967409","text":"import csv\r\n#Mensagem de Bem Vindo e Opcoes ao Usuario\r\ndef bemvindo():\r\n\tprint(\"Bem Vindo a Agenda\")\r\n\tprint(\"Selecione uma Opcao\")\r\n\tprint(\"1 Adicionar um novo contato\")\r\n\tprint(\"2 Listar os contatos da agenda\")\r\n\tprint(\"3 Buscar\")\r\n\tprint(\"4 Deletar\")\r\n\tprint(\"5 Sair do programa\")\r\n\r\n#Funcoes do processo\r\ndef opcao():\r\n x = int(input(\"Insira uma opção: \"))\r\n return x\r\n\r\ndef buscar():\r\n agenda = csv.reader(open('agendatelefonica.csv', 'r'))\r\n nome = input(\"Digite o nome a ser procurado: \")\r\n for linhas in agenda:\r\n if linhas[0] == nome:\r\n print(linhas)\r\n\r\ndef adicionar():\r\n\tprint(\"Adicionar um registro\")\r\n\tagenda = open(\"agendatelefonica.csv\",'a')\r\n\tnome = input(\"Nome do Contato:\")\r\n\ttelefone = input(\"Digite o telefone:\")\r\n\tprint(\"Contato salvo com nome:\",nome,\" e numero\",telefone)\r\n\tagenda.write(nome)\r\n\tagenda.write(\",\")\r\n\tagenda.write(telefone)\r\n\tagenda.write(\"\\n\")\r\n\tagenda.close()\r\n\t\r\ndef listar():\r\n print(\"Lista de Contatos\")\r\n agenda = open(\"agendatelefonica.csv\")\r\n for linhas in agenda:\r\n print(linhas)\r\n print(\"Listado corretamente\")\t\r\n agenda.close()\r\n\r\ndef falha():\r\n\tprint(\"Opcao Incorreta\")\r\n","sub_path":"funcoes.py","file_name":"funcoes.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"639537930","text":"#arguments : lemmata csv, SNER target_atf.Key, SNER atf_prediction.RT\nimport sys\n\nnameMarkers = ['PN', 'GN']\n\ndef checkLem(lem):\n isName = False\n for marker in nameMarkers:\n if marker in lem:\n isName = True\n return isName\n\ndef compileResults(idxFile, resFile):\n idx = []\n res = []\n with open(idxFile, 'r') as f:\n idx = f.read().splitlines()\n with open(resFile, 'r') as f:\n res = f.read().splitlines()\n\n q = {}\n wrd = {}\n for i in range(len(idx)):\n parts = idx[i].split('\\t')\n lineID = parts[1]\n isName = res[i].strip() == \"1\"\n if not lineID in q:\n q[lineID] = []\n wrd[lineID] = []\n if isName not in q[lineID]:\n q[lineID].append(isName)\n wrd[lineID].append(parts[3])\n return (q, wrd)\n\ndef main(lemFile, snerIdxFile, snerResFile):\n (res, wordMap) = compileResults(snerIdxFile, snerResFile)\n (truePositive, trueNegative, falsePositive, falseNegative) = (0, 0, 0, 0)\n undecided = 0\n total = 0\n\n with open(lemFile, 'r') as lemmata:\n for line in lemmata:\n total += 1\n parts = line.split('\\t')\n loc = parts[0]\n wrdSNER = wordMap.get(loc, []) \n if parts[1] not in parts[1]:\n print(\"{} -> {}\".format(parts[1], wrdSNER))\n isName = checkLem(parts[2])\n\n if loc in res:\n r = res[loc]\n else:\n r = [False] # SNER ommits - and ... from its results as known non-name\n\n if (True in r) and (False in r):\n undecided += 1\n elif (True in r):\n if isName:\n truePositive += 1\n else:\n falsePositive += 1\n else:\n if isName:\n falseNegative += 1\n else :\n trueNegative += 1\n print(\"Total tokens : {:6d} : 100.000%\".format(total) )\n print(\"Undecided : {:6d} : {:7.3f}%\".format(undecided, undecided / total * 100.0) )\n print(\"True Positive : {:6d} : {:7.3f}%\".format(truePositive, truePositive / total * 100.0) )\n print(\"True Negative : {:6d} : {:7.3f}%\".format(trueNegative, trueNegative / total * 100.0) )\n print(\"False Positive : {:6d} : {:7.3f}%\".format(falsePositive, falsePositive / total * 100.0) )\n print(\"False Negative : {:6d} : {:7.3f}%\".format(falseNegative, falseNegative / total * 100.0) )\n\n\nmain(sys.argv[1], sys.argv[2], sys.argv[3])\n","sub_path":"LemCompareV2.py","file_name":"LemCompareV2.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"157308008","text":"import h5py\nimport pandas as pd\nimport os\n\nimport numpy as np\nimport math\nimport random\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import OneHotEncoder, LabelEncoder\nimport keras\nfrom keras.utils import np_utils\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\n\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential, Model\nfrom keras.layers import Conv2D, MaxPooling2D, LSTM, Dense, Dropout, Flatten, Input, concatenate, Conv1D\nfrom keras.layers.convolutional import Conv3D\nfrom keras.layers.core import Permute, Reshape\nfrom keras.layers.convolutional_recurrent import ConvLSTM2D\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.callbacks import EarlyStopping\nfrom keras.layers import Conv2D, MaxPooling2D, ConvLSTM2D\nfrom sklearn.model_selection import train_test_split\nfrom keras.optimizers import Adam, Nadam, Adadelta\n\n\n\nimages = h5py.File('features_images.h5','r')\ndata_imgs = images['images'][:]\n\ny = pd.read_csv('merged_labels.csv')\nemotion_lables = y['Merged Emotion'].values\nlabel_encoder = LabelEncoder()\nemotion_lables_encoded = label_encoder.fit_transform(emotion_lables)\nclip_lens = pd.read_csv('subclip_lengths.csv')\nclip_lengths = np.zeros((614,1))\nclip_lengths[0] = 0.822\nclip_lengths[1:] = np.reshape(clip_lens['0.822'].values[:613], (613,1))\n\ntrain_indexes = pd.read_pickle('train_indx.p')\ntest_indexes = pd.read_pickle('test_indx.p')\ny_train = emotion_lables_encoded[train_indexes]\ny_test = emotion_lables_encoded[test_indexes]\n\nX_train = data_imgs[train_indexes]\nX_test = data_imgs[test_indexes]\n\nclip_lengths_train = clip_lengths[train_indexes]\nclip_lengths_test = clip_lengths[test_indexes]\n\naudio_predictions = np.loadtxt('Results/Audio/Emotion_audio_multi_preds.txt', delimiter=',')\nimage_predictions = np.loadtxt('Results/Image/Static Feature/Facial_points_Emotion_predictions_LSTM_ms.txt', delimiter=',')\n\ndef weighted_predictions(audio, audio_percentage, image, image_precentage):\n res = audio_percentage*audio*0.01 + image_precentage*image*0.01\n return res\n\ndef weighted_probs(audio, image):\n res = audio + image\n return res\n\ntry:\n f = open('Results/Late fusion/Emotion_weighted_results.txt','w+')\n wp = weighted_probs(audio_predictions, image_predictions)\n pred = np.argmax(wp, axis = -1)\n acc = np.mean(np.equal(pred, y_test))\n f.write('Audio and Image weighted probs resulting accuracy: ')\n f.write(str(acc))\n f.write('%\\n')\n f.close()\nexcept IOError as e:\n print(\"I/O error({0}): {1}\".format(e.errno, e.strerror))\nexcept ValueError:\n print(\"Could not convert data to an integer.\")\nexcept:\n print(\"Unexpected error:\", sys.exc_info()[0])\n raise\n\n\naudio_predictions = np.loadtxt('Results/Audio/Dominance_audio_predictions_LSTM_ms.txt', delimiter=',')\nimage_predictions = np.loadtxt('Results/Image/Static Feature/Facial_points_Dominance_predictions_LSTM_ms.txt', delimiter=',')\n\n\ntry:\n f = open('Results/Late fusion/Dominace_weighted_results.txt','w+')\n for i in range(0, 110, 10):\n wp = weighted_predictions(audio_predictions, i, image_predictions, 100-i)\n mse = np.mean((wp - y_test)**2)\n f.write('Audio weight ')\n f.write(str(i))\n f.write('%, Image weight: ')\n f.write(str(100-i))\n f.write('% - MSE:')\n f.write(str(mse))\n f.write('\\n')\n f.close()\nexcept IOError as e:\n print(\"I/O error({0}): {1}\".format(e.errno, e.strerror))\nexcept ValueError:\n print(\"Could not convert data to an integer.\")\nexcept:\n print(\"Unexpected error:\", sys.exc_info()[0])\n raise\n\n\n\n\naudio_predictions = np.loadtxt('Results/Audio/Arousal_audio_predictions_LSTM_ms.txt', delimiter=',')\nimage_predictions = np.loadtxt('Results/Image/Static Feature/Facial_points_Arousal_predictions_LSTM_ms.txt', delimiter=',')\n\ntry:\n f = open('Results/Late fusion/Arousal_weighted_results.txt','w+')\n for i in range(0, 110, 10):\n wp = weighted_predictions(audio_predictions, i, image_predictions, 100-i)\n mse = np.mean((wp - y_test)**2)\n f.write('Audio weight ')\n f.write(str(i))\n f.write('%, Image weight: ')\n f.write(str(100-i))\n f.write('% - MSE:')\n f.write(str(mse))\n f.write('\\n')\n f.close()\nexcept IOError as e:\n print(\"I/O error({0}): {1}\".format(e.errno, e.strerror))\nexcept ValueError:\n print(\"Could not convert data to an integer.\")\nexcept:\n print(\"Unexpected error:\", sys.exc_info()[0])\n raise\n","sub_path":"Late_fusion.py","file_name":"Late_fusion.py","file_ext":"py","file_size_in_byte":4531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"34424516","text":"import logging\nimport os\nfrom pathlib import Path\nfrom typing import cast\n\nfrom appdirs import user_config_dir\n\nfrom tox.config.source.ini import Ini, IniLoader\n\nDEFAULT_CONFIG_FILE = Path(user_config_dir(\"tox\")) / \"config.ini\"\n\n\nclass IniConfig:\n TOX_CONFIG_FILE_ENV_VAR = \"TOX_CONFIG_FILE\"\n STATE = {None: \"failed to parse\", True: \"active\", False: \"missing\"}\n\n section = \"tox\"\n\n def __init__(self):\n config_file = os.environ.get(self.TOX_CONFIG_FILE_ENV_VAR, None)\n self.is_env_var = config_file is not None\n self.config_file = Path(config_file if config_file is not None else DEFAULT_CONFIG_FILE)\n self._cache = {}\n\n self.has_config_file = self.config_file.exists()\n if self.has_config_file:\n self.config_file = self.config_file.absolute()\n try:\n self.ini = Ini(self.config_file)\n # noinspection PyProtectedMember\n self.has_tox_section = cast(IniLoader, self.ini.core)._section is not None\n except Exception as exception:\n logging.error(\"failed to read config file %s because %r\", config_file, exception)\n self.has_config_file = None\n\n def get(self, key, of_type):\n # noinspection PyBroadException\n cache_key = key, of_type\n if cache_key in self._cache:\n result = self._cache[cache_key]\n else:\n try:\n source = \"file\"\n value = self.ini.core.load(key, of_type=of_type, conf=None)\n result = value, source\n except KeyError: # just not found\n result = None\n except Exception as exception:\n logging.warning(\n \"%s key %s as type %r failed with %r\", self.config_file, key, of_type, exception,\n )\n result = None\n self._cache[cache_key] = result\n return result\n\n def __bool__(self):\n return bool(self.has_config_file) and bool(self.has_tox_section)\n\n @property\n def epilog(self):\n msg = \"{}config file {!r} {} (change{} via env var {})\"\n return msg.format(\n os.linesep,\n str(self.config_file),\n self.STATE[self.has_config_file],\n \"d\" if self.is_env_var else \"\",\n self.TOX_CONFIG_FILE_ENV_VAR,\n )\n","sub_path":"Exercise Tutorials/Pycon-Talk-Click-Example-Tutorial/venv/lib/python3.8/site-packages/tox/config/cli/ini.py","file_name":"ini.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"347379703","text":"#!/usr/bin/env python\n# coding=utf-8\nimport socket\nimport time\nsock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\nsock.bind(('127.0.0.1',8888))\ndef server():\n while True:\n date,adr=sock.recvfrom(1024)\n sock.sendto(b'rec%s' % date,adr)\n print('recv',date.decode('utf-8'))\nserver()\n\n","sub_path":"udp_server.py","file_name":"udp_server.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"244451856","text":"from django.http import HttpResponse\nfrom tastypie import resources\n\n__author__ = 'ir4y'\n\n\ndef build_content_type(format, encoding='utf-8'):\n \"\"\"\n Appends character encoding to the provided format if not already present.\n \"\"\"\n if 'charset' in format:\n return format\n\n return \"%s; charset=%s\" % (format, encoding)\n\n\ndef create_response(self, request, data, response_class=HttpResponse,\n **response_kwargs):\n desired_format = self.determine_format(request)\n serialized = self.serialize(request, data, desired_format)\n return response_class(content=serialized,\n content_type=build_content_type(desired_format),\n **response_kwargs)\n\nsetattr(resources.Resource, 'create_response', create_response)\n","sub_path":"miniature/api/monkey.py","file_name":"monkey.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"625453220","text":"from pox.core import core\nfrom path import Path\nfrom round_robin_path_balancer import RoundRobinPathBalancer\n\nlog = core.getLogger()\n\nclass ShortestPathsFinder:\n def __init__(self):\n self.sws_linked_to_a_host = []\n self.shortest_paths = {} # origin_dpid: {destiny_dpid: Path}\n self.path_balancer = RoundRobinPathBalancer()\n\n def notifyHostsChanged(self, hosts):\n old_sws_linked_to_a_host = self.sws_linked_to_a_host\n self._calculate_switches_linked_to_a_host(hosts)\n if old_sws_linked_to_a_host != self.sws_linked_to_a_host:\n log.info(\"Switches linked to a host: %s.\",\n self.sws_linked_to_a_host)\n self._calculate_shortest_paths()\n\n def notifyLinksChanged(self):\n self._calculate_shortest_paths()\n\n def get_path(self, origin, destiny):\n if origin in self.shortest_paths:\n if destiny in self.shortest_paths[origin] and len(self.shortest_paths[origin][destiny]) > 0:\n posible_paths = self.shortest_paths[origin][destiny]\n return self.path_balancer.get_balanced(origin, destiny, posible_paths)\n\n log.warn(\"No posible path beetween switches %s and %s.\", origin, destiny)\n return None\n\n def _calculate_switches_linked_to_a_host(self, hosts):\n self.sws_linked_to_a_host = list(set(\n map(lambda link_to_sw: link_to_sw.sw, hosts.values())))\n\n def _calculate_shortest_paths(self):\n self._reset_paths()\n\n for sw_origin in self.sws_linked_to_a_host:\n for sw_destiny in self.sws_linked_to_a_host:\n if (\n sw_origin != sw_destiny\n and not sw_destiny.dpid in self.shortest_paths.get(sw_origin.dpid, [])\n ):\n shortest_paths = self._find_paths(sw_origin, sw_destiny, Path(), [])\n self._set_paths(sw_origin, sw_destiny, shortest_paths)\n\n def _set_paths(self, sw_origin, sw_destiny, paths):\n shortest_paths_from_origin = self.shortest_paths.get(sw_origin.dpid, {})\n shortest_paths_from_origin[sw_destiny.dpid] = paths\n self.shortest_paths[sw_origin.dpid] = shortest_paths_from_origin\n\n def _find_paths(self, sw_origin, sw_destiny, actual_path, visited_sws):\n visited_sws.append(sw_origin)\n\n port_to_destiny = sw_origin.get_port_to(sw_destiny)\n if port_to_destiny:\n actual_path.add_jump(sw_origin, port_to_destiny)\n actual_path.add_destiny(sw_destiny)\n return [actual_path] # returns a list of posible paths\n else:\n paths_from_the_next_level = []\n linked_sws = sw_origin.get_linked_switches()\n\n old_visited_sws = visited_sws\n # update visited_sws to have the sws in the next level\n visited_sws = visited_sws + linked_sws\n for port, sw in sw_origin.get_links():\n # no go to a sw in a higher level\n if sw not in old_visited_sws:\n new_actual_path = actual_path.copy()\n new_actual_path.add_jump(sw_origin, port)\n for path in self._find_paths(sw, sw_destiny, new_actual_path, visited_sws):\n paths_from_the_next_level.append(path)\n return self._keep_only_shortests(paths_from_the_next_level)\n\n def _keep_only_shortests(self, paths):\n if len(paths) > 0:\n shortest = len(paths[0])\n for path in paths:\n if len(path) < shortest:\n shortest = len(path)\n return list(filter(lambda path: len(path) == shortest, paths))\n else:\n # no posible path between two switches\n return []\n\n def _reset_paths(self):\n self.shortest_paths = {}\n self.path_balancer.reset()\n","sub_path":"controller/extensions/shortest_paths_finder.py","file_name":"shortest_paths_finder.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"77838716","text":"# Define a funtion that returns true if the string is a palindrome.\ndef isPalindrome(s):\n \"\"\"Checks if s is a palindrome.\"\"\"\n # Define a function that changes the letters to lowercase and removes non-letters.\n def toChars(s):\n \"\"\"Converts string to lower case and removes non-letters.\"\"\"\n # Changes s to lowercase.\n s = s.lower()\n print(\"Changed string to lowercase and removed non-letters.\")\n chars = \"\"\n # Removes non-letters.\n for c in s:\n if c in 'abcdefghijklmnopqrstuvwxyz':\n chars += c\n # Returns new string.\n return chars\n # Define a function that checks if the string is the same when it is reversed.\n def isPal(s):\n \"\"\"Checks if the first and last letters of s are the same. \n Then uses recursion to check the rest of the string\"\"\"\n # If the string is of length 0 or 1, return True.\n if len(s) <= 1:\n print(\"Base case returned true.\")\n return True\n # Else, check if the first and last characters are the same. \n # Then, use recursion to check the rest of the string.\n else:\n # If the first and last letters match, and the rest of the string mathes, return True.\n if (s[0] != s[-1]):\n print(\"Letters did not match.\")\n return s[0] == s[-1] and isPal(s[1:-1])\n # Use toChars to change the string, and use isPal to check if it's a palindrome.\n return isPal(toChars(s))\n\ntext = input(\"Enter a string: \")\nprint(isPalindrome(text))","sub_path":"sem_1/programming_1/prac9/p17p5.py","file_name":"p17p5.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"135640516","text":"import requests\r\nimport re\r\nimport string\r\nimport time\r\nimport os\r\n\r\n\r\ntry:\r\n with open(\"cookie.txt\") as fh:\r\n cookie = {'.ROBLOSECURITY':fh.read()}\r\n if len(cookie['.ROBLOSECURITY']) < 1: raise FileNotFoundError\r\nexcept FileNotFoundError:\r\n print(\"Unable to find pin, either a file named 'cookie.txt' doesn't exist or it is empty. \\nPlease enter your cookie below: \\n\")\r\n cookiestring = input()\r\n with open(\"cookie.txt\",\"w\") as fh:\r\n fh.write(cookiestring)\r\n cookie = {'.ROBLOSECURITY':cookiestring}\r\n \r\n \r\nurl = 'https://auth.roblox.com/v1/account/pin/unlock'\r\ntoken = requests.post('https://auth.roblox.com/v1/login', cookies = cookie)\r\ntoken1 = (token.headers['x-csrf-token'])\r\nrequestheader = {'X-CSRF-TOKEN': token1}\r\n \r\n\r\n\r\n\r\n\r\nprint('''\r\n Loading Fork 0.1, forked from Version R2.0\r\n Official server: discord.gg/4sXG2DtU96 \\n\r\n This script might take a very very long time to find a pin due to roblox\r\n limiting the amount of tries, but it will 100% find it if left to run,\r\n this script is useful if you have no other choice! \\n\r\n Server Booster Credits: T0m45#0001, frog#8222, champagne charlie#5616, grango#5298,\r\n pebbles#3363, BlazingWaterz#0001, Sam.#6605, MEDO#1111, Roblox Thot#0001, Ackermann#1629, moq#0001\r\n (If you boost the server you will be mentioned in all of my scripts!)\\n\r\n Script By: Egypt#2325 (join the server if you have any issues)\\n\r\n Forked by johnngnky#9086\r\n Contact email: hi@amanda.ng.eu.org \\n\r\n ''')\r\n\r\nglobal i\r\ntry:\r\n with open(\"checkpoint.txt\") as fh:\r\n i = int(fh.read())\r\n if 0>i>10000: raise ValueError\r\nexcept FileNotFoundError:\r\n i = 0\r\nexcept ValueError:\r\n print(\"checkpoint content unable to be read correctly.\")\r\n raise RuntimeError\r\n\r\nif i>0: print(f\"Seems like we have ran this program before, we'll be starting at {i}\")\r\n\r\nwhile i < 10000:\r\n \r\n try:\r\n\r\n realpin = str(i).zfill(4)\r\n payload = {'pin': realpin}\r\n \r\n r = requests.post(url, data = payload, headers = requestheader, cookies = cookie)\r\n \r\n if 'unlockedUntil' in r.text:\r\n\r\n hit = \"THE PIN IS: \" + realpin\r\n print('FOUND PIN: ' + hit)\r\n with open(\"pin.txt\",\"w\") as fh:\r\n fh.write(hit)\r\n\r\n input('Pin has been found, press enter to exit!')\r\n \r\n break\r\n \r\n elif 'Too many requests made' in r.text:\r\n \r\n print('Roblox Blocked Request, please wait...')\r\n time.sleep(60)\r\n \r\n elif 'Authorization' in r.text:\r\n \r\n print('Authorization error, please make sure you have the correct cookie!')\r\n \r\n raise AssertionError\r\n \r\n elif 'Incorrect' in r.text:\r\n\r\n failedhit = \"Tried: \" + realpin\r\n print(failedhit)\r\n i += 1\r\n time.sleep(5)\r\n else:\r\n raise AssertionError\r\n\r\n except KeyboardInterrupt:\r\n with open(\"checkpoint.txt\",\"x\") as fh:\r\n fh.write(realpin)\r\n print(f\"Ctrl+C caught; currently trying {realpin}, next time you run the script, we'll start there.\")\r\n input(\"Press enter to exit.\")\r\n except Exception as e:\r\n print(e)\r\n print(r.text)\r\n print(payload)\r\n print('An error has occured. Please contact official support or send me an email at hi@amanda.ng.eu.org')\r\n input('Press enter to exit!')\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n","sub_path":"PinCrackerV2F0.1.py","file_name":"PinCrackerV2F0.1.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"165028298","text":"#!/usr/bin/env python\n\n\n# Run script from base directory:\n# python scripts/logres.py\n#\n###################################\n\n\nfrom datetime import timedelta\nimport pathlib\nimport time\nstart = time.time()\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.externals import joblib\nfrom sklearn.linear_model import LogisticRegression\n\n\n\n### SETTINGS\n\n# Random seed\nSEED = 112\n\n# Base directory\nBASE = pathlib.Path.cwd()\n\n# Data dir and files\nDATADIR = BASE / 'data_clean'\nDATAFILE = 'ClashRoyaleTournament_Demo.csv'\n\nMODELDIR = BASE / 'models'\nMODELNAME = 'mlp.joblib.pkl'\n\n\n\n### DATA COLS\ncols_labels = ['winner']\ncols_features_trophies = [\n 'players.right.trophy', 'players.left.trophy',\n 'trophy.discrepancy'\n]\ncols_features_cards = [\n 'Skeletons_L', 'Skeletons_R',\n 'Ice_Spirit_L', 'Ice_Spirit_R',\n 'Goblins_L', 'Goblins_R',\n 'Spear_Goblins_L', 'Spear_Goblins_R',\n 'Zap_L', 'Zap_R',\n 'Bats_L', 'Bats_R',\n 'Fire_Spirits_L', 'Fire_Spirits_R',\n 'Archers_L', 'Archers_R',\n 'Arrows_L', 'Arrows_R',\n 'Knight_L', 'Knight_R',\n 'Minions_L', 'Minions_R',\n 'Bomber_L', 'Bomber_R',\n 'Cannon_L', 'Cannon_R',\n 'Goblin_Gang_L', 'Goblin_Gang_R',\n 'Mortar_L', 'Mortar_R',\n 'Tesla_L', 'Tesla_R',\n 'Barbarians_L', 'Barbarians_R',\n 'Minion_Horde_L', 'Minion_Horde_R',\n 'Royal_Giant_L', 'Royal_Giant_R',\n 'Elite_Barbarians_L', 'Elite_Barbarians_R',\n 'Heal_L', 'Heal_R',\n 'Ice_Golem_L', 'Ice_Golem_R',\n 'Tombstone_L', 'Tombstone_R',\n 'Mega_Minion_L', 'Mega_Minion_R',\n 'Dart_Goblin_L', 'Dart_Goblin_R',\n 'Fireball_L', 'Fireball_R',\n 'Mini_Pekka_L', 'Mini_Pekka_R',\n 'Musketeer_L', 'Musketeer_R',\n 'Hog_Rider_L', 'Hog_Rider_R',\n 'Valkyrie_L', 'Valkyrie_R',\n 'Battle_Ram_L', 'Battle_Ram_R',\n 'Furnace_L', 'Furnace_R',\n 'Flying_Machine_L', 'Flying_Machine_R',\n 'Bomb_Tower_L', 'Bomb_Tower_R',\n 'Giant_L', 'Giant_R',\n 'Goblin_Hut_L', 'Goblin_Hut_R',\n 'Inferno_Tower_L', 'Inferno_Tower_R',\n 'Wizard_L', 'Wizard_R',\n 'Rocket_L', 'Rocket_R',\n 'Elixir_Collector_L', 'Elixir_Collector_R',\n 'Barbarian_Hut_L', 'Barbarian_Hut_R',\n 'Three_Musketeers_L', 'Three_Musketeers_R',\n 'Mirror_L', 'Mirror_R',\n 'Rage_L', 'Rage_R',\n 'Skeleton_Army_L', 'Skeleton_Army_R',\n 'Goblin_Barrel_L', 'Goblin_Barrel_R',\n 'Tornado_L', 'Tornado_R',\n 'Guards_L', 'Guards_R',\n 'Clone_L', 'Clone_R',\n 'Baby_Dragon_L', 'Baby_Dragon_R',\n 'Hunter_L', 'Hunter_R',\n 'Poison_L', 'Poison_R',\n 'Dark_Prince_L', 'Dark_Prince_R',\n 'Freeze_L', 'Freeze_R',\n 'Prince_L', 'Prince_R',\n 'Witch_L', 'Witch_R',\n 'Balloon_L', 'Balloon_R',\n 'Bowler_L', 'Bowler_R',\n 'Executioner_L', 'Executioner_R',\n 'Giant_Skeleton_L', 'Giant_Skeleton_R',\n 'Lightning_L', 'Lightning_R',\n 'X_Bow_L', 'X_Bow_R',\n 'PEKKA_L', 'PEKKA_R',\n 'Golem_L', 'Golem_R',\n 'The_Log_L', 'The_Log_R',\n 'Miner_L', 'Miner_R',\n 'Princess_L', 'Princess_R',\n 'Ice_Wizard_L', 'Ice_Wizard_R',\n 'Bandit_L', 'Bandit_R',\n 'Night_Witch_L', 'Night_Witch_R',\n 'Inferno_Dragon_L', 'Inferno_Dragon_R',\n 'Lumberjack_L', 'Lumberjack_R',\n 'Electro_Wizard_L', 'Electro_Wizard_R',\n 'Graveyard_L', 'Graveyard_R',\n 'Sparky_L', 'Sparky_R',\n 'Lava_Hound_L', 'Lava_Hound_R'\n]\ncols_features_card_lvls = [\n 'Skeletons_L_lvl', 'Skeletons_R_lvl',\n 'Ice_Spirit_L_lvl', 'Ice_Spirit_R_lvl',\n 'Goblins_L_lvl', 'Goblins_R_lvl',\n 'Spear_Goblins_L_lvl', 'Spear_Goblins_R_lvl',\n 'Zap_L_lvl', 'Zap_R_lvl',\n 'Bats_L_lvl', 'Bats_R_lvl',\n 'Fire_Spirits_L_lvl', 'Fire_Spirits_R_lvl',\n 'Archers_L_lvl', 'Archers_R_lvl',\n 'Arrows_L_lvl', 'Arrows_R_lvl',\n 'Knight_L_lvl', 'Knight_R_lvl',\n 'Minions_L_lvl', 'Minions_R_lvl',\n 'Bomber_L_lvl', 'Bomber_R_lvl',\n 'Cannon_L_lvl', 'Cannon_R_lvl',\n 'Goblin_Gang_L_lvl', 'Goblin_Gang_R_lvl',\n 'Mortar_L_lvl', 'Mortar_R_lvl',\n 'Tesla_L_lvl', 'Tesla_R_lvl',\n 'Barbarians_L_lvl', 'Barbarians_R_lvl',\n 'Minion_Horde_L_lvl', 'Minion_Horde_R_lvl',\n 'Royal_Giant_L_lvl', 'Royal_Giant_R_lvl',\n 'Elite_Barbarians_L_lvl', 'Elite_Barbarians_R_lvl',\n 'Heal_L_lvl', 'Heal_R_lvl',\n 'Ice_Golem_L_lvl', 'Ice_Golem_R_lvl',\n 'Tombstone_L_lvl', 'Tombstone_R_lvl',\n 'Mega_Minion_L_lvl', 'Mega_Minion_R_lvl',\n 'Dart_Goblin_L_lvl', 'Dart_Goblin_R_lvl',\n 'Fireball_L_lvl', 'Fireball_R_lvl',\n 'Mini_Pekka_L_lvl', 'Mini_Pekka_R_lvl',\n 'Musketeer_L_lvl', 'Musketeer_R_lvl',\n 'Hog_Rider_L_lvl', 'Hog_Rider_R_lvl',\n 'Valkyrie_L_lvl', 'Valkyrie_R_lvl',\n 'Battle_Ram_L_lvl', 'Battle_Ram_R_lvl',\n 'Furnace_L_lvl', 'Furnace_R_lvl',\n 'Flying_Machine_L_lvl', 'Flying_Machine_R_lvl',\n 'Bomb_Tower_L_lvl', 'Bomb_Tower_R_lvl',\n 'Giant_L_lvl', 'Giant_R_lvl',\n 'Goblin_Hut_L_lvl', 'Goblin_Hut_R_lvl',\n 'Inferno_Tower_L_lvl', 'Inferno_Tower_R_lvl',\n 'Wizard_L_lvl', 'Wizard_R_lvl',\n 'Rocket_L_lvl', 'Rocket_R_lvl',\n 'Elixir_Collector_L_lvl', 'Elixir_Collector_R_lvl',\n 'Barbarian_Hut_L_lvl', 'Barbarian_Hut_R_lvl',\n 'Three_Musketeers_L_lvl', 'Three_Musketeers_R_lvl',\n 'Mirror_L_lvl', 'Mirror_R_lvl',\n 'Rage_L_lvl', 'Rage_R_lvl',\n 'Skeleton_Army_L_lvl', 'Skeleton_Army_R_lvl',\n 'Goblin_Barrel_L_lvl', 'Goblin_Barrel_R_lvl',\n 'Tornado_L_lvl', 'Tornado_R_lvl',\n 'Guards_L_lvl', 'Guards_R_lvl',\n 'Clone_L_lvl', 'Clone_R_lvl',\n 'Baby_Dragon_L_lvl', 'Baby_Dragon_R_lvl',\n 'Hunter_L_lvl', 'Hunter_R_lvl',\n 'Poison_L_lvl', 'Poison_R_lvl',\n 'Dark_Prince_L_lvl', 'Dark_Prince_R_lvl',\n 'Freeze_L_lvl', 'Freeze_R_lvl',\n 'Prince_L_lvl', 'Prince_R_lvl',\n 'Witch_L_lvl', 'Witch_R_lvl',\n 'Balloon_L_lvl', 'Balloon_R_lvl',\n 'Bowler_L_lvl', 'Bowler_R_lvl',\n 'Executioner_L_lvl', 'Executioner_R_lvl',\n 'Giant_Skeleton_L_lvl', 'Giant_Skeleton_R_lvl',\n 'Lightning_L_lvl', 'Lightning_R_lvl',\n 'X_Bow_L_lvl', 'X_Bow_R_lvl',\n 'PEKKA_L_lvl', 'PEKKA_R_lvl',\n 'Golem_L_lvl', 'Golem_R_lvl',\n 'The_Log_L_lvl', 'The_Log_R_lvl',\n 'Miner_L_lvl', 'Miner_R_lvl',\n 'Princess_L_lvl', 'Princess_R_lvl',\n 'Ice_Wizard_L_lvl', 'Ice_Wizard_R_lvl',\n 'Bandit_L_lvl', 'Bandit_R_lvl',\n 'Night_Witch_L_lvl', 'Night_Witch_R_lvl',\n 'Inferno_Dragon_L_lvl', 'Inferno_Dragon_R_lvl',\n 'Lumberjack_L_lvl', 'Lumberjack_R_lvl',\n 'Electro_Wizard_L_lvl', 'Electro_Wizard_R_lvl',\n 'Graveyard_L_lvl', 'Graveyard_R_lvl',\n 'Sparky_L_lvl', 'Sparky_R_lvl',\n 'Lava_Hound_L_lvl', 'Lava_Hound_R_lvl'\n]\ncols_features_card_stats = [\n 'avg_lvl_L', 'avg_lvl_R', 'level_discrepancy',\n 'left_elixir_cost', 'right_elixir_cost'\n]\n\n\n\n### METHODS\n\n# Time elapsed\ndef clock():\n return timedelta(seconds=(time.time() - start))\n\n\n# Data set loader\ndef load_dataframe(PATH):\n df = pd.read_csv(PATH)\n\n # Fill missing data (card levels)\n df.fillna(-1.0, inplace=True)\n\n print(\"Loaded dataframe ({}) \\n{} \\n{} examples \\n\".format(clock(), PATH.name, len(df.index)))\n return df\n\n\n# Feature and target constructor\ndef get_dataset(df, cols_features):\n # Grab features\n X = df[cols_features].to_numpy()\n\n # Map target values\n # 'left': 0\n # 'right': 1\n y = np.ravel(np.where( df[cols_labels] == 'left', -1.0, 1.0 ))\n\n print(\"Built dataset ({}) \\n{} features \\n\".format(clock(), len(cols_features)))\n return X, y\n\n\n# Model loader\ndef load_model(PATH):\n model = joblib.load(PATH)\n\n print(\"Loaded pre-trained model ({}) \\n{} \\n\".format(clock(), PATH.name))\n return model\n\n\n# Evaluate\ndef eval(model, X_test, y_test):\n score = model.score(X_test, y_test)\n print(\"Classification score ({}) \\n{}\\n\".format(clock(), score))\n return score\n\n\n### RUNS\n# with different features\nruns = [\n ('Cards, card lvls, card stats', cols_features_cards + cols_features_card_lvls + cols_features_card_stats, True)\n]\n\n\n\n\n### SCRIPT\n\nprint(\"Ready ({})\\n\".format(clock()))\n\ndf = load_dataframe(DATADIR/DATAFILE)\nmodel = load_model(MODELDIR/MODELNAME)\n\nfor i, (title, cols_features, save) in enumerate(runs):\n print(\"### EVAL RUN No. {} ###\\n{}\\n\".format(i+1, title))\n\n X, y = get_dataset(df, cols_features)\n\n score = eval(model, X, y)\n\n del X, y\n\nprint(\"Done ({})\\n\".format(clock()))\n","sub_path":"scripts/eval_mlp.py","file_name":"eval_mlp.py","file_ext":"py","file_size_in_byte":8170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"346733659","text":"# 06.08.2017\nfilename = 'text_files/guest_book.txt'\nwith open(filename, 'a') as f_object:\n while True:\n print(\"Enter 'q' or 'quit' when you want to exit the program.\")\n name = input(\"Enter your name: \")\n if name.lower() != 'q' and name.lower() != 'quit':\n print(\"Hello, \" + name.title())\n f_object.write(name + \"\\n\")\n else:\n break\n","sub_path":"Basics/Exercises/exercise_files_3.py","file_name":"exercise_files_3.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"396337469","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\ncapital=int(input(\"請輸入本金:\"))\nrate=float(input(\"請輸入利率(小數):\"))\nyears=int(input(\"請輸入存款年數:\"))\nmoney=capital*((1+rate)**years)\nprint(\"您現在的存款為:\"+str(money))\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"W3_a2.py","file_name":"W3_a2.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"585892444","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom proj_geometry import *\nfrom utils import *\n\n\nif __name__ == '__main__':\n #filename = \"./data/0042.npz\"\n #filename = \"./data/0020.npz\" \n filename = \"./data/0027.npz\" \n t,features,linear_velocity,rotational_velocity,K,b,cam_T_imu = load_data(filename)\n \n#%% \n \n # (a) IMU Localization via EKF Prediction\n # Time step\n t_size = t.shape[1]\n tau = np.diff(t)\n \n # Random noise for the velocity and the angle \n rng = np.random.RandomState(seed=1234)\n p_velocity_std = 0.15\n p_omega_std = 0.25\n W_diag = np.array([p_velocity_std,p_velocity_std,p_velocity_std, \\\n p_omega_std,p_omega_std,p_omega_std])\n W = np.diag(W_diag) \n \n # Initialization of Mean & Covariance matrix\n u_t = np.concatenate((linear_velocity, rotational_velocity), axis=0)\n mu1_t = np.zeros((4,4,t_size))\n mu1_t[:,:,0] = np.eye(4)\n Sigma1_t = np.zeros((6,6,t_size))\n Sigma1_t[:,:,0] = np.eye(6) \n \n # Prediction step \n for i in range(t_size-1):\n ut = -1*tau[0,i]*u_t[:,i]\n noise = (tau[0,i]**2) * W\n mu1_t[:,:,i+1] = SE3(ut) @ mu1_t[:,:,i]\n Sigma1_t[:,:,i+1] = adjSE3(ut) @ Sigma1_t[:,:,i] @ adjSE3(ut).T + noise\n \n T_t_ = np.zeros((4,4,t_size)) \n for i in range(t_size):\n T_t_[:,:,i] = np.linalg.inv(mu1_t[:,:,i])\n T_t = mu1_t \n \n # Plot the trajectory\n fig, ax = visualize_trajectory_2d(T_t_,filename,True) \n plt.show()\n plt.waitforbuttonpress()\n plt.close() \n \n#%%\n \n # (b) Landmark Mapping via EKF Update\n # Prepare for known information\n oTi = cam_T_imu\n fsu = K[0,0]\n fsv = K[1,1] \n cu = K[0,2]\n cv = K[1,2] \n M = np.zeros((4,4))\n M[0:2,0:3] = K[0:2,0:3]\n M[2: ,0:3] = K[0:2,0:3] \n M[2,-1] = -1 * K[0,0] * b\n M_dis = np.zeros((3,4))\n M_dis[0:2,0:3] = K[0:2,0:3]\n M_dis[-1,-1] = K[0,0] * b\n lm = features.shape[1]\n D_ = np.zeros((4,3))\n D_[0:3,:] = np.eye(3) \n D = np.zeros((4*lm,3*lm)) \n for i in range(lm):\n D[(4*i):(4*i+4),(3*i):(3*i+3)] = D_ \n\n # Initialization of Mean & Covariance matrix\n mu2_t = np.zeros((4,lm,t_size))\n fetur_dis = np.zeros((3,1))\n for i in range(lm):\n for j in range(t_size):\n if ~(features[0,i,j] == -1 and \\\n features[1,i,j] == -1 and \\\n features[2,i,j] == -1 and \\\n features[3,i,j] == -1):\n uL = features[0,i,j]\n vL = features[1,i,j]\n uR = features[2,i,j]\n vR = features[3,i,j] \n z_z = (fsu*b)/(uL-uR)\n x_z = z_z * ((uL-cu)/(fsu))\n y_z = z_z * ((vL-cv)/(fsv))\n X = np.array([x_z,y_z,z_z,1]).T\n \n mu2_tmp = np.linalg.inv(T_t[:,:,j]) @ \\\n np.linalg.inv(oTi) @ \\\n X\n \n mu2_t[:,i,0] = mu2_tmp \n break\n \n sclr = 1\n Sigma2_t = np.zeros((3*lm,3*lm,t_size))\n for i in range(t_size):\n Sigma2_t[:,:,i] = sclr*np.eye(3*lm)\n \n # observed features corresponds to landmarks \n Nt = np.zeros(t_size)\n corrs = np.zeros((t_size,lm))\n for j in range(t_size):\n for i in range(lm):\n if ~(features[0,i,j] == -1 and \\\n features[1,i,j] == -1 and \\\n features[2,i,j] == -1 and \\\n features[3,i,j] == -1):\n corrs[j,Nt[j].astype(int)] = i \n Nt[j] += 1\n \n # Update step\n for k in range(t_size-1): \n Ntk = Nt[k].astype(int)\n H_t = np.zeros((4*Ntk,3*lm))\n z = np.zeros((4,Ntk))\n z_hat = np.zeros((4,Ntk))\n V = np.eye(4*Ntk)\n for i in range(Ntk):\n l = corrs[k,i].astype(int)\n dq = deProjection(oTi @ T_t[:,:,k] @ mu2_t[:,l,k])\n H_t[(4*i):(4*i+4),(3*l):(3*l+3)] = M @ dq @ oTi @ \\\n T_t[:,:,k] @ D_\n z[:,i] = features[:,l,k]\n z_hat[:,i] = M @ Projection(oTi @ T_t[:,:,k] @ mu2_t[:,l,k])\n \n # Random noise for obervation model\n if filename == \"./data/0042.npz\":\n v_sclr = 500000\n if filename == \"./data/0027.npz\":\n v_sclr = 500\n if filename == \"./data/0020.npz\":\n v_sclr = 50 \n \n V = v_sclr * np.eye(4*Ntk)\n K1 = Sigma2_t[:,:,k] @ H_t.T\n K2 = H_t @ Sigma2_t[:,:,k] @ H_t.T\n K_t = K1 @ np.linalg.inv(K2 + V)\n \n mu2_k0 = mu2_t[:,:,k].T.reshape((4*lm,1)) \n z_apox = z - z_hat\n z_apox = z_apox.T.reshape((4*Ntk,1))\n mu2_k1 = mu2_k0 + D @ K_t @ z_apox\n mu2_t[:,:,k+1] = mu2_k1.reshape((lm,4)).T\n Sigma2_t[:,:,k+1] = (np.eye(3*lm)-(K_t @ H_t)) @ Sigma2_t[:,:,k]\n \n # Plot visual mappings of the landmarks\n fig, ax = visualize_trajectory_2d(T_t_,filename,True) \n s = 1 \n for k in range(t_size): \n Ntk = Nt[k].astype(int)\n landmark = np.zeros((2,Ntk,t_size))\n for i in range(Ntk):\n l = corrs[k,i].astype(int) \n landmark[0:2,i,k] = mu2_t[0:2,l,k]\n \n for i in range(landmark.shape[1]):\n s = 1\n ax.scatter(landmark[0,:,k],landmark[1,:,k],s=s,color=\"green\") \n plt.show()\n plt.waitforbuttonpress()\n plt.close() \n\n","sub_path":"EKF.py","file_name":"EKF.py","file_ext":"py","file_size_in_byte":5719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"217863427","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 20 17:03:43 2018\r\n\r\n@author: fzhan\r\n\"\"\"\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndata=pd.read_csv('CF_data.csv',index_col=0)\r\ndata0=pd.read_csv('yelp_business.csv')\r\ndata0=data0.iloc[:,[0,12]]\r\ndata1=data0[list(map(lambda x: 'Restaurants' in x,data0['categories']))]\r\ndata=data.merge(data1,on='business_id').iloc[:,:3]\r\n'''def present(idn,pref):\r\n d={}\r\n for i,idn in enumerate(idn):\r\n d[idn]=pref+str(i)\r\n return d'''\r\ndef present(idn):\r\n d={}\r\n for i,idn in enumerate(idn):\r\n d[idn]=i\r\n return d\r\nud=present(data['user_id'])\r\ndata['user_id']=list(map(lambda x: ud[x],data['user_id']))\r\nbd=present(data['business_id'])\r\ndata['business_id']=list(map(lambda x: bd[x],data['business_id']))\r\n\r\n#exploratory analysis\r\nuser_num=len(set(data['user_id']))\r\nbusiness_num=len(set(data['business_id']))\r\n\r\nbusiness_popu=data.iloc[:,:2].groupby('business_id').count()\r\nbusiness_popu.columns=['review_count']\r\nplt.hist(business_popu.iloc[:,0].tolist(),range=(0,400))\r\nuser_popu=data.iloc[:,:2].groupby('user_id').count()\r\nuser_popu.columns=['review_count']\r\nplt.hist(user_popu.iloc[:,0].tolist(),range=(0,40))\r\n\r\n#user just with less than two reviews as test data\r\ndata3=data.set_index('user_id')\r\ntestdata=data3[user_popu['review_count']<=2]\r\ntraindata=data3[user_popu['review_count']>2]\r\n\r\n#split \r\nfrom sklearn.model_selection import train_test_split\r\ntrain,validate=train_test_split(traindata, test_size=0.33,random_state=42,stratify=traindata.index)\r\n'''def transdf(data):\r\n d=pd.DataFrame(data)\r\n d['user_id']=data.index\r\n d.index=range(len(data))\r\n return d\r\ntrain_dist=transdf(train.iloc[:,0].groupby(train.index).count())\r\nvalidate_dist=transdf(validate.iloc[:,0].groupby(validate.index).count())\r\ndist=train_dist.merge(validate_dist,on='user_id',how='outer')\r\n'''\r\ntestdata.sort_index().to_csv('testdata.csv')\r\ntrain.sort_index().to_csv('train.csv')\r\nvalidate.sort_index().to_csv('validate.csv')\r\n\r\nbatch_size=500\r\n\r\nclass convertdata(object): \r\n def __init__(self, batch_size):\r\n train=pd.read_csv('train.csv',index_col=0)\r\n validate=pd.read_csv('validate.csv',index_col=0)\r\n \r\n \r\n users=sorted(list(set(train.index).union(set(validate.index))))\r\n nb_users=len(users)\r\n business=sorted(list(set(train['business_id']).union(set(validate['business_id']))))\r\n nb_business=len(business)\r\n dic=present(business)\r\n # Converting the data into an array with users in lines and movies in columns\r\n \r\n def convert(self,data,users,dic,nb_business,batch_size):\r\n for i,id_users in enumerate(users):\r\n U=[]\r\n id_business = data['business_id'][data.index == id_users]\r\n ind=list(map(lambda x:dic[x],id_business))\r\n #id_business = list(map(lambda x:business.index(x),l))\r\n id_ratings = data['stars'][data.index == id_users]\r\n ratings = np.zeros(nb_business)\r\n ratings[ind] = id_ratings\r\n if i%batch_size==0:\r\n if i!=0:\r\n yield np.array(U)\r\n U=[list(ratings)]\r\n else:\r\n U.append(list(ratings))\r\n\r\n \r\n self.train_set = self.convert(train,users,dic,nb_business,batch_size)\r\n self.val_set = self.convert(validate,users,dic,nb_business,batch_size)\r\n\r\n\r\n#def convert(data):\r\n# data=data.sort_index()\r\n# data['user_id']=data.index\r\n# data=data.set_index(['user_id','business_id'])\r\n# return data.unstack()\r\n\r\n#convert(train)\r\n \r\n \r\n\r\n","sub_path":"dataExploration.py","file_name":"dataExploration.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"41887850","text":"def pokemon_text(text):\n t=list(text)\n for i in t:\n if t.index(i)%2==0:\n t[t.index(i)]=i.upper()\n else:\n t[t.index(i)]=i.lower()\n return \"\".join(t)\n\nprint(pokemon_text(\"Mam dzisiaj wolne\"))\n# Zwróci MaM DzIsIaJ WoLnE","sub_path":"ex13.py","file_name":"ex13.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"331259445","text":"'''\ncreate data table based on query from substance property database\n'''\n\nfrom produce_data import main\n\nprop = 'log Kow'\ndf = main(prop)\ndf.dropna(axis = 0, inplace = True)\ndf = df[['SMILES', 'value']]\ndf.rename(columns = {'SMILES': 'smiles', 'value' : prop})\ndf.to_csv(r'validation_data\\SOLUTIONS_%s.csv' % prop)\n","sub_path":"data_query.py","file_name":"data_query.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"616640371","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Copyright (C) 2018 Jacek Łysiak\n MIT License\n\n Utilities\n\"\"\"\n\nimport argparse\n \ndef create_parser(parser_config, desc):\n parser = argparse.ArgumentParser(description=desc)\n subparsers = parser.add_subparsers(title=\"Actions\", description=\"Actions to perform\", dest=\"action\")\n for action, opts in parser_config.items():\n p = subparsers.add_parser(action, help=opts['help'])\n for op, kw in opts['opts']:\n p.add_argument('--' + op, **kw)\n for op, kw in opts['pos']:\n p.add_argument(op, **kw)\n return parser\n","sub_path":"nn4omtf/cli/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"274196100","text":"##############################################################################################################################################################################\r\n# This script parses the output file for the HEU #\r\n# critical experiment for Mo cross section validation. #\r\n##############################################################################################################################################################################\r\n# #\r\n# parse() flags: #\r\n# 1 - use for single output file #\r\n# 2 - use in optimization script to return max sensitivity in 10 eV - 100 keV #\r\n# 3 - use in optimization script to return keff #\r\n# #\r\n##############################################################################################################################################################################\r\n\r\nimport os\r\nimport argparse\r\nimport subprocess\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import ndimage\r\n\r\n# ==========================================================================> Main Parse Function <========================================================================= # \r\n \r\ndef Parse(fname, flag):\r\n\r\n # ========================================================================> Global Variables <========================================================================== # \r\n\r\n global isotopes # Global variable - list of molybdenum isotope masses\r\n global abundances # Global variable - list of Mo isotope abundances\r\n \r\n isotopes = ['92', '94', '95', '96', '97', '98', '100']\r\n abundances = [0.1453, 0.0915, 0.1584, 0.1667, 0.0960, 0.2439, 0.0982]\r\n\r\n # =================================================================> Extract Multiplication Factor <==================================================================== # \r\n\r\n def get_k(line): # Extracts mutliplication factor from output file\r\n return [float(line.split()[2]), float(line.split()[3])]\r\n\r\n # ==================================================================> Extract Kinetics Parameters <===================================================================== # \r\n\r\n def get_kinetics(i, lines): # Extracts kinetics parameters from output file\r\n return [float(lines[i].split()[2]), float(lines[i].split()[3])], [float(lines[i+1].split()[1]), float(lines[i+1].split()[2])], [float(lines[i+2].split()[1]), float(lines[i+2].split()[2])]\r\n \r\n # ===================================================================> Extract Fission Tally Data <===================================================================== # \r\n\r\n def get_tally(i, lines): # Extracts fission tally data from output file\r\n tally = []\r\n \r\n for j in range(i+3, 1000000):\r\n if lines[j] == '\\n':\r\n break\r\n else:\r\n tally.append(float(lines[j].split()[1]))\r\n \r\n return tally\r\n \r\n # ===============================================================> Extract Isotopic Sensitivity Data <================================================================== # \r\n \r\n def get_sensblocks(sensstart, sensend, lines): # Extracts individual isotope sensitivity data from\r\n sens, senserror, blocks = [], [], [] # output file\r\n \r\n senslines = [x for x in lines[sensstart:sensend] if x != ' \\n']\r\n headeridx = [senslines.index(y) for y in senslines if '.80c' in y]\r\n \r\n for i in range(0, len(headeridx)-1):\r\n blocks.append(senslines[headeridx[i]+2:headeridx[i+1]])\r\n \r\n for j in range(0, len(blocks)):\r\n tempsens, temperror = [], []\r\n for line in blocks[j]:\r\n tempsens.append(float(line.split()[2]))\r\n temperror.append(float(line.split()[3]))\r\n sens.append(tempsens)\r\n senserror.append(temperror)\r\n \r\n return sens, senserror\r\n \r\n # ===================================================> Calculate Fraction of Flux in Intermediate Energy Region <======================================================= # \r\n \r\n def calc_fluxfrac(): # Calculates the fraction of the flux in the\r\n try: # intermediate energy region\r\n data = pd.read_csv('meshtal_24', header=None, delim_whitespace=True, dtype=str)\r\n data.columns = ['Bin', 'x', 'y', 'z', 'Tally', 'Error']\r\n \r\n totalfluxdata = data[data.Bin == 'Total'].Tally.astype(float)\r\n thermalfluxdata = data[data.Bin == '1.000E-05'].Tally.astype(float)\r\n interfluxdata = data[data.Bin == '1.000E-01'].Tally.astype(float)\r\n fastfluxdata = data[data.Bin == '2.000E+01'].Tally.astype(float)\r\n \r\n tff = sum(thermalfluxdata)/sum(totalfluxdata)\r\n iff = sum(interfluxdata)/sum(totalfluxdata)\r\n fff = sum(fastfluxdata)/sum(totalfluxdata)\r\n \r\n return tff, iff, fff \r\n except:\r\n raise Exception('meshtal file not found!')\r\n \r\n # =================================================> Calculate Fraction of Fissions in Intermediate Energy Region <===================================================== # \r\n \r\n def calc_tallyfrac(tally): # Calculates the fraction of fissions occuring in the \r\n tff = tally[0]/tally[-1]\r\n iff = tally[1]/tally[-1]\r\n fff = tally[2]/tally[-1]\r\n \r\n return tff, iff, fff\r\n \r\n # ===============================================> Calculate Natural XS Sensitivity in Intermediate Energy Region <===================================================== # \r\n \r\n def calc_naturalsens(sens, error): # Calculates the system sensitivity to natural isotopic\r\n absoluteerror = np.zeros_like(error) # molybdenum cross sections\r\n \r\n for i in range(0, len(error)):\r\n for j in range(0, len(error[i])):\r\n absoluteerror[i][j] = float(sens[i][j]) * float(error[i][j])\r\n \r\n naturalsens, temperror = np.zeros_like(sens[0]), np.zeros_like(absoluteerror[0])\r\n \r\n for k in range(0, len(sens)):\r\n naturalsens += abundances[k]*np.array(sens[k])\r\n \r\n for l in range(0, len(abundances)):\r\n for m in range(0, len(absoluteerror)):\r\n temperror += (abundances[l]**2)*(np.array(absoluteerror[m])**2)\r\n \r\n naturalerror = temperror**0.5\r\n \r\n return naturalsens, naturalerror\r\n \r\n # ===========================================> Calculate Maximum Isotopic XS Sensitivity in Intermediate Energy Region <================================================ # \r\n \r\n def calc_sensmax(sens): # Calculates the maximum intermediate energy sensitivity\r\n maxsens = max(abs(sens))\r\n return maxsens\r\n \r\n # =======================================================================> Plot Sensitivity <=========================================================================== # \r\n\r\n def plot_sensitivity(sens, error): # Plot sensitivity as a function of energy \r\n bins = np.logspace(-5, -1, 202)\r\n naturalsens, naturalerror = [], []\r\n \r\n for i in range(0, len(sens)):\r\n naturalsens.append(calc_naturalsens(sens[i], error[i])[0])\r\n naturalerror.append(calc_naturalsens(sens[i], error[i])[1])\r\n \r\n fig, ax = plt.subplots()\r\n \r\n for j in range(0, len(naturalsens)):\r\n if j == 0:\r\n label = 'Capture'\r\n elif j == 1:\r\n label = 'Elastic Scattering'\r\n \r\n ax.step(bins[:-1], naturalsens[j], where='post', label=label)\r\n \r\n ax.set_title('Natural Isotopic Molybdenum Cross Section Sensitivity', y=1.025)\r\n ax.set_ylabel('Sensitivity')\r\n ax.set_xlabel('Energy [MeV]')\r\n ax.set_xscale('log')\r\n ax.legend()\r\n ax.grid()\r\n \r\n return ax\r\n \r\n # ======================================================================> Split meshtal File <========================================================================== #\r\n\r\n def split_meshtal():\r\n with open('meshtal') as ofile:\r\n lines = ofile.readlines()\r\n \r\n startidx = []\r\n \r\n for i in range(0, len(lines)):\r\n if 'Mesh Tally Number' in lines[i]:\r\n startidx.append(i)\r\n \r\n for flag in ['24', '34', '44']:\r\n with open('meshtal_' + flag, 'w') as wfile:\r\n if flag == '24':\r\n writelines = lines[startidx[0]+11:startidx[1]-1]\r\n elif flag == '34':\r\n writelines = lines[startidx[1]+11:startidx[2]-1]\r\n elif flag == '44':\r\n writelines = lines[startidx[2]+11:-1]\r\n \r\n for j in range(0, len(writelines)):\r\n wfile.write(writelines[j])\r\n \r\n def remove_meshtal():\r\n for flag in ['24', '34', '44']:\r\n try:\r\n os.remove(os.getcwd() + '\\\\' + 'meshtal_' + flag)\r\n except OSError:\r\n pass\r\n \r\n # =======================================================================> Plot Fmesh Tally <=========================================================================== #\r\n \r\n def plot_fmesh(flag):\r\n \r\n if flag == '24':\r\n axes = []\r\n binnums = [3,2,1]\r\n \r\n for bin in binnums:\r\n with open('commands.txt', 'w') as wfile:\r\n wfile.write('FMESH 24\\nBASIS 0 1 0 0 0 1\\nEBIN {0}\\nFILE\\nEND\\nEND'.format(bin))\r\n \r\n with open('Fmeshplot.bat', 'w') as wfile:\r\n wfile.write('FOR %%a IN (*.inp.r) do (\\n')\r\n wfile.write(' start /b /low /wait C:\\MCNP\\MCNP_CODE\\\\bin\\mcnp611.exe z RUNTPE=%%a COM=commands.txt )\\n')\r\n wfile.write('gswin64c -o FMESH{0}.png -sDEVICE=pngalpha plotm.ps'.format(bin))\r\n \r\n p1 = subprocess.Popen('env.bat', cwd=os.getcwd())\r\n stdout, stderr = p1.communicate()\r\n \r\n p2 = subprocess.Popen(\"Fmeshplot.bat\", cwd=os.getcwd())\r\n stdout, stderr = p2.communicate()\r\n \r\n img = ndimage.imread('FMESH{0}.png'.format(bin))\r\n rotated = ndimage.rotate(img, 270)\r\n \r\n fig, ax = plt.subplots()\r\n \r\n if bin == 1:\r\n title = 'Thermal (0 - 10 eV) Flux Shape'\r\n elif bin == 2:\r\n title = 'Intermediate (10 eV - 100 keV) Flux Shape'\r\n else:\r\n title = 'Fast (100 keV - 20 MeV) Flux Shape'\r\n \r\n ax.imshow(rotated)\r\n ax.set_title(title)\r\n ax.axis('off')\r\n \r\n delfiles = ['comout', 'outp', 'FMESH{0}.png'.format(bin), 'plotm.ps', 'commands.txt', 'Fmeshplot.bat']\r\n for file in delfiles:\r\n try:\r\n os.remove(os.getcwd() + '\\\\' + file)\r\n except OSError:\r\n pass\r\n \r\n axes.append(ax)\r\n \r\n return axes\r\n \r\n elif flag == '34' or flag == '44':\r\n \r\n data = pd.read_csv('meshtal_' + flag, header=None, delim_whitespace=True)\r\n data.columns = ['Energy', 'R', 'Z', 'Theta', 'Tally', 'Error']\r\n data = data[data.Energy != 'Total']\r\n \r\n thermal = data[data.Energy == '1.000E-05']\r\n inter = data[data.Energy == '1.000E-01']\r\n fast = data[data.Energy == '2.000E+01']\r\n \r\n fig, ax = plt.subplots()\r\n \r\n if flag == '34':\r\n ax.plot(thermal.R, thermal.Tally, label='Thermal', color = 'r')\r\n ax.plot(inter.R, inter.Tally, label='Intermediate', color = 'g')\r\n ax.plot(fast.R, fast.Tally, label='Fast', color = 'b')\r\n ax.set_title('Radial Grouped Flux Profile')\r\n ax.set_ylabel('Flux')\r\n ax.set_xlabel('Radial Position [cm]')\r\n elif flag == '44':\r\n ax.plot(thermal.Z, thermal.Tally, label='Thermal', color='r')\r\n ax.plot(inter.Z, inter.Tally, label='Intermediate', color='g')\r\n ax.plot(fast.Z, fast.Tally, label='Fast', color='b')\r\n ax.set_title('Axial Grouped Flux Profile')\r\n ax.set_ylabel('Flux')\r\n ax.set_xlabel('Axial Position Relative to Bottom [cm]')\r\n \r\n ax.grid()\r\n ax.legend()\r\n \r\n return ax\r\n \r\n # =========================================================> Calculate Stationary and Mobile Unit Weights <============================================================= #\r\n # Stationary unit weight - weight of stationary unit cells + reflector\r\n # Mobile unit weight - weight of mobile unit cells\r\n \r\n def calc_weights(lines):\r\n Inventory = {'solid':5, '2.5':7, '6':7}\r\n UsedPlates = {'solid':0, '2.5':0, '6':0}\r\n UpperPlateTypes = ['solid', '2.5', '6']\r\n LowerPlateTypes = ['2.5', '6']\r\n FuelThick = 0.29972\r\n FuelDen = 18.8525\r\n MolyDen = 10.22\r\n \r\n for i in range(0, len(lines)):\r\n if 'Moderator Thickness' in lines[i]:\r\n ModThick = float(lines[i].split()[5])\r\n elif 'Moderator Density' in lines[i]:\r\n ModDen = -1*float(lines[i].split()[5])\r\n elif 'Molybdenum Thickness' in lines[i]:\r\n MolyThick = float(lines[i].split()[5])\r\n elif 'Reflector Density' in lines[i]:\r\n RefDen = -1*float(lines[i].split()[5])\r\n elif 'Number of Moderator' in lines[i]:\r\n ModNum = int(lines[i].split()[10])\r\n elif 'Number of Fuel' in lines[i]:\r\n FuelNum = int(lines[i].split()[10])\r\n elif 'Number of Molybdenum' in lines[i]:\r\n MolyNum = int(lines[i].split()[10])\r\n elif 'Number of Top' in lines[i]:\r\n TopUnits = int(lines[i].split()[7])\r\n elif 'Number of Bottom' in lines[i]:\r\n BotUnits = int(lines[i].split()[7])\r\n elif 'Corner Reflector Bottom' in lines[i]:\r\n CRBot = float(lines[i].split()[6])\r\n elif 'Corner Reflector Top' in lines[i]:\r\n CRTop = float(lines[i].split()[6])\r\n \r\n def calc_plate_weight(loc, type, hole, den, thick):\r\n OuterR = 26.67\r\n \r\n if loc == 'bottom' and type != 'fuel':\r\n InnerR = (2.48/2)*2.54\r\n elif loc == 'top' and type != 'fuel':\r\n InnerR = 0\r\n else:\r\n if hole == 'solid':\r\n InnerR = 0\r\n elif hole == '2.5':\r\n InnerR = (2.5/2) * 2.54\r\n elif hole == '6':\r\n InnerR = (6/2) * 2.54\r\n \r\n V = np.pi*thick*(OuterR**2 - InnerR**2)\r\n m = den * V\r\n return m\r\n \r\n def calc_ref_weight(den, CRBot, CRTop):\r\n \r\n TopRefV = ((22*22*5.68) - np.pi*((0.25/2)**2)*5.68)*(2.54**3)\r\n BotRefV = np.pi*(10.5**2 - 1.24**2)*5.68 *(2.54**3)\r\n SideRefV = ((34.76*34.76*48.78) - (22*22*48.78)) * (2.54**3)\r\n CRefV = ((22*22*((CRTop-CRBot)/2.54))-(np.pi*10.5*2*((CRTop-CRBot)/2.54))) * (2.54**3)\r\n \r\n TotalV = TopRefV + BotRefV + SideRefV + CRefV\r\n\r\n m = den*TotalV\r\n return m\r\n \r\n TopFuelWt = 0\r\n BotFuelWt = 0\r\n \r\n for type in UpperPlateTypes:\r\n if Inventory[type] < UsedPlates[type]:\r\n TopFuelWt += calc_plate_weight('top', 'fuel', type, FuelDen, FuelThick) * FuelNum\r\n else:\r\n pass\r\n \r\n for type in LowerPlateTypes:\r\n if Inventory[type] < UsedPlates[type]:\r\n BotFuelWt += calc_plate_weight('bottom', 'fuel', type, FuelDen, FuelThick) * FuelNum\r\n else:\r\n pass\r\n \r\n TopModWt = calc_plate_weight('top', 'mod', 'solid', ModDen, ModThick) * ModNum\r\n TopMolyWt = calc_plate_weight('top', 'moly', 'solid', MolyDen, MolyThick) * MolyNum\r\n TopUCellWt = TopFuelWt + TopModWt + TopMolyWt\r\n \r\n BotModWt = calc_plate_weight('bottom', 'mod', 'solid', ModDen, ModThick) * ModNum\r\n BotMolyWt = calc_plate_weight('bottom', 'moly', 'solid', MolyDen, MolyThick) * MolyNum\r\n BotUCellWt = BotFuelWt + BotModWt + BotMolyWt\r\n \r\n RefWt = calc_ref_weight(RefDen, CRBot, CRTop)\r\n \r\n StatWeight = (TopUnits*TopUCellWt + RefWt) * (1/453.592)\r\n MobWeight = (BotUnits*BotUCellWt) * (1/453.592)\r\n \r\n return StatWeight, MobWeight\r\n\r\n # =====================================================================> Check Tally Statistics <======================================================================= # \r\n \r\n def check_tallies(line): # Checks if the tallies passed all statistical checks\r\n checklist = line.split()[1:]\r\n \r\n if 'no' in checklist:\r\n return False\r\n else:\r\n return True\r\n \r\n # ======================================================================> Write Run Summary <=========================================================================== # \r\n \r\n def write_summary(data): # Writes the run summary\r\n \r\n def align(line):\r\n while len(line) < 78:\r\n line += ' ' \r\n line += '#'\r\n return line \r\n \r\n print('\\n')\r\n print('###############################################################################')\r\n print('# #')\r\n print('# ==============================> RUN SUMMARY <============================== #')\r\n print('# #')\r\n print('###############################################################################')\r\n print('# #')\r\n print('# This summary provides detailed information concerning the run, namely the #')\r\n print('# system eigenvalues and kinetics paramters as well as the fraction of the #')\r\n print('# flux and fission rate occuring in the intermediate (10 eV - 100 keV) range #')\r\n print('# #')\r\n print('###############################################################################')\r\n print('# #')\r\n print(align('# Multiplication Factor: {0} +/- {1}'.format(data['keff'][0], data['keff'][1])))\r\n print(align('# Mean Generation Time: {0} +/- {1} [ns]'.format(data['gt'][0], data['gt'][1])))\r\n print(align('# Rossi-Alpha Eigenvalue: {0} +/- {1} [/ns]'.format(data['ra'][0], data['ra'][1])))\r\n print(align('# Effective Delayed Neutron Fraction: {0} +/- {1}'.format(data['beff'][0], data['beff'][1])))\r\n print('# #')\r\n print(align('# Fraction of flux between 0 and 10 eV: {0}'.format(round(data['thermalfluxfrac'], 5))))\r\n print(align('# Fraction of flux between 10 eV and 100 keV: {0}'.format(round(data['interfluxfrac'], 5))))\r\n print(align('# Fraction of flux between 100 keV and 20 MeV: {0}'.format(round(data['fastfluxfrac'], 5))))\r\n print('# #')\r\n print(align('# Fraction of fissions between 0 and 10 eV: {0}'.format(round(data['thermalfissionfrac'], 5))))\r\n print(align('# Fraction of fissions between 10 eV and 100 keV: {0}'.format(round(data['interfissionfrac'], 5))))\r\n print(align('# Fraction of fissions between 100 keV and 20 MeV: {0}'.format(round(data['fastfissionfrac'], 5))))\r\n print('# #')\r\n print(align('# Intermediate Molybdenum Capture Rate: {0}'.format(round(data['mocaprate'], 5))))\r\n print('# #')\r\n print(align('# Maximum Mo capture sensitivity: {0}'.format(round(data['capturesensmax'], 5))))\r\n print(align('# Maximum Mo elastic scattering sensitivity: {0}'.format(round(data['escattersensmax'], 5))))\r\n print('# #')\r\n print(align('# Weight of stationary portion: {0}'.format(round(data['statweight'], 0))))\r\n print(align('# Weight of mobile portion: {0}'.format(round(data['mobweight'],0))))\r\n print('# #')\r\n print(align('# Source entropy converged? {0}'.format(data['converged'])))\r\n print(align('# Tallies met statistical checks? {0}'.format(data['checklist'])))\r\n print('# #')\r\n print('###############################################################################')\r\n \r\n # =========================================================================> Parse Output <============================================================================= # \r\n \r\n def parse_output(lines, flag): # Parses the output file and returns necessary data,\r\n font = {'size':18} # if applicable\r\n mpl.rc('font', **font) # Flag = 1: Write summary, plot tallies and\r\n mpl.rcParams['figure.figsize'] = 9, 7 # sensitivity\r\n # Flag = 2: Returns optimization design variables\r\n data = {} \r\n checklist, sensidx, sens, senserror = [], [], [], [] \r\n tallynum = 1\r\n converged = False\r\n\r\n for i in range(0, len(lines)):\r\n\r\n if 'final result' in lines[i]:\r\n data['keff'] = get_k(lines[i])\r\n \r\n if 'gen. time' in lines[i]:\r\n data['gt'], data['ra'], data['beff'] = get_kinetics(i, lines)\r\n\r\n if 'cell union total' in lines[i]:\r\n if tallynum == 1:\r\n ft = get_tally(i, lines)\r\n tallynum += 1\r\n else:\r\n mot = get_tally(i, lines)\r\n \r\n if 'passed?' in lines[i]:\r\n checklist.append(check_tallies(lines[i]))\r\n \r\n if 'Source entropy convergence check passed' in lines[i]:\r\n converged = True\r\n \r\n if 'sensitivity profile' in lines[i]:\r\n sensidx.append(i)\r\n if '1average' in lines[i]:\r\n sensidx.append(i)\r\n \r\n if False in checklist:\r\n data['checklist'] = 'No'\r\n else:\r\n data['checklist'] = 'Yes'\r\n \r\n if converged == True:\r\n data['converged'] = 'Yes'\r\n else:\r\n data['converged'] = 'No'\r\n \r\n for j in range(0, len(sensidx)-1):\r\n sens.append(get_sensblocks(sensidx[j], sensidx[j+1], lines)[0])\r\n senserror.append(get_sensblocks(sensidx[j], sensidx[j+1], lines)[1])\r\n \r\n data['thermalfissionfrac'], data['interfissionfrac'], data['fastfissionfrac'] = calc_tallyfrac(ft)\r\n data['capturesensmax'] = calc_sensmax(calc_naturalsens(sens[0], senserror[0])[0])\r\n data['escattersensmax'] = calc_sensmax(calc_naturalsens(sens[1], senserror[1])[0]) \r\n data['statweight'], data['mobweight'] = calc_weights(lines)\r\n \r\n if flag == 1:\r\n split_meshtal()\r\n data['thermalfluxfrac'], data['interfluxfrac'], data['fastfluxfrac'] = calc_fluxfrac()\r\n data['mocaprate'] = mot[1]\r\n ax456 = plot_fmesh('24')\r\n ax4, ax5, ax6 = ax456[0], ax456[1], ax456[2]\r\n ax3 = plot_fmesh('44')\r\n ax2 = plot_fmesh('34')\r\n ax1 = plot_sensitivity(sens, senserror)\r\n write_summary(data) \r\n remove_meshtal()\r\n plt.show()\r\n elif flag == 2:\r\n passed = True\r\n if data['statweight'] > 20000:\r\n passed = False\r\n if data['mobweight'] > 2000:\r\n passed = False\r\n if (data['keff'][0] - data['keff'][1]) < 1 or (data['keff'][0] + data['keff'][1]) > (1 + 0.8*data['beff']):\r\n passed = False\r\n if data['interfissionfrac'] != max([data['thermalfissionfrac'], data['interfissionfrac'], data['fastfissionfrac']]):\r\n passed = False\r\n return data['capturesensmax'], data['escattersensmax'], passed \r\n else:\r\n raise Exception('Incorrect flag specification')\r\n \r\n # ===============================================================================> Run <================================================================================ # \r\n \r\n with open(fname) as ofile:\r\n lines = ofile.readlines()\r\n \r\n output = parse_output(lines, flag)\r\n if output == None:\r\n pass\r\n else:\r\n return output\r\n \r\nif __name__ == \"__main__\":\r\n\r\n parser = argparse.ArgumentParser(description = 'Parse MCNP Output File')\r\n parser.add_argument('fname', help = 'Output File Name', metavar = '')\r\n args = parser.parse_args()\r\n \r\n Parse(args.fname, 1)","sub_path":"Parse_Output.py","file_name":"Parse_Output.py","file_ext":"py","file_size_in_byte":29759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"488334791","text":"import re\nfrom collections import defaultdict\n\nfrom .dataloader import *\nfrom . import en\nfrom .formulas import JST\n\n# chains\ndef discover_evolutionary_chains(card_list):\n chains = bucketize(lambda x: x.series_id, [\n card_list[key] for key in card_list])\n\n chain_by_card = {}\n for chain in chains:\n for card in chains[chain]:\n chain_by_card[card.id] = chain\n chains[chain] = order_chain(chains[chain])\n\n return chains, chain_by_card\n\n\ndef bucketize(key, a_list):\n ret = defaultdict(lambda: [])\n\n for item in a_list:\n ret[key(item)].append(item)\n\n return ret\n\n\ndef order_chain(chain):\n new_chain = [next(filter(lambda x: x.evolution_id == 0, chain))]\n chain.remove(new_chain[0])\n\n while chain:\n for card in chain:\n if card.evolution_id == new_chain[-1].id:\n break\n else:\n raise ValueError(\n \"Invalid chain group: could not find a card with evolution_id of {0}\".format(new_chain[-1].id))\n chain.remove(card)\n new_chain.append(card)\n\n new_chain.reverse()\n return new_chain\n\n\ndef pick_random_card_of_chara(self, chara):\n return random.choice(list(filter(lambda x: card_db[x].chara_id == chara, card_db)))\n\n# needed arks\nTITLE_ONLY_REGEX = r\"^[(.+)]\"\nNAME_ONLY_REGEX = r\"^(?:[.+])?(.+)$\"\n\ncard_comments = list(csvloader.load_db_file(ark_data_path(\"card_comments.csv\")))\ncard_va_by_object_id = lambda x: filter(lambda y: y.id == x, card_comments)\n\nnames = cached_keyed_db(private_data_path(\"names.csv\"))\nskills = csvloader.load_keyed_db_file(ark_data_path(\"skill_data.csv\"))\nlead_skills = csvloader.load_keyed_db_file(ark_data_path(\"leader_skill_data.csv\"))\nrarity_dep = csvloader.load_keyed_db_file(ark_data_path(\"card_rarity.csv\"))\n\nchara_db = csvloader.load_keyed_db_file(ark_data_path(\"chara_data.csv\"),\n kanji_spaced=lambda obj: names.get(obj.chara_id).kanji_spaced,\n kana_spaced=lambda obj: names.get(obj.chara_id).kana_spaced,\n conventional=lambda obj: names.get(obj.chara_id).conventional,\n valist=lambda obj: list(card_va_by_object_id(obj.chara_id)))\ncard_db = csvloader.load_keyed_db_file(ark_data_path(\"card_data.csv\"),\n chara=lambda obj: chara_db.get(obj.chara_id),\n has_spread=lambda obj: obj.rarity > 4,\n name_only=lambda obj: re.match(NAME_ONLY_REGEX, obj.name).group(1),\n title=lambda obj: re.match(TITLE_ONLY_REGEX, obj.name).group(1) if obj.title_flag else None,\n skill=lambda obj: skills.get(obj.skill_id),\n lead_skill=lambda obj: lead_skills.get(obj.leader_skill_id),\n rarity_dep=lambda obj: rarity_dep.get(obj.rarity),\n overall_min=lambda obj: obj.vocal_min + obj.dance_min + obj.visual_min,\n overall_max=lambda obj: obj.vocal_max + obj.dance_max + obj.visual_max,\n valist=lambda obj: list(card_va_by_object_id(obj.id)))\nevolutionary_chains, chains_by_card = discover_evolutionary_chains(card_db)\n","sub_path":"starlight/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"515296680","text":"import os, sys, socket\n\ndef servidor():\n\n\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\n\n\ts.bind(('',1200))\n\ts.listen(5)\n\tprint('\\nServidor escuchando peticiones\\n')\t\n\n\twhile True:\n\t\tnueva_s, direccion = s.accept()\n\n\t\tpeticion_codificada = nueva_s.recv(512)\n\t\tpeticion = peticion_codificada.decode('utf8')\n\t\n\t\tip = direccion[0]\n\t\tprint('La peticion llega por la ip %s'%ip)\n\t\t\n\t\tif peticion == 'Frase':\n\t\t\tprint('\\nServidor comprobando frase\\n')\n\t\t\tenunciado = 'Frase que quieres comprobar'\n\t\t\tenunciado_cod = enunciado.encode('utf8')\n\t\t\tnueva_s.send(enunciado_cod)\n\n\t\t\tfrase_cod = nueva_s.recv(4096)\n\t\t\tfrase = frase_cod.decode('utf8')\n\n\t\t\tif str(frase) == str(frase)[::-1]:\n\t\t\t\trespuesta = 'Si es palindroma'\n\t\t\t\trespuesta_cod = respuesta.encode('utf8')\n\t\t\t\tnueva_s.send(respuesta_cod)\n\n\t\t\telse:\n\t\t\t\trespuesta = 'No es palindroma'\n\t\t\t\trespuesta_cod = respuesta.encode('utf8')\n\t\t\t\tnueva_s.send(respuesta_cod)\n\n\t\telif peticion == 'NumeroNatural':\n\t\t\tprint('\\nServidor comprobando numero\\n')\n\t\t\tenunciado = 'Numero natural que quieres comprobar'\n\t\t\tenunciado_cod = enunciado.encode('utf8')\n\t\t\tnueva_s.send(enunciado_cod)\n\n\t\t\tnumero_cod = nueva_s.recv(1024)\n\t\t\tnumero = numero_cod.decode('utf8')\n\t\t\tif str(numero) == str(numero)[::-1]:\n\t\t\t\trespuesta = 'Si es palindromo'\n\t\t\t\trespuesta_cod = respuesta.encode('utf8')\n\t\t\t\tnueva_s.send(respuesta_cod)\n\t\t\telse:\n\t\t\t\trespuesta = 'No es palindromo'\n\t\t\t\trespuesta_cod = respuesta.encode('utf8')\n\t\t\t\tnueva_s.send(respuesta_cod)\n\t\t\t\t\n\t\tprint('\\nEl servidor ha hecho su trabajo\\nEsperando nueva orden\\n')\n\n\tnueva_s.close()\n\nservidor()\n\n\n\n\n\n\n\n\n","sub_path":"practicas/fra/palindromas TCP/serv.py","file_name":"serv.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"466463015","text":"import os\nimport argparse\nimport dlr\nimport cv2\nimport numpy as np\nfrom dlr import DLRModel\nimport config_utils\nimport time\nfrom utils import load_model, load_image, preprocess_image, predict, publish_msg, gstreamer_pipeline\n\n\ndef show_camera(model, args):\n gstreamer = gstreamer_pipeline(\n capture_width=args.width, capture_height=args.height, \n display_width=args.width, display_height=args.height\n )\n print(gstreamer)\n cap = cv2.VideoCapture(gstreamer, cv2.CAP_GSTREAMER)\n\n if cap.isOpened():\n window_handle = cv2.namedWindow(\"CSI Camera\", cv2.WINDOW_AUTOSIZE)\n # Window\n prev_t = 0 \n while cv2.getWindowProperty(\"CSI Camera\", 0) >= 0:\n ret_val, img = cap.read()\n\n # Prediction\n img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n pred_class, pred_str, prob, msg = predict(img_rgb, model)\n\n # Compute FPS\n curr_t = time.time()\n fps = 1./(curr_t - prev_t)\n prev_t = curr_t\n\n # Show results\n put_msg = f'{msg}, fps={fps:.2f}'\n font = cv2.FONT_HERSHEY_COMPLEX \n cv2.putText(img, put_msg, (30,40), font, 1, (150,255,0), 2, cv2.LINE_AA)\n cv2.imshow(\"CSI Camera\", img)\n\n # Stop the program on the ESC key\n keyCode = cv2.waitKey(1) & 0xFF\n if keyCode == 27:\n break\n cap.release()\n cv2.destroyAllWindows()\n else:\n print(\"Unable to open camera...\")\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description='AIoT Demo')\n parser.add_argument('--width', \n default=1280, type=int,\n help='Camera width (default: 1280')\n parser.add_argument('--height', \n default=720, type=int,\n help='Camera height (default: 720')\n\n args = parser.parse_args()\n config_utils.logger.info(args) \n\n if config_utils.USE_GPU:\n model = load_model(model_dir='model_gpu', device='gpu')\n else:\n model = load_model(model_dir='model_cpu', device='cpu') \n \n show_camera(model, args)\n","sub_path":"ggv2-deploy-on-device/artifacts/test_camera_dlr.py","file_name":"test_camera_dlr.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"91761633","text":"# -*- coding: utf-8 -*-\n#/#############################################################################\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 datetime import datetime\nfrom lxml import etree\nimport math\nimport pytz\nimport urlparse\n\nimport openerp\nfrom openerp import tools,api\nfrom openerp.osv import osv, fields\nfrom openerp.osv.expression import get_unaccent_wrapper\nfrom openerp.tools.translate import _\n\nclass humanity_people(osv.Model):\n _name = 'humanity.people'\n _description = \"Fiche signalétique\"\n _inherit = ['mail.thread', 'ir.needaction_mixin']\n\n _mail_post_access = 'read'\n\n _track = {\n 'user_id': {\n # this is only an heuristics; depending on your particular stage configuration it may not match all 'new' stages\n 'humanity.mt_log_new': lambda self, cr, uid, obj, ctx=None: obj.user_id,\n 'humanity.mt_humanity_log_new': lambda self, cr, uid, obj, ctx=None: obj.user_id\n }\n }\n\n def name_get(self, cr, uid, ids, context={}):\n res=[]\n\n for emp in self.browse(cr, uid, ids,context=context):\n res.append((emp.id, emp.Main_LastName + ', ' + emp.Main_FirstName)) \n return res\n\n def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):\n if not args:\n args = []\n if not context:\n context = {}\n if name:\n # Be sure name_search is symetric to name_get\n ids = self.search(cr, uid, ['|',('Main_LastName', operator, name),('Main_FirstName', operator, name)] + args, limit=limit, context=context)\n else:\n ids = self.search(cr, uid, args, limit=limit, context=context)\n return self.name_get(cr, uid, ids, context)\n\n def _get_image(self, cr, uid, ids, name, args, context=None):\n result = dict.fromkeys(ids, False)\n for obj in self.browse(cr, uid, ids, context=context):\n result[obj.id] = tools.image_get_resized_images(obj.image, avoid_resize_medium=True)\n return result\n\n # Ajouter une image\n def _set_image(self, cr, uid, id, name, value, args, context=None):\n return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)\n\n # Compte les feuilles de route pour le boutton smart\n def _log_count(self, cr, uid, ids, field_name, arg, context=None):\n res = dict(map(lambda x: (x,0), ids))\n\n try:\n for people in self.browse(cr, uid, ids, context):\n res[people.id] = len(people.log_ids)\n except:\n pass\n return res\n\n # Compte les projets pour le boutton smart\n def _project_count(self, cr, uid, ids, field_name, arg, context=None):\n res = dict(map(lambda x: (x,0), ids))\n\n try:\n for people in self.browse(cr, uid, ids, context):\n res[people.id] = len(people.project_ids)\n except:\n pass\n return res\n\n # Compte les lettres pour le boutton smart\n def _letter_count(self, cr, uid, ids, field_name, arg, context=None):\n res = dict(map(lambda x: (x,0), ids))\n\n try:\n for people in self.browse(cr, uid, ids, context):\n res[people.id] = len(people.letter_ids)\n except:\n pass\n return res\n\n _columns = {\n\n # Champs sytèmes\n 'id': fields.integer('ID', readonly=True), \n 'user_ids': fields.one2many('res.users', 'partner_id', 'Users'),\n 'log_count': fields.function(_log_count, string='# de feuille de route', type='integer'),\n 'letter_count': fields.function(_letter_count, string='# de lettres', type='integer'),\n 'project_count': fields.function(_project_count, string='# de projets', type='integer'),\n 'log_ids': fields.one2many('humanity.log','people_id','Dossier'),\n 'letter_ids': fields.one2many('humanity.letter','people_id','Lettres'),\n 'project_ids': fields.one2many('project.project','people_id','Projets'),\n\n # 1 Données de base de la personne prise en charge\n \t'Main_Actif' : fields.boolean(string='Actif'),\n 'Main_FileNumber': fields.char(string='No de dossier'),\n 'Main_ImageDate': fields.date(string='Date de la photo'),\n 'Main_LastName': fields.char(string='Nom de famille', required=True, track_visibility='onchange'),\n 'Main_FirstName': fields.char(string='Prénom', required=True),\n 'Main_Genre': fields.selection([('m', 'Masculin'), ('f', 'Féminin'), ], string='Genre'),\n 'Main_Birthday': fields.date(string='Date de naissance'),\n 'Main_Nationality': fields.char(string='Nationnalité'),\n 'Main_Department': fields.char(string='Département'),\n 'Main_Language': fields.char(string='Langue'),\n 'program_id': fields.many2one('humanity.program', string='Programme', ondelete='restrict'), \n 'country_id': fields.many2one('res.country', string='Pays', ondelete='restrict'), \n 'Main_Decision': fields.selection([('1', 'Pas besoin de suivi'),\n ('2', 'Visite trimestrielle'),\n ('3', 'Visite semetrielle') ,\n ('4', 'Visite annuelle'),\n ('5', 'Recontacter la personne si opération possible')], string='Decision',), \n\n # 2 Filiation\n 'Filiation_FatherName': fields.char(string='Nom/Prénom du père'), \n 'Filiation_FatherBirthday': fields.date(string='Anniversaire du père'), \n 'Filiation_FatherAddress': fields.char(string='Adresse du père'), \n 'Filiation_FatherPhone': fields.char(string='Téléphone du père'), \n 'Filiation_FatherActivity': fields.char(string='Activité actuelle du père'), \n 'Filiation_FatherIncome': fields.char(string='Revenu du père'), \n 'Filiation_MotherName': fields.char(string='Nom/Prénom de la mère'), \n 'Filiation_MotherBirthday': fields.date(string='Anniveraire de la mère'), \n 'Filiation_MotherAddress': fields.char(string='Adresse de la mère'), \n 'Filiation_MotherPhone': fields.char(string='Téléphone de la mère'), \n 'Filiation_MotherActivity': fields.char(string='Activité de la mère'), \n 'Filiation_MotherIncome': fields.char(string='Revenu de la mère'),\n\n\n # 3 Formation\n 'Formation_Schooled': fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Scolarisé'),\n 'Formation_Grade' : fields.char(string=\"Niveau scolaire\"),\n 'Formation_VocationalTraining' : fields.char(string=\"Formation professionnelle\"),\n 'Formation_DurationTraining' : fields.char(string='Durée de la formation'),\n 'Formation_CurrentActivity' : fields.char(string='Occupation actuelle'),\n\n # 4 Lieu de vie actuel\n 'Location_IsVillage': fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Est-ce un village'),\n 'Location_VillageName' : fields.char(string=\"Nom du village\"),\n 'Location_DistanceTown' : fields.char(string='Ville la plus proche',help='Kilomètre'),\n 'Location_IsFar' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Lieu isolé'),\n # Label Coordonnées d'une personne de référence\n 'Location_ReferenceLastName' : fields.char(string='Nom'),\n 'Location_ReferenceFirstName' : fields.char(string='Prénom'),\n 'Location_ReferenceAddress' : fields.char(string='Adresse'),\n 'Location_ReferencePhone' : fields.char(string='Téléphone'),\n 'Location_ReferenceFax' : fields.char(string='Fax'),\n # Label Hôpital le plus proche \n 'Location_DistanceHospital' : fields.char(string='Distance', help=\"Kilomètre\"),\n 'Location_TimeToHospital' : fields.char(string='Durée du trajet'),\n 'Location_TransportToHospital' :fields.char(string='Moyen de locomotion'),\n # Label Dispensaire le plus proche \n 'Location_DistanceDispensary' : fields.char(string='Distance',help=\"Kilomètre\"),\n 'Location_TimeToDispensary' : fields.char(string='Durée du trajet'),\n 'Location_TransportToDispensary' : fields.char(string='Moyen de locomotion'),\n\n\n # 5 première rencontre avec l'enfant\n 'First_WhoMeet' : fields.char(string=\"Qui a rencontré la personne\"),\n 'First_WhenMeet' : fields.date(string=\"Quand\"),\n 'First_WhereMeet' : fields.char(string=\"Où\"),\n 'First_HowMeet' : fields.char(string=\"Comment\"),\n\n # 6 Medical\n \n 'health_description' : fields.text(string=\"Description\", help=\"Etat de santé général\"),\n\n # Vaccins\n 'Vaccine_ro': fields.boolean(string=\"Rougeole\"),\n 'Vaccine_ru': fields.boolean(string=\"Rubéole\"),\n 'Vaccine_or': fields.boolean(string=\"Oreillons\"),\n 'Vaccine_di': fields.boolean(string=\"DI-TE-PER-POL (rattrapage)\"),\n 'Vaccine_gr': fields.boolean(string=\"Grippe\"),\n 'Vaccine_ot': fields.boolean(string=\"Autres\"),\n 'Vaccine_ot_name': fields.char(string=\"Nom\"),\n\n # Ajout du tableau des vaccins\n 'Vaccines_ids': fields.one2many('humanity.vaccines', 'people_id'), \n\n 'Noma_program' : fields.boolean(string=\"Programme Noma\"),\n\n 'Lesion_Origin' : fields.selection([('N', 'Noma'), ('B', 'Bec de lièvre'), ('A','Autre'), ], string='Origine des lésions'),\n 'Lesion_Description' : fields.text(string=\"Description des lésions\", help=\"Localisation/délimitation des lésions externes\"),\n \n # Description des lésions internes\n 'Lesion_MaxillaryBone' : fields.boolean(string=\"Os maxillaire supérieur\"),\n 'Lesion_MaxillaryBoneLower' : fields.boolean(string=\"Os maxillaire inférieur\"),\n 'Lesion_MalarBone' : fields.boolean(string=\"Os malaire\"),\n 'Lesion_Mouth' : fields.boolean(string=\"Plancher buccal\"),\n 'Lesion_Constriction' : fields.boolean(string=\"Constriction\"),\n 'Lesion_Palate' : fields.boolean(string=\"Palais\"),\n 'Lesion_NasalBone' : fields.boolean(string=\"Os nasal\"),\n 'Lesion_Columella' : fields.boolean(string=\"Columelle\"),\n 'Lesion_Orbit' : fields.boolean(string=\"Orbite\"),\n 'Lesion_Other' : fields.char(string=\"Autre\"),\n\n\t\n # 7 Composition de la famille vivant avec l'enfant \n 'Family_ids': fields.one2many('humanity.family', 'people_id'), \n\n\n # 8 Quotidien de l'enfant\n # Régime alimentaire de l'enfant\n 'Feeding_MealDay' : fields.integer(string=\"Nbre de repas par jour\"),\n 'Feeding_MealTime' : fields.char(string=\"Horaire des repas\"),\n 'Feeding_Meat' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Mange-t-il de la viande'),\n 'Feeding_WhatMeat' : fields.char(string=\"Quelle viande\"),\n 'Feeding_Vegetable' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Mange-t-il des légumes'),\n 'Feeding_WhatVegetable' : fields.char(string=\"Quels légumes\"),\n 'Feeding_Allergy' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Alérgie'),\n 'Feeding_AllergyName' : fields.char(string=\"Nom de l'alérgie\"),\n 'Feeding_Milk' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Prend-il du lait'),\n 'Feeding_WhatMilk' : fields.char(string='Quel lait'),\n 'Feeding_NumberMilk' : fields.integer(string=\"Nbre biberons par jour\"),\n 'Feeding_TimeMilk' : fields.char(string=\"Horaire des biberons\"),\n 'Feeding_Help' : fields.selection([('S', 'Seul'), ('A', \"Avec de l'aide\"), ], string=\"La personne mange\"),\n\n # Régime alimentaire de la famille\n 'FeedingFamily_Morning' : fields.char(string=\"Le matin\"),\n 'FeedingFamily_Midday' : fields.char(string=\"Le midi\"),\n 'FeedingFamily_Evening' : fields.char(string=\"Le soir\"),\n\n # Quantité mensuelle estimée de nourriture consommée\n 'FeedingFamily_Cereal' : fields.integer(string=\"Céréal/Kg\"),\n 'FeedingFamily_MeatFish' : fields.integer(string=\"Viande-Poisson/Kg\"),\n 'FeedingFamily_DairyProduct' : fields.integer(string=\"Produit laitier/Kg\"),\n 'FeedingFamily_Note' : fields.text(string=\"Autres remarques\"),\n\n # Hygiène\n 'Hygiene_Wash' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Se lave-t-il'),\n 'Hygiene_Bath' : fields.boolean(string=\"Bain\"),\n 'Hygiene_Shower' : fields.boolean(string=\"Douche\"),\n 'Hygiene_WashTooth' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Se lave les dents'),\n 'Hygiene_ToiletAlone' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Va seul aux toilettes'),\n 'Hygiene_BedWetting' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Mouille son lit'),\n\n # Sommeil\n 'Sleep_Day' : fields.selection([('Y', 'Oui'), ('N', 'Non'),('R','Rarement') ], string='Dort la journée'),\n 'Sleep_BedTimeEvening' : fields.char(string=\"Heure du couché\"),\n 'Sleep_BedTimeMorning' : fields.char(string=\"Heure du levé\"),\n 'Sleep_WakeNight' : fields.selection([('Y', 'Oui'), ('N', 'Non'),('R','Rarement') ], string='Se réveille la nuit'),\n 'Sleep_WhyWakeNight' : fields.char(string=\"Pourquoi\"),\n 'Sleep_Toy' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Prend un jouet'),\n 'Sleep_WhatToy' : fields.char(string=\"Lequel\"),\n\n # Relations affectives\n 'Relationship_Mother' : fields.char(string=\"Avec sa mère\"),\n 'Relationship_Father' : fields.char(string=\"Avec son père\"),\n 'Relationship_GrandParents' : fields.char(string=\"Avec ses grands parents\"),\n 'Relationship_Other' : fields.char(string=\"Avec d'autres\"),\n\n # Religion\n 'Religion_Practicing' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Pratique sa religion'),\n 'Religion_Name' : fields.char(string=\"Nom de la religion\"),\n 'Religion_How' : fields.char(string=\"Quelle pratique\"),\n 'Religion_Note' : fields.text(string=\"Autres remarques\"),\n\n\n # 9 Budget mensuel du groupe familial\n # Ressources\n 'Budget_Income' : fields.char(string=\"Revenus\"),\n 'Budget_Allocation' : fields.char(string=\"Allocations\"),\n 'Budget_Other' : fields.char(string=\"Autre\"),\n\n # Charges actuelles\n 'Budget_Food' : fields.char(string=\"Nourriture\"),\n 'Budget_Rent' : fields.char(string=\"Loyer\"),\n 'Budget_Schooling' : fields.char(string=\"Scolarité\"),\n 'Budget_Care' : fields.char(string=\"Soins\"),\n 'Budget_Other' : fields.char(string=\"Autres\"),\n\n # Participation\n 'Budget_Participation' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Participatoin aux soins'),\n 'Budget_WhoParticipation' : fields.char(string=\"Qui\"),\n 'Budget_HowParticipation' : fields.char(string=\"Si oui, combien\"),\n\n\n # 10 Le logement\n 'Accommodation_QuarterType' : fields.char(string=\"Type de quartier\"),\n 'Accomodation_NumberRooms' : fields.float(string=\"Nbre de pièce\"),\n 'Accomodation_Electricity' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Electricité'),\n 'Accomodation_Water' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Eau'),\n 'Accomodation_State' : fields.char(string=\"Etat du logement\"),\n 'Accomodation_People' : fields.integer(string=\"Nbre d'occupant\"),\n 'Accomodation_Dimension' : fields.char(string=\"Dimension du logement\"),\n 'Accomodation_NumberBeds' : fields.integer(string=\"Nbre de lit\"),\n 'Accomodation_Kitchen' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Cuisine'),\n 'Accomodation_Bath' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Salle de bains/Toilettes'),\n 'Accomodation_Description' : fields.text(string=\"Description détaillée\"),\n\n # 11 La vie de l'enfant\n 'Life_Note' : fields.text(string=\"Exposé\"),\n\n # 12 Le début de la maladie et son développement\n 'Illness_WhoFind' : fields.char(string=\"Qui a découvert la maladie\"),\n 'Illness_FirstSymptom' : fields.text(string=\"Premiers symptomes\"),\n 'Illness_Advice' : fields.text(string=\"Conseils\"),\n 'Illness_Begin' : fields.text(string=\"Temps depuis le début\"),\n 'Illness_WhoBring' : fields.text(string=\"Qui a amené la personne\"),\n 'Illness_Reaction' : fields.text(string=\"Réaction de la famille\"),\n 'Illness_Care' : fields.text(string=\"Soins reçu à l'hopital\"),\n 'Illness_Live' : fields.text(string=\"La personne et la maladie\"),\n 'Illness_LiveParents' : fields.text(string=\"Les parents et la maladie\"),\n\n # 13 Noms des personnes de la famille (ou amies) présentes lors de cet entretien et ayant répondu aux questions ?\n 'Contact_IsMother' : fields.boolean(string=\"La mère\"),\n 'Contact_IsFather' : fields.boolean(string=\"Le père\"),\n 'Contact_IsOther' : fields.boolean(string=\"Autre personne\"),\n\n #Autres\n 'Contact_FirstNameOther' : fields.char(string=\"Prénom\"),\n 'Contact_LastNameOther' : fields.char(string=\"Nom de famille\"),\n 'Contact_LinkOther' : fields.char(string=\"Lien de parenté\"),\n\n # 14 Coordonnées de la personne qui a rempli l'enquête médico-sociale.\n 'Investigation_LastName' : fields.char(string=\"Nom de famille\"),\n 'Investigation_FirstName' : fields.char(string=\"Prénom\"),\n 'Investigation_Fonction' : fields.char(string=\"Fonction\"),\n 'Investigation_Address' : fields.char(string=\"Adresse\"),\n 'Investigation_Phone' : fields.char(string=\"Téléphone\"),\n 'Investigation_Date' : fields.date(string=\"Date\"),\n\n\n # 15 Détention\n 'Detention_Reason' : fields.char(string=\"Motif\"),\n 'Detention_Confession' : fields.selection([('Y', 'Oui'), ('N', 'Non'), ], string='Aveux'),\n 'Detention_Date' : fields.date(string=\"Date du placement\"),\n 'Detention_Duration' : fields.char(string=\"Durée du placement\"),\n 'Detention_Supported' : fields.text(string=\"Motif de la prise en charge\"),\n 'Detention_DateSupport' : fields.date(string=\"Date de la prise en charge\"),\n\n # Gestion des images\n 'image': fields.binary(\"Image\",\n help=\"This field holds the image used as avatar for this contact, limited to 1024x1024px\"),\n 'image_small': fields.function(_get_image, fnct_inv=_set_image,\n string=\"Small-sized image\", type=\"binary\", multi=\"_get_image\",\n store={\n 'humanity.people': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),\n },\n help=\"Small-sized image of the product. It is automatically \"\\\n \"resized as a 64x64px image, with aspect ratio preserved. \"\\\n \"Use this field anywhere a small image is required.\"),\n\n 'image_medium': fields.function(_get_image, fnct_inv=_set_image,\n string=\"Medium-sized image\", type=\"binary\", multi=\"_get_image\",\n store={\n 'humanity.people': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),\n },\n help=\"Medium-sized image of this contact. It is automatically \"\\\n \"resized as a 128x128px image, with aspect ratio preserved. \"\\\n \"Use this field in form views or some kanban views.\"),\n\n }\n\n _sql_constraints = [\n ('Main_FileNumber', 'unique(Main_FileNumber)', 'No de dossier déjà attribué'),\n ]\n\n _defaults = {\n 'Main_Actif': True,\n }\n\nclass humanity_vaccine(osv.Model):\n _name = 'humanity.vaccine'\n\n _columns = {\n 'name': fields.char(string='Nom du vaccin'),\n }\n\nclass humanity_vaccines(osv.Model):\n _name = 'humanity.vaccines'\n\n _columns = {\n 'todo': fields.date(string='A effectuer'),\n 'made': fields.date(string='Effectué'),\n 'reaction': fields.text('Réactions'),\n 'vaccine_id': fields.many2one('humanity.vaccine','Vaccins'),\n 'people_id': fields.many2one('humanity.people','people_id', 'People'),\n }\n\nclass humanity_family(osv.Model):\n _name = 'humanity.family'\n\n _columns = {\n 'name': fields.char(string='Nom'),\n 'year': fields.date(string='Né/e le'),\n 'sex': fields.selection([('m', 'Masculin'), ('f', 'Féminin'), ], string='Genre'),\n 'link': fields.selection([\n ('P', 'Père'),\n ('M', 'Mère'),\n ('GF', 'Grand frère'),\n ('PF', 'Petit frère'),\n ('GS', 'Grande soeur'),\n ('PS', 'Petite soeur'),\n ('ON', 'Oncle'),\n ('TA', 'Tante'),\n ('GP', 'Grand-Père'),\n ('GM', 'Grand-Mère'),\n ('CN', 'Cousin'),\n ('CE', 'Cousine'),\n ('BF', 'Beau-frère'),\n ('BS', 'Belle-soeur'),\n ('BM', 'Belle-mère'),\n ('BP', 'Beau-père'),\n ('CO', 'Co-épouse'),\n ('BF', 'Beau-fils'),\n ('BFI', 'Belle-fille'),\n ('FI', 'Fille'),\n ('FIS', 'Fils'),\n ('DF', 'Demi-frère'),\n ('DS', 'Demi-soeur'),\n ], string='Lien de parentée'),\n 'marital': fields.char(string='Etat civil'),\n 'activity': fields.char(string='Occupation'),\n 'chousehold' : fields.boolean(string=\"Vit avec la personne\"),\n 'people_id': fields.many2one('humanity.people','people_id', 'People')\n }\n\nclass humanity_log(osv.Model):\n _name = 'humanity.log'\n _inherit = ['mail.thread', 'ir.needaction_mixin']\n _description = 'Feuilles de route'\n\n _mail_post_access = 'read'\n _track = {\n 'user_id': {\n # this is only an heuristics; depending on your particular stage configuration it may not match all 'new' stages\n 'humanity.mt_log_new': lambda self, cr, uid, obj, ctx=None: obj.user_id,\n },\n\n }\n\n _columns = {\n 'name' : fields.char(string=\"Titre\"),\n 'description': fields.text('Description'),\n 'treatment': fields.text('Traitement'),\n 'care': fields.text('Les soins'),\n 'diet': fields.text('Régime'),\n 'phyiso': fields.text('Physio'),\n 'feedback_cs' : fields.text('Feedback CS'),\n 'date_next': fields.datetime(string='Prochaine consultation'),\n 'date': fields.datetime(string='Début'),\n 'dateto' : fields.datetime(string='Fin'),\n 'people_id': fields.many2one('humanity.people',string=\"Dossier\",ondelete='restrict'),\n 'logtype_id' : fields.many2one('humanity.logtype',string='Type',ondelete='restrict'),\n 'user_id': fields.many2one('res.users','Responsable'),\n 'project_id': fields.many2one('project.project','Projet'),\n 'allday' : fields.boolean(string=\"La journée\"),\n }\n\n _defaults = {\n 'date': lambda self,cr,uid,context=None: fields.date.context_today(self,cr,uid,context) + \" 11:00:00\",\n 'user_id' : lambda obj, cr, uid, context: uid,\n }\n\n\nclass humanity_program(osv.Model):\n\n def _dept_name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):\n res = self.name_get(cr, uid, ids, context=context)\n return dict(res)\n\n _name = 'humanity.program'\n\n _columns = {\n 'name': fields.char('Titre'),\n 'complete_name': fields.function(_dept_name_get_fnc, type=\"char\", string='Name'),\n 'parent_id': fields.many2one('humanity.program', 'Programme parent', select=True),\n 'child_ids': fields.one2many('humanity.program', 'parent_id', 'Programmes'),\n 'comment': fields.text('Description')\n }\n\n def name_get(self, cr, uid, ids, context=None):\n if context is None:\n context = {}\n if not ids:\n return []\n if isinstance(ids, (int, long)):\n ids = [ids]\n reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)\n res = []\n for record in reads:\n name = record['name']\n if record['parent_id']:\n name = record['parent_id'][1]+' / '+name\n res.append((record['id'], name))\n return res\n\nclass humanity_delegation(osv.Model):\n _name = 'humanity.delegation'\n\n _columns = {\n 'name': fields.char('Titre'),\n }\n\n# Type de projet que l'on peut créer dans un programme\nclass humanity_ProjectType(osv.Model):\n _name = 'humanity.projecttype'\n\n _columns = {\n 'name': fields.char('Titre'),\n 'description': fields.text('Description'),\n 'program_id': fields.many2one('humanity.program', string='Programme', ondelete='restrict'), \n }\n\n# Projets ouvert dans un programme pour un enfant\nclass humanity_Project(osv.Model):\n _name = 'humanity.project'\n\n _columns = {\n 'people_id': fields.many2one('humanity.people',string=\"Dossier\",ondelete='restrict'),\n 'projecttype_id': fields.many2one('humanity.projecttype',string=\"Type de projet\",ondelete='restrict'),\n 'date_start': fields.date(string=\"Date de début\"),\n 'date_end': fields.date(string=\"Date de fin\"),\n 'image': fields.related('people_id', 'image', type='binary', string='Image', readonly=True),\n }\n\nclass humanity_logtype(osv.Model):\n _name = 'humanity.logtype'\n\n _columns = {\n 'name': fields.char('Nom'),\n 'comment': fields.text('Description')\n }\n\nclass humanity_letterTemplate(osv.Model):\n _name = 'humanity.lettertemplate'\n\n _columns = {\n 'name' : fields.char(string='Nom', required='True'),\n 'text' : fields.html(string='Texte', required='True')\n }\n\n @api.multi\n def get_value(self):\n self.ensure_one()\n return self\n\nclass humanity_letter(osv.Model):\n _name = \"humanity.letter\"\n\n _columns = {\n 'comment_template_id' : fields.many2one('humanity.lettertemplate',\n string='Modèle'),\n 'name' : fields.char(string='Nom', required='True'),\n 'date' : fields.date(string='Date'),\n 'text' : fields.html(string='Texte'),\n 'signature' : fields.char(string='Signature'),\n 'droit' : fields.boolean(string='A qui de droit'),\n 'partner_id' : fields.many2one('res.partner',string='Contact'),\n 'people_id': fields.many2one('humanity.people',string=\"Dossier\",ondelete='restrict'),\n\n }\n \n def trans(self,text):\n text = text.format(name=self.people_id.Main_LastName)\n return text\n\n @api.onchange('comment_template_id')\n def _set_text(self):\n comment = self.comment_template_id\n if comment:\n birthday = datetime.strptime(self.people_id.Main_Birthday,\"%Y-%m-%d\")\n self.text = comment.get_value().text.format(lastname=self.people_id.Main_LastName,firstname=self.people_id.Main_FirstName,birthday=birthday.strftime(\"%d/%m/%y\"))\n self.name = comment.get_value().name\n\n\n\n\n\n","sub_path":"humanity.py","file_name":"humanity.py","file_ext":"py","file_size_in_byte":27138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"191321423","text":"from a10sdk.common.A10BaseClass import A10BaseClass\n\n\nclass NotificationCfg(A10BaseClass):\n \n \"\"\"This class does not support CRUD Operations please use parent.\n\n :param notification: {\"default\": 0, \"type\": \"number\", \"description\": \"Enable lldp notification\", \"format\": \"flag\"}\n :param interval: {\"description\": \"Configure lldp notification interval, default is 30 (The lldp notification interval value, default is 30)\", \"format\": \"number\", \"default\": 30, \"maximum\": 3600, \"minimum\": 5, \"type\": \"number\"}\n :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`\n\n \n\n \n \"\"\"\n def __init__(self, **kwargs):\n self.ERROR_MSG = \"\"\n \n self.b_key = \"notification-cfg\"\n self.DeviceProxy = \"\"\n self.notification = \"\"\n self.interval = \"\"\n\n for keys, value in kwargs.items():\n setattr(self,keys, value)\n\n\nclass TxSet(A10BaseClass):\n \n \"\"\"This class does not support CRUD Operations please use parent.\n\n :param fast_interval: {\"description\": \"Configure lldp tx fast interval value (The lldp tx fast interval value, default is 1)\", \"format\": \"number\", \"default\": 1, \"maximum\": 3600, \"minimum\": 1, \"type\": \"number\"}\n :param fast_count: {\"description\": \"Configure lldp tx fast count value (The lldp tx fast count value, default is 4)\", \"format\": \"number\", \"default\": 4, \"maximum\": 8, \"minimum\": 1, \"type\": \"number\"}\n :param hold: {\"description\": \"Configure lldp tx hold multiplier (The lldp tx hold value, default is 4)\", \"format\": \"number\", \"default\": 4, \"maximum\": 10, \"minimum\": 1, \"type\": \"number\"}\n :param tx_interval: {\"description\": \"Configure lldp tx interval (The lldp tx interval value, default is 30)\", \"format\": \"number\", \"default\": 30, \"maximum\": 3600, \"minimum\": 1, \"type\": \"number\"}\n :param reinit_delay: {\"description\": \"Configure lldp tx reinit delay (The lldp tx reinit_delay value, default is 2)\", \"format\": \"number\", \"default\": 2, \"maximum\": 10, \"minimum\": 1, \"type\": \"number\"}\n :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`\n\n \n\n \n \"\"\"\n def __init__(self, **kwargs):\n self.ERROR_MSG = \"\"\n \n self.b_key = \"tx-set\"\n self.DeviceProxy = \"\"\n self.fast_interval = \"\"\n self.fast_count = \"\"\n self.hold = \"\"\n self.tx_interval = \"\"\n self.reinit_delay = \"\"\n\n for keys, value in kwargs.items():\n setattr(self,keys, value)\n\n\nclass EnableCfg(A10BaseClass):\n \n \"\"\"This class does not support CRUD Operations please use parent.\n\n :param enable: {\"default\": 0, \"type\": \"number\", \"description\": \"Enable lldp\", \"format\": \"flag\"}\n :param rx: {\"default\": 0, \"type\": \"number\", \"description\": \"Enable lldp rx\", \"format\": \"flag\"}\n :param tx: {\"default\": 0, \"type\": \"number\", \"description\": \"Enable lldp tx\", \"format\": \"flag\"}\n :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`\n\n \n\n \n \"\"\"\n def __init__(self, **kwargs):\n self.ERROR_MSG = \"\"\n \n self.b_key = \"enable-cfg\"\n self.DeviceProxy = \"\"\n self.enable = \"\"\n self.rx = \"\"\n self.tx = \"\"\n\n for keys, value in kwargs.items():\n setattr(self,keys, value)\n\n\nclass Lldp(A10BaseClass):\n \n \"\"\"Class Description::\n Configure LLDP.\n\n Class lldp supports CRUD Operations and inherits from `common/A10BaseClass`.\n This class is the `\"PARENT\"` class for this module.`\n\n :param uuid: {\"description\": \"uuid of the object\", \"format\": \"string\", \"minLength\": 1, \"modify-not-allowed\": 1, \"optional\": true, \"maxLength\": 64, \"type\": \"string\"}\n :param system_description: {\"description\": \"Configure lldp system description\", \"format\": \"string\", \"minLength\": 1, \"optional\": true, \"maxLength\": 127, \"type\": \"string\"}\n :param system_name: {\"description\": \"Configure lldp system name\", \"format\": \"string\", \"minLength\": 1, \"optional\": true, \"maxLength\": 127, \"type\": \"string\"}\n :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`\n\n \n\n URL for this object::\n `https:////axapi/v3/network/lldp`.\n\n \n\n \n \"\"\"\n def __init__(self, **kwargs):\n self.ERROR_MSG = \"\"\n self.required=[]\n self.b_key = \"lldp\"\n self.a10_url=\"/axapi/v3/network/lldp\"\n self.DeviceProxy = \"\"\n self.uuid = \"\"\n self.system_description = \"\"\n self.management_address = {}\n self.notification_cfg = {}\n self.tx_set = {}\n self.enable_cfg = {}\n self.system_name = \"\"\n\n for keys, value in kwargs.items():\n setattr(self,keys, value)\n\n\n","sub_path":"a10sdk/core/network/network_lldp.py","file_name":"network_lldp.py","file_ext":"py","file_size_in_byte":4813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"164876547","text":"#!/usr/bin/env python\n# -*- coding: UTF8 -*-\n\n\n\"\"\"\n减少可调用对象的参数个数\n\"\"\"\n\n\ndef spam(a, b, c, d):\n print(a, b, c, d)\n\n\nfrom functools import partial\n\ns1 = partial(spam, 1) # a=1\ns1(2, 3, 4)\ns1(4, 5, 6)\n\ns2 = partial(spam, d=42) # d=42\ns2(1, 2, 3) # 1 2 3 42\n\ns3 = partial(spam, 1, 2, d=42) # a = 1, b = 2, d = 42\ns3(10) # 1 2 10 42\ns3(20) # 1 2 20 42\n\n\"\"\"\npartial() 固定某些参数并返回一个新的callable 对象。这个新的callable\n接受未赋值的参数,然后跟之前已经赋值过的参数合并起来,最后将所有参数传递给\n原始函数。\n\"\"\"\n","sub_path":"python/cb3e/function/partial_args.py","file_name":"partial_args.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"535715577","text":"money = int(input('the amount of money in cents is :'))\r\n\r\ntoonies = money//200\r\nloonies = money%200//100\r\nquarters = money%100//25\r\ndimes = money%100%25//10\r\nnickels = money%100%25%10//5\r\npennies = money%100%25%10%5//1\r\n\r\nprint(toonies,'toonies', loonies,'loonies', quarters,'quarters', dimes,'dimes', nickels,'nickels', pennies,'pennies')","sub_path":"making change.py","file_name":"making change.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"176966014","text":"from django.conf.urls.defaults import *\nfrom django.contrib.auth.views import login,logout\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nfrom mysite.my_settings import STATIC_ROOT\n\nurlpatterns = patterns('',\n # Example:\n # (r'^mysite/', include('mysite.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # (r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n (r'^statics/(?P.*)$', 'django.views.static.serve',{'document_root': STATIC_ROOT}),\n (r'^django-admin/', include(admin.site.urls)),\n# (r'^$','mysite.views.hello'),\n (r'^login/',login,{'template_name':'login.html'}),\n (r'^logout/$',logout,{'template_name':'bye.html'}),\n (r'^admin/',include('mysite.myadmin.urls')),\n)\n\nurlpatterns += patterns('',\n (r'^',include('mysite.front.urls')),\n)\n\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"181780776","text":"from urllib import request\n\ngoog_url = 'http://real-chart.finance.yahoo.com/table.csv?s=GOOG&d=3&e=6&f=2015&g=d&a=2&b=27&c=2014&ignore=.csv'\n\n\ndef dload_stock_info(csv_url):\n response = request.urlopen(csv_url)\n csv = response.read()\n csv_str = str(csv)\n line = csv_str.split(\"\\\\n\")\n destin_url = r'google.csv'\n file_x = open(destin_url, \"w\")\n for line in line:\n file_x.write(line + \"\\n\")\n file_x.close()\n\ndload_stock_info(goog_url)","sub_path":"Python3/TNB/oldFiles/24.py","file_name":"24.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"242700911","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Feb 3 22:13:35 2019\r\n\r\n@author: jeremychen\r\n\"\"\"\r\n\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef calc_h(rows, cols, bestpos, sigma):\r\n j_mat, i_mat = np.meshgrid(range(cols), range(rows))\r\n S = np.sqrt((i_mat - bestpos[0]) ** 2 + (j_mat - bestpos[1]) ** 2)\r\n h = np.exp(-S ** 2 / (2 * sigma ** 2)).reshape(rows, cols, 1)\r\n return h\r\n\r\nrows = 51\r\ncols = 101\r\nbest_pos = (5, 10)\r\n\r\nh = np.squeeze(calc_h(rows, cols, best_pos, 20))\r\nj_mat, i_mat = np.meshgrid(range(cols), range(rows))\r\n\r\nfig = plt.figure()\r\nax = fig.gca(projection='3d')\r\nsurf = ax.plot_surface(j_mat, i_mat, h, linewidth=0, antialiased=True)","sub_path":"src/test_gaussian.py","file_name":"test_gaussian.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"331646408","text":"N = int(input())\n\ndef calc(p, s):\n return p + s\n\ndef main():\n l0 = 2\n l1 = 1\n if N == 1:\n print(l1)\n else:\n p = l0\n s = l1\n for i in range(N - 1):\n temp = calc(p, s)\n p = s\n s = temp\n print(s)\n\nif __name__ == '__main__':\n main()","sub_path":"beginner_79/lucas_number.py","file_name":"lucas_number.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"243157552","text":"from sklearn import tree\nfrom sklearn import metrics\nfrom sklearn.model_selection import StratifiedKFold\nimport numpy as np\n\nclass AdaBoost:\n\n def __init__(self, n_estimators = 10):\n self.h = list()\n self.alpha = np.zeros(n_estimators)\n self.n_estimators = n_estimators\n\n def fit(self, XTrain, yTrain):\n length = XTrain.shape[0]\n D = np.ones(length) / length\n\n for t in range(self.n_estimators):\n\n clf = tree.DecisionTreeClassifier()\n f = clf.fit(XTrain, yTrain, sample_weight=D)\n pred = f.predict(XTrain)\n\n error = np.average(pred != yTrain, weights=D)\n\n #print(error)\n\n if error > 0.5:\n break\n elif error <= 0:\n self.h.append(f)\n self.alpha[t] = 1\n break\n\n self.h.append(f)\n\n self.alpha[t] = 0.5 * np.log((1 - error) / error)\n D = D*np.exp(-1*pred*yTrain*self.alpha[t])\n D = D/np.sum(D)\n\n\n def predict(self, XTest):\n length = len(self.h)\n pred = np.zeros((length, XTest.shape[0]))\n result = np.zeros(XTest.shape[0])\n prob = np.zeros(XTest.shape[0])\n\n for t in range(0, length):\n pred[t] = self.h[t].predict(XTest)*self.alpha[t]\n prob += pred[t]\n\n\n\n for i in range(XTest.shape[0]):\n if prob[i] >= 0:\n result[i] = 1\n else:\n result[i] = -1\n return result, prob\n\n\n\ndef loadData():\n XTrain = np.genfromtxt(\"adult_dataset/adult_train_feature.txt\")\n XTest = np.genfromtxt(\"adult_dataset/adult_test_feature.txt\")\n yTrain = np.genfromtxt(\"adult_dataset/adult_train_label.txt\")\n yTest = np.genfromtxt(\"adult_dataset/adult_test_label.txt\")\n return XTrain, XTest, yTrain, yTest\n\ndef crossValidation(XTrain, yTrain):\n skf = StratifiedKFold(n_splits=5)\n maxT = 2\n maxAuc = 0.0\n\n for t in range(1, 51):\n Auc = 0.0\n for trIdx, cvIdx in skf.split(XTrain, yTrain):\n # print(trIdx, cvIdx)\n XTr, yTr = XTrain[trIdx], yTrain[trIdx]\n XCV, yCV = XTrain[cvIdx], yTrain[cvIdx]\n adaboost = AdaBoost(n_estimators = t)\n adaboost.fit(XTr, yTr)\n result, prob = adaboost.predict(XCV)\n Auc += metrics.roc_auc_score(yCV, prob)\n Auc = Auc / 5\n if Auc > maxAuc:\n maxT = t\n maxAuc = Auc\n print(t, Auc)\n\n return maxT\n\nif __name__ == '__main__':\n\n print('AdaBoost algorithm start...')\n print('loading data...')\n XTrain, XTest, yTrain, yTest = loadData()\n\n yTrain = (yTrain - 0.5)*2\n yTest = (yTest - 0.5)*2\n\n T = 25\n #T = crossValidation(XTrain, yTrain)\n #print(T)\n\n print('training(T=25)...')\n adaboost = AdaBoost(n_estimators=T)\n adaboost.fit(XTrain, yTrain)\n yPred, yProb = adaboost.predict(XTest)\n\n print(metrics.classification_report(y_true=yTest, y_pred=yPred))\n print(\"AdaBoost AUC: \", metrics.roc_auc_score(yTest, yProb))\n\n\n\n\n","sub_path":"ml5/BoostMain.py","file_name":"BoostMain.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"41537525","text":"from tkinter import *\n\nexpression = \"\"\n\ndef press (num):\n global expression\n expression = expression + str(num)\n equation.set(expression)\n\ndef equalpress():\n try:\n global expression\n total = str(eval(expression))\n equation.set(total)\n expression = \"\"\n except:\n equation.set(' error ')\n expression = \"\"\n\ndef clear():\n global expression\n expression = \"\"\n equation.set(\"\")\n\nif __name__ == \"__main__\":\n gui = Tk()\n gui.configure(background=\"light green\")\n gui.title(\"Simple Calculator\")\n gui.geometry(\"265x125\")\n equation = StringVar()\n expression_field = Entry(gui, textvariable=equation)\n expression_field.grid(columnspan=4,ipadx=70)\n equation.set('enter your expression')\n #create buttons and place at a particular location\n #when user presses the button,the command is executed\n button1 = Button(gui, text=' 1 ',fg='black',bg='red',\n\t\t command=lambda: press(1), height=1, width=7)\n button1.grid(row=2, column=0)\n\n #button 2 \n button2 = Button(gui, text= ' 2 ',fg='black',bg='red',\n command=lambda: press(2), height=1, width=7)\n button2.grid(row=2, column=1)\n\n #button3\n button3 = Button(gui, text=' 3 ',fg='black',bg='red',\n command=lambda: press(3), height=1, width=7)\n button3.grid(row=2, column=2)\n\n #button4\n button4 = Button(gui, text=' 4 ',fg='black',bg='red',\n command=lambda: press(4), height=1, width=7)\n button4.grid(row=3, column=0)\n\n #button5\n button5 = Button(gui, text=' 5 ',fg='black',bg='red',\n command=lambda: press(5), height=1, width=7)\n button5.grid(row=3, column=1)\n\n #button6\n button6 = Button(gui, text= ' 6 ',fg='black',bg='red',\n command=lambda: press(6), height=1,width=7)\n button6.grid(row=3, column=2) \n\n #button7\n button7 = Button(gui, text= ' 7 ',fg='black',bg='red',\n command=lambda: press(7), height=1,width=7)\n button7.grid(row=4, column=0)\n\n #button8\n button8 = Button(gui, text=' 8 ',fg='black',bg='red',\n command=lambda: press(8), height=1,width=7)\n button8.grid(row=4, column=1)\n\n #button9\n button9 = Button(gui, text= ' 9 ',fg='black',bg='red',\n command=lambda: press(9), height=1,width=7)\n button9.grid(row=4, column=2)\n\n #button0\n button0 = Button(gui, text= ' 0 ',fg='black',bg='red',\n command=lambda: press(0), height=1,width=7)\n button0.grid(row=5, column=0)\n\n #Plus operator\n plus = Button(gui, text=' + ',fg='black',bg='red',\n command=lambda: press(\"+\"), height=1,width=7)\n plus.grid(row=2, column=3)\n\n #Subtract operator\n minus = Button(gui, text=' - ',fg='black',bg='red',\n command=lambda: press(\"-\"), height=1,width=7)\n minus.grid(row=3, column=3)\n\n #Multiply operator\n multiply = Button(gui, text=' * ',fg='black',bg=' red ',\n command=lambda: press(\"*\"), height=1,width=7)\n multiply.grid(row=4, column=3) \n\n #Divide Operator\n Divide = Button(gui, text= ' / ',fg='black',bg='red',\n command=lambda: press(\"/\"), height=1,width=7)\n Divide.grid(row=5, column=3)\n\n #Equal Operator\n equal = Button(gui, text= ' = ',fg='black',bg='red',\n command=lambda: press(' = '), height=1,width=7)\n equal.grid(row=5, column=2)\n\n #clear Button\n clear = Button(gui,text= 'Clear',fg='black',bg='red',\n command=lambda: press(' clear'), height=1,width=7)\n clear.grid(row=5, column='1')\n\n #start the GUI\n gui.mainloop() ","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":3846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"219872209","text":"def convolution(img, kernel, padding=True):\n \"\"\" Performs convolution operation given an image and a kernel\n\n Parameters\n ----------\n img : array_like\n 1-channel image\n kernel : array-like\n kernel (filter) for convolution\n \n Returns\n -------\n np.ndarray\n result of the convolution operation\n \"\"\"\n result = np.zeros_like(img)\n p_size_i = kernel.shape[0] // 2\n p_size_j = kernel.shape[1] // 2\n\n if padding:\n padded_img = np.zeros((img.shape[0] + 2 * p_size_i, img.shape[1] + 2 * p_size_j))\n i_first = p_size_i\n i_last = padded_img.shape[0] - p_size_i - 1\n j_first = p_size_j\n j_last = padded_img.shape[1] - p_size_j - 1\n padded_img[i_first: i_last + 1, j_first: j_last + 1] = img\n else:\n padded_img = img.copy()\n i_first = p_size_i\n i_last = padded_img.shape[0] - p_size_i - 1\n j_first = p_size_j\n j_last = padded_img.shape[1] - p_size_j - 1\n \n for i in range(i_first, i_last):\n for j in range(j_first, j_last):\n window = padded_img[i - p_size_i: i + p_size_i + 1, j - p_size_j: j + p_size_j + 1]\n res_pix = np.sum(window * kernel)\n result[i - p_size_i, j - p_size_j] = res_pix\n return result","sub_path":"Tutorial 1/convolution.py","file_name":"convolution.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"605490901","text":"from opengever.base.monkey.patching import MonkeyPatch\n\n\nclass PatchFullHistory(MonkeyPatch):\n\n def __call__(self):\n\n def fullHistory(viewlet):\n history = original_fullHistory(viewlet)\n if history is None:\n history = []\n return history\n\n from plone.app.layout.viewlets.content import ContentHistoryViewlet\n\n locals()['__patch_refs__'] = False\n original_fullHistory = ContentHistoryViewlet.fullHistory\n self.patch_refs(ContentHistoryViewlet, 'fullHistory', fullHistory)\n","sub_path":"opengever/base/monkey/patches/content_history_viewlet.py","file_name":"content_history_viewlet.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"201007224","text":"def find_path(graph, start, end, path=[]):\n ''' from https://www.python.org/doc/essays/graphs/ '''\n path = path + [start]\n if start == end:\n return path\n if not graph.get(start):\n return None\n for node in graph[start]:\n if node not in path:\n newpath = find_path(graph, node, end, path)\n if newpath: return newpath\n return None\n\ndef check_connection(network, first, second):\n net_list = [i.split('-') for i in network]\n drons = set([j for i in net_list for j in i])\n drons_friends = {name : [j for i in net_list for j in i if name in i if j != name] for name in drons}\n return find_path(drons_friends, first, second) and True or False\n\n\nif __name__ == '__main__':\n #These \"asserts\" using only for self-checking and not necessary for auto-testing\n print(check_connection(\n (\"dr101-mr99\", \"mr99-out00\", \"dr101-out00\", \"scout1-scout2\",\n \"scout3-scout1\", \"scout1-scout4\", \"scout4-sscout\", \"sscout-super\"),\n \"scout2\", \"scout3\"))# == True, \"Scout Brotherhood\"\n print(check_connection(\n (\"dr101-mr99\", \"mr99-out00\", \"dr101-out00\", \"scout1-scout2\",\n \"scout3-scout1\", \"scout1-scout4\", \"scout4-sscout\", \"sscout-super\"),\n \"super\", \"scout2\"))# == True, \"Super Scout\"\n print(check_connection(\n (\"dr101-mr99\", \"mr99-out00\", \"dr101-out00\", \"scout1-scout2\",\n \"scout3-scout1\", \"scout1-scout4\", \"scout4-sscout\", \"sscout-super\"),\n \"dr101\", \"sscout\"))# == False, \"I don't know any scouts.\"\n\ndef check_connection2(network, first, second):\n graph = {}\n for conn in network:\n node0, node1 = conn.split('-')\n graph.setdefault(node0, set()).add(node1)\n graph.setdefault(node1, set()).add(node0)\n visited = set()\n queue = [first]\n while queue:\n drone = queue.pop(0)\n friends = graph.get(drone, set()) # first might have no friends at all\n if second == drone or second in friends:\n return True\n visited.add(drone)\n queue.extend(friends.difference(visited))\n return False\n\ndef check_connection3(network, first, second):\n toCheck, checked = {first}, set()\n while toCheck:\n p = toCheck.pop()\n checked.add(p)\n for i in network:\n if p in i:\n if second in i:\n return True\n else:\n pairs = i.split('-')\n pairs.remove(p)\n k = pairs.pop()\n if not k in checked:\n toCheck.add(k)\n else:\n return False\n\ndef check_connection4(network, friend1, friend2):\n connection = set([friend1])\n\n for _,_ in enumerate(network):\n for pair in network:\n first, second = pair.split('-')\n union = {first}|{second}\n\n if len(connection.intersection(union)):\n connection.update(union)\n\n return (friend2 in connection)\n\n","sub_path":"checkio/FindFriends.py","file_name":"FindFriends.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"468145692","text":"from __future__ import unicode_literals\n\n\nfrom django.db import models\n#from django.utils.encoding import python_2_unicode_compatible\nfrom django.utils import timezone\nimport datetime\n# Create your models here.\n\n\nclass Ballot(models.Model):\n\tballot_text = models.CharField(max_length=200)\n\tpub_date = models.DateTimeField('date published')\n\tend_date = models.DateTimeField('end date')\n\tdef __str__(self):\n\t\treturn self.ballot_text\n\n\tdef was_published_recently(self):\n\t\tnow = timezone.now()\n\t\treturn now - datetime.timedelta(days=1) <= self.pub_date <= now\n\t\twas_published_recently.admin_order_field = 'pub_date'\n\t\twas_published_recently.boolean = True\n\t\twas_published_recently.short_description = 'Published recently?'\n\nclass Choice(models.Model):\n\tballot = models.ForeignKey(Ballot, on_delete=models.CASCADE)\n\tchoice_text = models.CharField(max_length=200)\n\tchoice_address = models.CharField(max_length=36)\n\tvotes = models.IntegerField(default=0)\n\t\n\tdef __str__(self):\n\t\treturn self.choice_text\n\n\n\n","sub_path":"sweng500BVS/polls/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"34827509","text":"import unittest\r\nfrom HTMLTestRunner import HTMLTestRunner\r\nsuite = unittest.TestSuite()\r\na = unittest.defaultTestLoader.discover(r\"H:\\PycharmProjects\\工商银行\",pattern=\"Test*.py\")\r\nsuite.addTests(a)\r\nb = open(file=\"银行测试报告.html\",mode=\"w+\",encoding=\"utf-8\")\r\nc= HTMLTestRunner.HTMLTestRunner(\r\n stream= b,\r\n title=\"银行测试报告\",\r\n verbosity=2,\r\n description=\"银行业务逻辑测试用例\"\r\n)\r\nc.run(suite)","sub_path":"day16作业/入口程序.py","file_name":"入口程序.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"386087182","text":"#!/usr/bin/python\n#coding:utf-8\n\n\nimport pyclamd\n\nscantype=\"contscan_file\" #指写扫描模式,支持multiscan_file、contscan_file、\nscanfile=\"/\" #指定扫描路径\ncd = pyclamd.ClamdNetworkSocket(\"121.14.47.44\",3310) #创建网络套接字连接if cd.ping(): #探测连通性\ncd.reload() #重载clamd病毒特征库,建议更新病毒库后做reload()操作\ncd.contscan_file(scanfile)\ncd.multiscan_file(scantype)\n#scanresult=\"{0}\\n\".format(cd.multiscan_file(scanfile))\nscanresult=\"{0}\\n\".format(cd.scan_file(scanfile))\n#cd.scan_file(scanfile)\n\n\nprint (scanresult) #打印扫描结果\n","sub_path":"pyclamdExample.py","file_name":"pyclamdExample.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"238464967","text":"class Solution:\n def maxSum(self, nums1, nums2):\n save1 = [0]* (len(nums1) + 1)\n save2 = [0]* (len(nums2) + 1)\n # save1[len(nums1)] = 0\n # save2[len(nums2)] = 0\n for i in range(-1,len(nums1)-1):\n save1[i+1] = save1[i] + nums1[i+1]\n for i in range(-1,len(nums2)-1):\n save2[i+1] = save2[i] + nums2[i+1]\n\n print(save1,save2)\n last1 = last2 = -1\n count = 0\n i = j = 0\n \n while i < len(nums1) and j < len(nums2):\n if nums1[i] == nums2[j]:\n count += max(save1[i] - save1[last1], save2[j] - save2[last2])\n print(count)\n count = count % (10 ** 9 + 7)\n last1 = i\n last2 = j\n i += 1\n j += 1\n elif nums1[i] > nums2[j]:\n j += 1\n else:\n i += 1\n\n count += max(save1[len(nums1)-1] - save1[last1], save2[len(nums2)-1] - save2[last2])\n\n return count % (10 ** 9 + 7)\n\n\na = Solution()\nprint(a.maxSum(nums1 = [1,4,5,8,9,11,19], nums2 = [2,3,4,11,12]))","sub_path":"比赛/200场周赛/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"165037045","text":"##########################################\n#filename:xlwt.py\n#author:MacGuffin\n#date:2017/11/13\n#function:test the xlwt \n############################################\n#History:\n#\t2017/11/13 MacGuffin operation:inital this file\n#\t2017/11/15 MacGuffin operation:add sheet 2\n#####################################################\nimport xlwt\nworkbook = xlwt.Workbook()\nnumbers =workbook.add_sheet(\"numbers\",cell_overwrite_ok=True)\nNNum = workbook.add_sheet(\"Naturalnumber\",cell_overwrite_ok=True)\nx = 1\ny = 1\ndef oneline1(n,sheetname):#write numbers for one row\n global x\n for col in range(15):\n sheetname.write(n,col,x)\n x =x+n\n x += 1\nfor row in range(0,11):\n oneline1(row,numbers)\n x = x+row\ndef oneline2(n,sheetname):\n\tglobal y\n\tj=1\n\tfor col in range(0,15):\n\t\tsheetname.write(n,col,\"(%d,%d)\" %(y,j))\n\t\tj = j + 1\nfor row2 in range(0,15):\n\toneline2(row2,NNum)\n\ty = y +1\t\nworkbook.save(\"./test2.xls\")\n\t\n","sub_path":"sort/xlwttest.py","file_name":"xlwttest.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"604212851","text":"import datetime\nimport json\nimport logging\nimport pytz\n\nfrom helpers.match_helper import MatchHelper\nfrom models.event import Event\nfrom models.match import Match\n\nQF_SF_MAP = {\n 1: (1, 3), # in sf1, qf seeds 2 and 4 play. 0-indexed becomes 1, 3\n 2: (0, 2),\n 3: (1, 2),\n 4: (0, 3),\n 5: (2, 3),\n 6: (0, 1)\n}\n\nLAST_LEVEL = {\n 'sf': 'qf',\n 'f': 'sf'\n}\n\n\nclass FMSAPIHybridScheduleParser(object):\n def __init__(self, year, event_short):\n self.year = year\n self.event_short = event_short\n\n def _get_comp_level(self, match_level, match_number):\n if match_level == 'Qualification':\n return 'qm'\n else:\n if match_number <= 8:\n return 'qf'\n elif match_number <= 14:\n return 'sf'\n else:\n return 'f'\n\n def _get_match_number(self, comp_level, match_number):\n if comp_level == 'sf':\n return match_number - 8\n elif comp_level == 'f':\n return match_number - 14\n else: # qm, qf\n return match_number\n\n def parse(self, response):\n \"\"\"\n This currently only works for the 2015 game, where elims matches are all part of one set.\n \"\"\"\n matches = response['Schedule']\n\n event_key = '{}{}'.format(self.year, self.event_short)\n event = Event.get_by_id(event_key)\n if event.timezone_id:\n event_tz = pytz.timezone(event.timezone_id)\n else:\n logging.warning(\"Event {} has no timezone! Match times may be wrong.\".format(event_key))\n event_tz = None\n\n set_number = 1\n parsed_matches = []\n for match in matches:\n comp_level = self._get_comp_level(match['level'], match['matchNumber'])\n match_number = self._get_match_number(comp_level, match['matchNumber'])\n\n red_teams = []\n blue_teams = []\n team_key_names = []\n null_team = False\n for team in match['Teams']:\n if team['teamNumber'] is None:\n null_team = True\n team_key = 'frc{}'.format(team['teamNumber'])\n team_key_names.append(team_key)\n if 'Red' in team['station']:\n red_teams.append(team_key)\n elif 'Blue' in team['station']:\n blue_teams.append(team_key)\n if null_team and match['scoreRedFinal'] is None and match['scoreBlueFinal'] is None:\n continue\n\n alliances = {\n 'red': {\n 'teams': red_teams,\n 'score': match['scoreRedFinal']\n },\n 'blue': {\n 'teams': blue_teams,\n 'score': match['scoreBlueFinal']\n }\n }\n\n score_breakdown = {\n 'red': {\n 'auto': match['scoreRedAuto'],\n 'foul': match['scoreRedFoul']\n },\n 'blue': {\n 'auto': match['scoreBlueAuto'],\n 'foul': match['scoreBlueFoul']\n }\n }\n\n time = datetime.datetime.strptime(match['startTime'], \"%Y-%m-%dT%H:%M:%S\")\n if event_tz is not None:\n time = time - event_tz.utcoffset(time)\n\n parsed_matches.append(Match(\n id=Match.renderKeyName(\n event_key,\n comp_level,\n set_number,\n match_number),\n event=event.key,\n year=event.year,\n set_number=set_number,\n match_number=match_number,\n comp_level=comp_level,\n team_key_names=team_key_names,\n time=time,\n alliances_json=json.dumps(alliances),\n score_breakdown_json=json.dumps(score_breakdown)\n ))\n\n # Fix null teams in elims (due to FMS API failure, some info not complete)\n # Should only happen for sf and f matches\n organized_matches = MatchHelper.organizeMatches(parsed_matches)\n for level in ['sf', 'f']:\n playoff_advancement = MatchHelper.generatePlayoffAdvancement2015(organized_matches)\n if playoff_advancement[LAST_LEVEL[level]] != []:\n for match in organized_matches[level]:\n if 'frcNone' in match.team_key_names:\n if level == 'sf':\n red_seed, blue_seed = QF_SF_MAP[match.match_number]\n else:\n red_seed = 0\n blue_seed = 1\n red_teams = ['frc{}'.format(t) for t in playoff_advancement[LAST_LEVEL[level]][red_seed][0]]\n blue_teams = ['frc{}'.format(t) for t in playoff_advancement[LAST_LEVEL[level]][blue_seed][0]]\n\n alliances = match.alliances\n alliances['red']['teams'] = red_teams\n alliances['blue']['teams'] = blue_teams\n match.alliances_json = json.dumps(alliances)\n match.team_key_names = red_teams + blue_teams\n\n fixed_matches = []\n for key, matches in organized_matches.items():\n if key != 'num':\n for match in matches:\n if 'frcNone' not in match.team_key_names:\n fixed_matches.append(match)\n\n return fixed_matches\n","sub_path":"datafeeds/parsers/fms_api/fms_api_hybrid_schedule_parser.py","file_name":"fms_api_hybrid_schedule_parser.py","file_ext":"py","file_size_in_byte":5564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"125234247","text":"# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# (C) British Crown Copyright 2017-2019 Met Office.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\"\"\"Unit tests for the utilities.OccurrenceWithinVicinity plugin.\"\"\"\n\nimport unittest\n\nimport iris\nimport numpy as np\nfrom cf_units import Unit\nfrom iris.coords import DimCoord\nfrom iris.cube import Cube\nfrom iris.tests import IrisTest\n\nfrom improver.utilities.spatial import OccurrenceWithinVicinity\n\n\ndef set_up_thresholded_cube():\n \"\"\"Create a cube with metadata and values suitable for a thresholded\n cube.\"\"\"\n data = np.zeros((1, 1, 4, 4))\n # Convert from mm/hr to m/s.\n data[0, 0, 0, 2] = 1.0\n data[0, 0, 2, 1] = 1.0\n data[0, 0, 3, 0] = 1.0\n return set_up_cube(data, \"lwe_precipitation_rate\", \"m s-1\")\n\n\ndef set_up_cube(data, phenomenon_standard_name, phenomenon_units,\n realizations=np.array([0]),\n timesteps=np.array([402192.5]),\n y_dimension_values=np.array([0., 2000., 4000., 6000.]),\n x_dimension_values=np.array([0., 2000., 4000., 6000.])):\n \"\"\"Create a cube containing the required realizations, timesteps,\n y-dimension values and x-dimension values.\"\"\"\n cube = Cube(data, standard_name=phenomenon_standard_name,\n units=phenomenon_units)\n cube.add_dim_coord(DimCoord(realizations, 'realization',\n units='1'), 0)\n time_origin = \"hours since 1970-01-01 00:00:00\"\n calendar = \"gregorian\"\n tunit = Unit(time_origin, calendar)\n cube.add_dim_coord(DimCoord(timesteps, \"time\", units=tunit), 1)\n cube.add_dim_coord(DimCoord(y_dimension_values,\n 'projection_y_coordinate', units='m'), 2)\n cube.add_dim_coord(DimCoord(x_dimension_values,\n 'projection_x_coordinate', units='m'), 3)\n return cube\n\n\nclass Test__repr__(IrisTest):\n\n \"\"\"Test the repr method.\"\"\"\n\n def test_basic(self):\n \"\"\"Test that the __repr__ returns the expected string.\"\"\"\n result = str(OccurrenceWithinVicinity(10000))\n msg = ('')\n self.assertEqual(result, msg)\n\n\nclass Test_maximum_within_vicinity(IrisTest):\n\n \"\"\"Test the maximum_within_vicinity method.\"\"\"\n\n def setUp(self):\n \"\"\"Set up distance.\"\"\"\n self.distance = 2000\n self.grid_values = np.arange(0.0, 10000.0, 2000.0)\n\n def test_basic(self):\n \"\"\"Test for binary events to determine where there is an occurrence\n within the vicinity.\"\"\"\n expected = np.array(\n [[1., 1., 1., 0., 0.],\n [1., 1., 1., 1., 1.],\n [0., 0., 1., 1., 1.],\n [0., 0., 1., 1., 1.],\n [0., 0., 0., 0., 0.]])\n data = np.zeros((1, 1, 5, 5))\n data[0, 0, 0, 1] = 1.0\n data[0, 0, 2, 3] = 1.0\n cube = set_up_cube(data, \"lwe_precipitation_rate\", \"m s-1\",\n y_dimension_values=self.grid_values,\n x_dimension_values=self.grid_values)\n cube = cube[0, 0, :, :]\n result = OccurrenceWithinVicinity(\n self.distance).maximum_within_vicinity(cube)\n self.assertIsInstance(result, Cube)\n self.assertArrayAlmostEqual(result.data, expected)\n\n def test_fuzzy(self):\n \"\"\"Test for non-binary events to determine where there is an occurrence\n within the vicinity.\"\"\"\n expected = np.array(\n [[1., 1., 1., 0., 0.],\n [1., 1., 1., 0.5, 0.5],\n [0., 0., 0.5, 0.5, 0.5],\n [0., 0., 0.5, 0.5, 0.5],\n [0., 0., 0., 0., 0.]])\n data = np.zeros((1, 1, 5, 5))\n data[0, 0, 0, 1] = 1.0\n data[0, 0, 2, 3] = 0.5\n cube = set_up_cube(data, \"lwe_precipitation_rate\", \"m s-1\",\n y_dimension_values=self.grid_values,\n x_dimension_values=self.grid_values)\n cube = cube[0, 0, :, :]\n result = OccurrenceWithinVicinity(\n self.distance).maximum_within_vicinity(cube)\n self.assertIsInstance(result, Cube)\n self.assertArrayAlmostEqual(result.data, expected)\n\n def test_different_distance(self):\n \"\"\"Test for binary events to determine where there is an occurrence\n within the vicinity for an alternative distance.\"\"\"\n expected = np.array(\n [[1., 1., 1., 1., 1.],\n [1., 1., 1., 1., 1.],\n [1., 1., 1., 1., 1.],\n [0., 1., 1., 1., 1.],\n [0., 1., 1., 1., 1.]])\n data = np.zeros((1, 1, 5, 5))\n data[0, 0, 0, 1] = 1.0\n data[0, 0, 2, 3] = 1.0\n cube = set_up_cube(data, \"lwe_precipitation_rate\", \"m s-1\",\n y_dimension_values=self.grid_values,\n x_dimension_values=self.grid_values)\n cube = cube[0, 0, :, :]\n distance = 4000.0\n result = OccurrenceWithinVicinity(\n distance).maximum_within_vicinity(cube)\n self.assertIsInstance(result, Cube)\n self.assertArrayAlmostEqual(result.data, expected)\n\n def test_masked_data(self):\n \"\"\"Test masked values are ignored in OccurrenceWithinVicinity.\"\"\"\n expected = np.array(\n [[1., 1., 1., 0., 10.],\n [1., 1., 1., 1., 1.],\n [0., 0., 1., 1., 1.],\n [0., 0., 1., 1., 1.],\n [0., 0., 0., 0., 0.]])\n data = np.zeros((1, 1, 5, 5))\n data[0, 0, 0, 1] = 1.0\n data[0, 0, 2, 3] = 1.0\n data[0, 0, 0, 4] = 10.0\n mask = np.zeros((1, 1, 5, 5))\n mask[0, 0, 0, 4] = 1\n masked_data = np.ma.array(data, mask=mask)\n cube = set_up_cube(masked_data, \"lwe_precipitation_rate\", \"m s-1\",\n y_dimension_values=self.grid_values,\n x_dimension_values=self.grid_values)\n cube = cube[0, 0, :, :]\n result = OccurrenceWithinVicinity(\n self.distance).maximum_within_vicinity(cube)\n self.assertIsInstance(result, Cube)\n self.assertIsInstance(result.data, np.ma.core.MaskedArray)\n self.assertArrayAlmostEqual(result.data.data, expected)\n self.assertArrayAlmostEqual(result.data.mask, mask[0, 0, :, :])\n\n\nclass Test_process(IrisTest):\n\n \"\"\"Test the process method.\"\"\"\n\n def setUp(self):\n \"\"\"Set up distance.\"\"\"\n self.distance = 2000\n\n def test_with_multiple_realizations_and_times(self):\n \"\"\"Test for multiple realizations and times, so that multiple\n iterations will be required within the process method.\"\"\"\n expected = np.array(\n [[[[0., 0., 0., 0.],\n [1., 1., 1., 0.],\n [1., 1., 1., 0.],\n [1., 1., 1., 0.]],\n [[0., 0., 0., 0.],\n [0., 0., 0., 0.],\n [0., 0., 0., 0.],\n [0., 0., 0., 0.]]],\n [[[0., 0., 0., 0.],\n [0., 0., 0., 0.],\n [0., 0., 0., 0.],\n [0., 0., 0., 0.]],\n [[0., 0., 1., 1.],\n [0., 0., 1., 1.],\n [0., 0., 1., 1.],\n [0., 0., 0., 0.]]]])\n data = np.zeros((2, 2, 4, 4))\n data[0, 0, 2, 1] = 1.0\n data[1, 1, 1, 3] = 1.0\n cube = set_up_cube(data, \"lwe_precipitation_rate\", \"m s-1\",\n timesteps=np.array([402192.5, 402195.5]),\n realizations=np.array([0, 1]))\n orig_shape = cube.data.copy().shape\n result = OccurrenceWithinVicinity(self.distance).process(cube)\n self.assertIsInstance(result, Cube)\n self.assertEqual(result.data.shape, orig_shape)\n self.assertArrayAlmostEqual(result.data, expected)\n\n def test_with_multiple_realizations(self):\n \"\"\"Test for multiple realizations, so that multiple\n iterations will be required within the process method.\"\"\"\n expected = np.array(\n [[[[0., 0., 0., 0.],\n [1., 1., 1., 0.],\n [1., 1., 1., 0.],\n [1., 1., 1., 0.]]],\n [[[0., 0., 1., 1.],\n [0., 0., 1., 1.],\n [0., 0., 1., 1.],\n [0., 0., 0., 0.]]]])\n data = np.zeros((2, 1, 4, 4))\n data[0, 0, 2, 1] = 1.0\n data[1, 0, 1, 3] = 1.0\n cube = set_up_cube(data, \"lwe_precipitation_rate\", \"m s-1\",\n realizations=np.array([0, 1]))\n result = OccurrenceWithinVicinity(self.distance).process(cube)\n self.assertIsInstance(result, Cube)\n self.assertArrayAlmostEqual(result.data, expected)\n\n def test_with_multiple_times(self):\n \"\"\"Test for multiple times, so that multiple\n iterations will be required within the process method.\"\"\"\n expected = np.array(\n [[[[0., 0., 0., 0.],\n [1., 1., 1., 0.],\n [1., 1., 1., 0.],\n [1., 1., 1., 0.]],\n [[0., 0., 1., 1.],\n [0., 0., 1., 1.],\n [0., 0., 1., 1.],\n [0., 0., 0., 0.]]]])\n data = np.zeros((1, 2, 4, 4))\n data[0, 0, 2, 1] = 1.0\n data[0, 1, 1, 3] = 1.0\n cube = set_up_cube(data, \"lwe_precipitation_rate\", \"m s-1\",\n timesteps=np.array([402192.5, 402195.5]))\n orig_shape = cube.data.shape\n result = OccurrenceWithinVicinity(self.distance).process(cube)\n self.assertIsInstance(result, Cube)\n self.assertEqual(result.data.shape, orig_shape)\n self.assertArrayAlmostEqual(result.data, expected)\n\n def test_no_realization_or_time(self):\n \"\"\"Test for no realizations and no times, so that the iterations\n will not require slicing cubes within the process method.\"\"\"\n expected = np.array(\n [[0., 0., 0., 0.],\n [1., 1., 1., 0.],\n [1., 1., 1., 0.],\n [1., 1., 1., 0.]])\n data = np.zeros((1, 1, 4, 4))\n data[0, 0, 2, 1] = 1.0\n cube = set_up_cube(data, \"lwe_precipitation_rate\", \"m s-1\",\n realizations=np.array([0]))\n cube = iris.util.squeeze(cube)\n orig_shape = cube.data.shape\n result = OccurrenceWithinVicinity(self.distance).process(cube)\n self.assertIsInstance(result, Cube)\n self.assertEqual(result.data.shape, orig_shape)\n self.assertArrayAlmostEqual(result.data, expected)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"lib/improver/tests/utilities/test_OccurrenceWithinVicinity.py","file_name":"test_OccurrenceWithinVicinity.py","file_ext":"py","file_size_in_byte":11965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"382764610","text":"from DBUtils import select\nfrom DBUtils import update\nc=[]\nnum=0\nf=open(file=\"用户.txt\",mode=\"r+\",encoding=\"utf-8\")\ndata=f.readlines()\nfor i in data:\n da=i.replace(\"\\n\",\"\").split(\",\")\n c.append(da)\nfor i in c:\n sql01 = \"select * from users2 where users2.姓名 = %s\"\n data01=select(sql01,i[0])\n if len(data01)==0:\n sql=\"insert into users2 values(%s,%s,%s)\"\n param=[i[0],i[1],i[2]]\n update(sql,param)\n else:\n break\n\nfor i in c:\n num=num+int(i[2])\nprint(\"资产总和为:\",num)","sub_path":"day10/day10lianxi.py","file_name":"day10lianxi.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"292443974","text":"import cv2\nimport logging as log\nfrom openvino.inference_engine import IENetwork, IECore\n\n'''\nThis is a sample class for a model. You may choose to use it as-is or make any changes to it.\nThis has been provided just to give you an idea of how to structure your model class.\n'''\n\n\nclass Model_Face_Detection:\n '''\n Class for the Face Detection Model.\n '''\n\n def __init__(self, model_name, conf=0.5, device='CPU', extensions=None):\n '''\n TODO: Use this to set your instance variables.\n '''\n self.model_name = model_name\n self.device = device\n self.extensions = extensions\n self.confidence = conf\n self.ie = None\n self.network = None\n self.exec_network = None\n self.infer_request = None\n self.input_name = None\n self.input_shape = None\n self.output_name = None\n self.output_shape = None\n self.model_width = None\n self.model_height = None\n self.width = None\n self.height = None\n self.model_width = None\n self.model_height = None\n self.frame = None\n\n def load_model(self):\n '''\n Load the model given IR files.\n Defaults to CPU as device for use in the workspace.\n Synchronous requests made within.\n '''\n\n log.info(f\"##### Loading Model: {self.model_name}\")\n model_xml = self.model_name + \".xml\"\n model_bin = self.model_name + \".bin\"\n\n # Initialize the inference engine\n self.ie = IECore()\n\n # Add a CPU extension, if applicable\n if self.extensions and \"CPU\" in self.device:\n self.ie.add_extension(self.extensions, self.device)\n\n # Read the IR as a IENetwork\n self.network = self.ie.read_network(model=model_xml, weights=model_bin)\n\n self.check_model()\n\n # Load the IENetwork into the inference engine\n self.exec_network = self.ie.load_network(self.network, self.device)\n\n # Get the layer's info\n self.input_name = next(iter(self.exec_network.inputs))\n self.output_name = next(iter(self.exec_network.outputs))\n self.input_shape = self.exec_network.inputs[self.input_name].shape\n self.output_shape = self.exec_network.outputs[self.output_name].shape\n\n log.info(f\"Input shape: {self.input_shape}\")\n log.info(f\"Output shape: {self.output_shape}\")\n self.model_width = self.input_shape[3]\n self.model_height = self.input_shape[2]\n log.info(f'Input image will be resized to ( {self.model_width} x {self.model_height} ) for inference')\n return self.exec_network\n\n def get_input_shape(self):\n '''\n Gets the input shape of the network\n '''\n return self.input_shape\n\n def get_output_shape(self):\n '''\n Gets the output shape of the network\n '''\n return self.output_shape\n\n def predict(self, image):\n '''\n This method is meant for running predictions on the input image.\n '''\n self.frame = image\n self.height = image.shape[0]\n self.width = image.shape[1]\n frame_inference = self.preprocess_input(image)\n outputs = self.exec_network.infer(inputs={self.input_name: frame_inference})\n return self.preprocess_output(outputs[self.output_name])\n\n def check_model(self):\n ### Check for any unsupported layers, and let the user\n ### know if anything is missing. Exit the program, if so.\n supported_layers = self.ie.query_network(network=self.network, device_name=self.device)\n unsupported_layers = [l for l in self.network.layers.keys() if l not in supported_layers]\n if len(unsupported_layers) != 0:\n log.error(\"Unsupported layers found: {}\".format(unsupported_layers))\n log.error(\"Check whether extensions are available to add to IECore.\")\n exit(1)\n\n def preprocess_input(self, image):\n '''\n Before feeding the data into the model for inference,\n you might have to preprocess it. This function is where you can do that.\n '''\n frame_inference = cv2.resize(image, (self.model_width, self.model_height))\n\n # Transform the image from the original size to the (1, 3, 320, 544) input shape\n frame_inference = frame_inference.transpose((2, 0, 1))\n frame_inference = frame_inference.reshape(1, *frame_inference.shape)\n return frame_inference\n\n def extract_face(self, box):\n margin_top = 0\n margin = 0\n width = self.width\n height = self.height\n x_min = int(max(box[3] - box[3] * margin, 0) * width)\n y_min = int(max(box[4] - box[4] * margin_top, 0) * height)\n x_max = int(min(box[5] + box[5] * margin, 1) * width)\n y_max = int(min(box[6] + box[6] * margin, 1) * height)\n return self.frame[y_min:y_max, x_min:x_max]\n\n def preprocess_output(self, outputs):\n '''\n Before feeding the output of this model to the next model,\n you might have to preprocess the output. This function is where you can do that.\n '''\n # Return only the first face\n if outputs[0][0][0] is not None and outputs[0][0][0][2] >= self.confidence:\n return self.extract_face(outputs[0][0][0])\n else:\n return None\n","sub_path":"src/face_detection.py","file_name":"face_detection.py","file_ext":"py","file_size_in_byte":5326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"97955487","text":"#!/usr/bin/env python3\n\nimport sys\nimport json\n\nfrom settingsAsDict import SettingsAsDict\n\n\nclass AlarmClock(SettingsAsDict, Exception):\n\n\n def __init__(self, init_dict=None):\n super().__init__({'isactive'\n , 'alarmtime'\n , 'description'\n , 'days'\n , 'song'\n , 'room'\n , 'fadein_time'\n , 'finalvolume'\n , 'buzzer'\n , 'snooze_time'})\n if init_dict is not None:\n self.assign(init_dict)\n self.triggered = None\n\n def _set_default(self):\n self.settings = dict()\n self.settings['isactive'] = True\n self.settings['alarmtime'] = \"06:00\"\n self.settings['description'] = \"description\"\n self.settings['days'] = [False, True, True, True, True, True, True]\n self.settings['song'] = \"0\"\n self.settings['room'] = 'Flur'\n self.settings['fadein_time'] = \"60\"\n self.settings['finalvolume'] = \"30\"\n self.settings['buzzer'] = \"oncantplay\"\n self.settings['snooze_time'] = \"600\"\n\n #check if active, check if has to be activated\n def does_trigger(self, now):\n t_as_string = now.strftime(\"%H:%M\")\n if t_as_string == self.triggered:\n return\n if self.settings['alarmtime'] == t_as_string:\n # ok, time reached, but let's check rest of date\n day = now.strftime(\"%w\") # 0 = Sunday\n if self.settings['days'][int(day)]:\n self.triggered = now.strftime(\"%H:%M\")\n return True\n else:\n print(\"this day is off!\")\n pass\n return False\n\n\nclass AlarmClocks:\n\n def __init__(self, callback_alarm, base_filename = None):\n self.alarm_clock_list = list()\n if base_filename is not None:\n self.load(base_filename)\n self.callback_alarm = callback_alarm\n\n def add_clock(self, alarm):\n self.alarm_clock_list.append(alarm)\n\n def get_json(self):\n clocks = []\n for item in self.alarm_clock_list:\n clocks.append(item.settings)\n jsondata = json.dumps(clocks, sort_keys=True, indent=2)\n return jsondata\n\n def load(self, file_name):\n try:\n s = open(file_name, 'r').read()\n allclocks = json.loads(s)\n for item in allclocks:\n alarm = AlarmClock(item)\n self.alarm_clock_list.append(alarm)\n except Exception as err:\n print(\"Exception: {0}\".format(err))\n\n def save(self, file_name):\n with open(file_name, 'w') as f:\n json.dump(self.settings, f, ensure_ascii=False, sort_keys=True, indent=4)\n\n def check_time(self, now):\n for item in self.alarm_clock_list:\n if item.settings['isactive']:\n if item.does_trigger(now):\n self.callback_alarm(item)\n\n def get_alarm_list(self):\n return self.alarm_clock_list\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 1:\n print(\"usage: \"+sys.argv[0]+\" filename\")\n sys.exit(2)\n o = AlarmClocks(None, sys.argv[1])\n print(o.get_json())\n","sub_path":"alarmClock.py","file_name":"alarmClock.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"84196051","text":"import numpy as np\n\n### START CODE HERE ###\ndef Mode(a):\n\n list_a = list(a)\n dict = {} # Empty dictionary to store value:frequency pairs\n i = 0\n\n# This nested loop iterates through each item, creates a dictionary entry,\n# and compares it to the other items. When it finds an item of equivalent\n# value, it deletes that value and increments the :frequency value in the\n# dictionary.\n\n while i < len(list_a)-1:\n dict[\"{}\".format(list_a[i])] = 1\n y = i+1\n while y < len(list_a):\n if list_a[i] == list_a[y]:\n list_a.pop(y)\n dict[\"{}\".format(list_a[i])] += 1\n else:\n y += 1\n i += 1\n\n dict_list = list(dict.items()) # Creates a list of tuples from the dict\n\n# Iterates the new list, and removes anything lower than the highest\n# frequency. 'z' resets if tuples are swapped, and only increments if the\n# frequencies are equal.\n x = 0\n z = 1\n while z < (len(dict_list)):\n if dict_list[x][1] > dict_list[z][1]:\n dict_list.pop(z)\n elif dict_list[z][1] > dict_list[x][1]:\n dict_list[z], dict_list[x] = dict_list[x], dict_list[z]\n dict_list.pop(z)\n z = 1\n elif dict_list[z][1] == dict_list[x][1]:\n z += 1\n\n if len(dict_list) == len(dict): # If no values have been removed, then\n return None # there is no mode.\n elif len(dict_list) == 1:\n return dict_list[0][0]\n elif len(dict_list) > 1:\n x = 0 # Same as the earlier loop, but compares\n z = 1 # values rather than frequencies.\n while z < (len(dict_list)):\n if int(dict_list[x][0]) < int(dict_list[z][0]):\n dict_list.pop(z)\n elif int(dict_list[z][0]) < int(dict_list[x][0]):\n dict_list[z], dict_list[x] = dict_list[x], dict_list[z]\n dict_list.pop(z)\n z = 1\n return dict_list[0][0]\n\n\n### END CODE HERE ###\n\nnp.random.seed(1)\nc_data = np.random.randint(10, size=100)\nnp.random.seed(2)\nd_data = np.random.randint(100, size=100)\nnp.random.seed(3)\nf_data = np.random.randint(1000, size=100)\n\nc_mode = Mode(c_data)\nd_mode = Mode(d_data)\nf_mode = Mode(f_data)\n\nprint(\"c_mode = {}\".format(c_mode))\nprint(\"d_mode = {}\".format(d_mode))\nprint(\"f_mode = {}\".format(f_mode))\n\n#** c_mode ** 7\n\n#** d_mode ** 90\n\n#** f_mode ** 274","sub_path":"challengeTaskLab2CSC005.py","file_name":"challengeTaskLab2CSC005.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"285198863","text":"import logging\n'''\n这玩意有什么用处\n也就是可以指定输出格式,输出到\n\n\n\n另外我们还可以使用其他的 Handler 进行日志的输出,logging 模块提供的 Handler 有:\n\nStreamHandler:logging.StreamHandler;日志输出到流,可以是 sys.stderr,sys.stdout 或者文件。\nFileHandler:logging.FileHandler;日志输出到文件。\nBaseRotatingHandler:logging.handlers.BaseRotatingHandler;基本的日志回滚方式。\nRotatingHandler:logging.handlers.RotatingHandler;日志回滚方式,支持日志文件最大数量和日志文件回滚。\nTimeRotatingHandler:logging.handlers.TimeRotatingHandler;日志回滚方式,在一定时间区域内回滚日志文件。\nSocketHandler:logging.handlers.SocketHandler;远程输出日志到TCP/IP sockets。\nDatagramHandler:logging.handlers.DatagramHandler;远程输出日志到UDP sockets。\nSMTPHandler:logging.handlers.SMTPHandler;远程输出日志到邮件地址。\nSysLogHandler:logging.handlers.SysLogHandler;日志输出到syslog。\nNTEventLogHandler:logging.handlers.NTEventLogHandler;远程输出日志到Windows NT/2000/XP的事件日志。\nMemoryHandler:logging.handlers.MemoryHandler;日志输出到内存中的指定buffer。\nHTTPHandler:logging.handlers.HTTPHandler;通过”GET”或者”POST”远程输出到HTTP服务器。\n下面我们使用三个 Handler 来实现日志同时输出到控制台、文件、HTTP 服务器:\n'''\nlogger = logging.getLogger(__name__)\nlogger.setLevel(level=logging.INFO)\nhandler = logging.FileHandler('handle.log')\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\n\nlogger.info('This is a log info')\nlogger.debug('Debugging')\nlogger.warning('Warning exists')\nlogger.info('Finish')","sub_path":"loggings/log-handle.py","file_name":"log-handle.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"495598400","text":"test = {\n 'name': 'q10',\n 'points': 1,\n 'suites': [\n {\n 'cases': [\n {\n 'code': r\"\"\"\n >>> assert fr_clean.shape == (1960, 14), \"Incorrect DataFrame shape. Check your rows and columns\"\n >>> assert ~(fr_clean.isnull()).values.all(), \"You have at least one missing value\"\n \"\"\",\n 'hidden': False,\n 'locked': False\n }\n ],\n 'scored': True,\n 'setup': '',\n 'teardown': '',\n 'type': 'doctest'\n }\n ]\n}\n","sub_path":"hw1/tests/q10.py","file_name":"q10.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"179981070","text":"\"\"\"-----------------------------------------------------------------------------\r\nScript Name: List of pgtables Tool\r\nVersion: 1.1\r\nDescription: Receives as input the .csv table which lists posgresql tables \r\n and prepares it for further processing in the .bat tool. \r\nCreated By: Kusasalethu Sithole\r\nDate: 2019-08-28\r\nLast Revision: 2019-08-29\r\n--------------------------------------------------------------------------------\"\"\"\r\n\r\n\r\nimport csv\r\nimport openpyxl\r\nimport pandas as pd\r\nfrom pandas import DataFrame\r\n\r\n#convert csv to working xlsx\r\nwb = openpyxl.Workbook()\r\nws = wb.active\r\n\r\nwith open('list_of_pgtables.csv') as f:\r\n reader = csv.reader(f, delimiter='|')\r\n for row in reader:\r\n ws.append(row)\r\n\r\nws.insert_cols(1)\r\nwb.save('list_of_pgtables.xlsx')\r\n\r\n\r\n#concantenate schema name and table name columns\r\nwb = pd.read_excel('list_of_pgtables.xlsx', header = None)\r\nwb[1] = wb[1].str.strip()\r\nwb[2] = wb[2].str.strip()\r\nwb[0] = wb[1].astype(str) + '.' + wb[2].astype(str)\r\nwb.to_excel('list_of_pgtables.xlsx', index=False)\r\n\r\n\r\n#remove unwanted rows and columns\r\nwb = openpyxl.load_workbook('list_of_pgtables.xlsx')\r\nsheet = wb['Sheet1']\r\nsheet.delete_rows(1,2)\r\nsheet.delete_rows(1,2)\r\nsheet.delete_cols(2,3)\r\nsheet.delete_cols(2,3) \r\nwb.save('list_of_pgtables.xlsx') \r\nwb.close()\r\n\r\n\r\n#convert working xlsx to final csv\r\nwb = pd.read_excel('list_of_pgtables.xlsx')\r\nwb.to_csv('list_of_pgtables_2.csv', index=False)\r\n\r\n\r\n","sub_path":"list_pgtables.py","file_name":"list_pgtables.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"105690055","text":"import os\nimport unittest\nimport json\n\nfrom flaskr import create_app\nfrom models import setup_db, Book\n\nclass BookTestCase(unittest.TestCase):\n '''\n Test Class to endpoints and database testing\n '''\n\n def setUp(self):\n '''\n Test Variables\n '''\n self.app = create_app()\n self.client = self.app.test_client\n self.database_name = \"bookshelf_test\"\n self.database_path = \"postgresql://{}:{}@{}/{}\".format(\n \"student\", \"123\", \"127.0.0.1:5432\", self.database_name\n )\n setup_db(self.app, self.database_path)\n\n self.new_book = {\n \"title\": \"Test Book\",\n \"author\": \"Test Author\",\n \"rating\": \"5\"\n }\n\n # ----\n def tearDown(self):\n '''\n Execute after reach test\n '''\n pass\n\n def test_index(self):\n res = self.client().get('/')\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n self.assertTrue(data[\"total_books\"])\n self.assertTrue(len(data['books']))\n\n def test_update_rating(self):\n res = self.client().patch(\"/books/3\", json={\"rating\": 3})\n data = json.loads(res.data)\n book = Book.query.filter(Book.id == 3).one_or_none()\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data[\"success\"], True)\n self.assertEqual(book.format()[\"rating\"], 3)\n\n def test_create_book(self):\n res = self.client().post('/books', json=self.new_book)\n data = json.loads(res.data)\n\n self.assertEqual(res.status_code, 200)\n self.assertEqual(data['success'], True)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"backend/test_flaskr.py","file_name":"test_flaskr.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"190262438","text":"#!/usr/bin/python3\n\nimport logging\nimport os\n\nlogger = logging.getLogger(\"nitsi.recipe\")\n\n\n\nclass RecipeExeption(Exception):\n def __init__(self, message):\n self.message = message\n\n\n\n# Should read the test, check if the syntax are valid\n# and return tuples with the ( host, command ) structure\nclass Recipe():\n def __init__(self, path, circle=[], machines=[], fallback_machines=[], include_path=None):\n self.recipe_file = path\n try:\n self.path = os.path.dirname(self.recipe_file)\n self.path = os.path.abspath(self.path)\n self.name = os.path.basename(self.path)\n except BaseException as e:\n logger.error(\"Failed to get the path to this recipe\")\n raise e\n\n self.log = logger.getChild(self.name)\n self.log.debug(\"Path of recipe is: {}\".format(self.recipe_file))\n\n # This path must be absolut\n self.include_path = include_path\n\n if self.include_path and not os.path.isabs(self.include_path):\n raise RecipeExeption(\"Include path must be absolut.\")\n\n self.log.debug(\"Include path is: {}\".format(self.include_path))\n\n self._recipe = None\n self._machines = machines\n self._fallback_machines = fallback_machines\n\n self.log.debug(\"Machine names we use when we substitute the all statement: {}\".format(self._machines))\n\n self.log.debug(\"Length of the cirle list {}\".format(len(circle)))\n self.in_recursion = True\n if len(circle) == 0:\n self.in_recursion = False\n\n self.log.debug(\"We are in a recursion: {}\".format(self.in_recursion))\n\n self.circle = circle\n self.log.debug(\"Recipes we have already included: {}\".format(self.circle))\n\n if not os.path.isfile(self.recipe_file):\n self.log.error(\"{} is not a file\".format(self.recipe_file))\n raise RecipeExeption(\"{} is not a file\".format(self.recipe_file))\n\n try:\n with open(self.recipe_file) as fobj:\n self.raw_recipe = fobj.readlines()\n except FileNotFoundError as error:\n self.log.error(\"No such file: {}\".format(self.recipe_file))\n raise error\n\n @property\n def recipe(self):\n if not self._recipe:\n self.parse()\n\n return self._recipe\n\n @property\n def machines(self):\n return self._machines\n\n def parse(self):\n self._recipe = []\n i = 1\n for line in self.raw_recipe:\n # Check if the line is empty\n if line.strip() == \"\":\n self.log.debug(\"Skipping empty line {}\".format(i))\n i = i + 1\n continue\n\n # Check if the line is a comment\n if line.strip().startswith(\"#\"):\n self.log.debug(\"Skipping comment in line {}\".format(i))\n i = i + 1\n continue\n\n raw_line = line.split(\":\", 1)\n if len(raw_line) < 2:\n self.log.error(\"Error parsing the recipe in line {}\".format(i))\n raise RecipeExeption(\"Error parsing the recipe in line {}\".format(i))\n cmd = raw_line[1].strip()\n\n raw_line = raw_line[0].strip().split(\" \")\n if len(raw_line) == 0:\n self.log.error(\"Failed to parse the recipe in line {}\".format(i))\n raise RecipeExeption(\"Failed to parse the recipe in line {}\".format(i))\n\n if raw_line[0].strip() == \"\":\n self.log.error(\"Failed to parse the recipe in line {}\".format(i))\n raise RecipeExeption(\"Failed to parse the recipe in line {}\".format(i))\n\n machine = raw_line[0].strip()\n\n if len(raw_line) == 2:\n extra = raw_line[1].strip()\n else:\n extra = \"\"\n\n # We could get a machine here or a include statement\n if machine == \"include\":\n path = cmd.strip()\n if self.include_path:\n path = os.path.normpath(self.include_path + \"/\" + path)\n else:\n path = os.path.normpath(self.path + \"/\" + path)\n\n # If we did not get a valid file we asume that we get a valid path to a test.\n if os.path.isdir(path):\n path = path + \"/recipe\"\n\n self.log.debug(\"Path of recipe to include is: {}\".format(path))\n\n if path in self.circle:\n self.log.error(\"Detect import loop!\")\n raise RecipeExeption(\"Detect import loop!\")\n self.circle.append(path)\n recipe_to_include = Recipe(path, circle=self.circle, include_path=self.include_path)\n\n if machine == \"include\":\n self._recipe.extend(recipe_to_include.recipe)\n else:\n # Support also something like 'alice,bob: echo'\n machines = machine.split(\",\")\n for machine in machines:\n self._recipe.append((machine.strip(), extra.strip(), cmd.strip()))\n\n # Increase the line number by one\n i = i + 1\n\n # Substitue the all statement\n if not self.in_recursion:\n self.log.debug(\"We are not in a recursion\")\n # We will store the machine names we use to substitute the all statement\n # in tmp_machines to keep the code which actually does the substitution clear\n tmp_machines = None\n\n # Check if we get a setting to substitute the all statement\n if len(self.machines) != 0:\n tmp_machines = self.machines\n\n # Second try to fill tmp_machines\n if not tmp_machines:\n # dertermine machines we use in this recipe\n tmp = []\n for line in self.recipe:\n self.log.debug(line)\n if not line[0] in tmp and line[0] != \"all\":\n tmp.append(line[0])\n\n self.log.debug(\"Machines except all in the recipe: {}\".format(tmp))\n\n # Check if we got anything else then all: in th recipe\n if len(tmp) != 0:\n tmp_machines = tmp\n\n # If we get here we are using all machines in the virtual environment as fallback value\n if not tmp_machines:\n tmp_machines = self._fallback_machines\n\n tmp_recipe = []\n for line in self._recipe:\n if line[0] != \"all\":\n tmp_recipe.append(line)\n else:\n for machine in tmp_machines:\n tmp_recipe.append((machine.strip(), line[1], line[2]))\n\n self._recipe = tmp_recipe\n","sub_path":"src/nitsi/recipe.py","file_name":"recipe.py","file_ext":"py","file_size_in_byte":6761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"242714431","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndata=pd.read_csv(\"Salary_Data.csv\")\nprint(data.columns)\na=data[\"YearsExperience\"]\n#print(a,type(a))\nb=data[\"Salary\"]\n#print(b,type(b))\nl1=a.tolist()\nprint(l1)\nl2=b.tolist()\nprint(l2)\n\nc=sum(l1) # Summation x\nprint(c)\nd=sum(l2) # Summation y\nprint(d)\n\npro=[]\nfor i,j in zip(l1,l2):\n pro.append(i*j)\nprint(pro)\ne=sum(pro) # Summation xy\nprint(e)\n\n\nl3=[]\nfor i in l1:\n l3.append(i*i)\nprint(l3)\n\n\nf=sum(l3) # Summation of x^2\nprint(f)\n\ng=c*c # summation x whole square\nprint(g)\n\nn=30\nm=((n*e)-(c*d))/((n*f)-g) # m= (n*summation(xy)-(summation(x).summation(y)))/ ((n*summation(x^2)-(summation(x))^2)\nprint(m)\n\nk=(d-(m*c))/n # c=(summation(y)-m*summation(x))/n\nprint(k)\n\nfor i in x_test:\n y_p=(m*i)+k\n print(y_p)\n\n","sub_path":"Simple Linear Regression/Code files/Manual Interpretation of Simple Linear Regression.py","file_name":"Manual Interpretation of Simple Linear Regression.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"241000963","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport unittest\r\n\r\nclass testWebsite(unittest.TestCase):\r\n \r\n def test_HomePage(self):\r\n\r\n driver = webdriver.Chrome()\r\n driver.get('http://www.python.org')\r\n\r\n print(driver.title)\r\n self.assertIn('Welcome to Python', driver.title)\r\n driver.quit()\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"Website/Testing/Acceptance_Testing/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"383569002","text":"from scipy.linalg import expm\nfrom pandas import DataFrame\nfrom helpers import draw\nfrom numpy import diag\n\n\nclass Edge:\n heads = {\n 'arrow': 'normal',\n 'open': 'odot',\n 'none': 'none'\n }\n\n def __init__(self, node1, node2, head1, head2):\n self.data = {\n (node1, self.heads[head1]),\n (node2, self.heads[head2])\n }\n\n def __eq__(self, other):\n return isinstance(other, self.__class__) and self.data == other.data\n\n def __hash__(self):\n data = sorted(self.data, key=lambda d: d[0].name)\n return hash(tuple(map(lambda d: d[0].name, data)))\n\n def augmented(self):\n return any(map(lambda node: node.augmented, self.nodes()))\n\n def nodes(self, type=None, name=None):\n for c in self.data:\n if type and not c[0].type == type:\n continue\n if name and not c[0].name == name:\n continue\n yield c[0]\n\n def is_between(self, node1, node2):\n return self.nodes() == {node1, node2}\n\n def has_node_of_type(self, type):\n return len(list(self.nodes(type=type))) > 0\n\n def dot_output(self):\n c1, c2 = sorted(self.data, key=lambda x: x[1])\n if c1[1] == c2[1]:\n return f'{c1[0]}->{c2[0]}[dir=\"both\", arrowhead=\"{c1[1]}\"];\\n'\n return f'{c1[0]}->{c2[0]}[arrowtail=\"{c1[1]}\", arrowhead=\"{c2[1]}\"];\\n'\n\n\nclass Node:\n def __init__(self, id, type, name, shape, augmented):\n self.id = id\n self.type = type\n self.name = name + str(id)\n self.edges = set()\n self.shape = shape\n self.augmented = augmented\n\n def __eq__(self, other):\n return isinstance(other, self.__class__) and self.name == other.name\n\n def __hash__(self):\n return hash(self.name)\n\n def __str__(self):\n return self.name\n\n def has_type(self, type):\n return self.type == type\n\n def is_parent_of(self, node):\n options = {\n Edge(self, node, 'arrow', 'arrow'),\n Edge(self, node, 'open', 'arrow'),\n Edge(self, node, 'none', 'arrow')\n }\n return len(options & self.edges) > 0\n\n def adjacent_nodes(self, type=None, sort=False):\n nodes = set()\n for edge in self.edges:\n nodes = nodes | {node for node in edge.nodes()}\n nodes = nodes - {self}\n if type:\n nodes = filter(lambda node: node.has_type(type), nodes)\n if sort:\n return sorted(nodes, key=lambda x: x.name)\n return nodes\n\n def parents(self, type=None):\n return filter(lambda node: node.is_parent_of(self),\n self.adjacent_nodes(type))\n\n def children(self, type=None):\n return filter(lambda node: self.is_parent_of(node),\n self.adjacent_nodes(type))\n\n def order(self):\n return len(self.edges)\n\n def dot_output(self, augmented=False):\n if not augmented and self.augmented:\n if len(list(self.children())) == 2:\n return '{}->{}[dir=\"both\"];\\n'.format(\n *{node.name for node in self.adjacent_nodes(sort=True)}\n )\n return ''\n return f'{self.name}[label=\"{self.name}\", shape={self.shape}];\\n'\n\n\nclass Graph:\n def __init__(self):\n self.nodes = set()\n self.edges = set()\n\n def get_nodes(self, type=None, name=None, sort=False):\n nodes = self.nodes\n if type:\n nodes = [node for node in nodes if node.type == type]\n if name:\n nodes = [node for node in nodes if node.name == name]\n if sort:\n return sorted(nodes, key=lambda node: node.name)\n return nodes\n\n def get_edges(self, augmented=False):\n if augmented:\n return self.edges\n edges = set()\n for edge in self.edges:\n if not edge.augmented():\n edges.add(edge)\n return edges\n\n def adjacency_matrix(self, type, sort=False):\n matrix = DataFrame(\n 0,\n index=self.get_nodes(type, sort=sort),\n columns=self.get_nodes(type, sort=sort)\n )\n for node in self.get_nodes(type):\n for child in node.children(type=type):\n matrix.at[node, child] = 1\n for parent in node.parents(type=type):\n matrix.at[parent, node] = 1\n return matrix\n\n def ancestral_matrix(self, type):\n adj_mat = self.adjacency_matrix(type=type, sort=True)\n anc_mat = adj_mat.copy()\n n = len(self.get_nodes(type=type))\n for i in range(n):\n anc_mat = anc_mat.add(anc_mat.dot(adj_mat))\n return anc_mat.applymap(lambda val: min(1, val))\n\n def is_acyclic(self, type):\n exp = expm(self.adjacency_matrix(type=type).to_numpy())\n return abs(sum(diag(exp))) - len(self.get_nodes(type=type)) < 1e-10\n\n def add_node(self, type, name, shape, augmented=False, id=None):\n ids = [v.id for v in self.get_nodes(type=type)]\n id = max(ids) + 1 if ids else 0\n node = Node(id, type, name, shape, augmented)\n self.nodes.add(node)\n return node\n\n def add_edge(self, edge):\n self.edges.add(edge)\n for node in edge.nodes():\n node.edges.add(edge)\n\n def add_directed_edge(self, node1, node2, random=False):\n if random and draw(0.5):\n edge = Edge(node2, node1, 'none', 'arrow')\n else:\n edge = Edge(node1, node2, 'none', 'arrow')\n self.add_edge(edge)\n\n def has_edge_between(self, node1, node2):\n for edge in self.edges:\n if edge.is_between(node1, node2):\n return True\n return False\n\n def dot_output(self, augmented=False):\n out = 'digraph G {\\n'\n for node in self.get_nodes(sort=True):\n out += node.dot_output(augmented)\n for edge in self.get_edges(augmented):\n out += edge.dot_output()\n out += '}\\n'\n return out\n","sub_path":"graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":6014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"432287204","text":"import pymongo\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom pyquery import PyQuery as pq\nfrom urllib.parse import quote\nimport json\nKEYWORD = 'iphone'\n#Chrome Headless模式\nchrome_options = webdriver.ChromeOptions()\nchrome_options.add_argument('--headless')\nbrowser = webdriver.Chrome(chrome_options=chrome_options)\n\nwait = WebDriverWait(browser, 10)\ndef index_page(page):\n print('正在爬取第', page, '页')\n try:\n url = 'https://s.taobao.com/search?q=' + quote(KEYWORD)\n browser.get(url)\n if page > 1:\n input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-pager div.form > input.J_Input')))\n input.clear()\n input.send_keys(page)\n submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#mainsrp-pager div.form > span.btn.J_Submit')))\n submit.click()\n\t\t\t#检查高亮文本是否为page\n wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, '#mainsrp-pager li.item.active > span'), str(page)))\n wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.m-itemlist .items .item')))\n get_products()\n except TimeoutException:\n index_page(page)\n\n\ndef get_products():\n \"\"\"\n 提取商品数据\n \"\"\"\n html = browser.page_source\n doc = pq(html)\n items = doc('#mainsrp-itemlist .items .item').items()\n for item in items:\n product = {\n 'image': item.find('.pic .img').attr('data-src'),\n 'price': item.find('.price').text(),\n 'deal': item.find('.deal-cnt').text(),\n 'title': item.find('.title').text(),\n 'shop': item.find('.shop').text(),\n 'location': item.find('.location').text()\n }\n print(product)\n with open(KEYWORD+'.txt', 'a', encoding='utf-8') as file:\n file.write(json.dumps(product, ensure_ascii=False) + '\\n')\n file.write('\\n' + '=' * 50 + '\\n')\n\n\nif __name__ == '__main__':\n for i in range(1,101):\n index_page(i)\n browser.close()\n","sub_path":"TaoBao/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"458012748","text":"from flask import Flask,g,render_template,request,redirect\r\n#Flask is the main function of my application\r\n\r\nimport sqlite3\r\n#Database that I used\r\n\r\napp = Flask(__name__)\r\n\r\nDATABASE = 'database.db'\r\n#Database that I used to store informations (comments, pictures, links)\r\n\r\ndef get_db():\r\n db= getattr(g, '_database', None)\r\n if db is None:\r\n db = g._database = sqlite3.connect(DATABASE)\r\n return db\r\n#This fuction is used to get the data from the database\r\n\r\n@app.teardown_appcontext\r\ndef close_connection(exception):\r\n db = getattr(g, '_database' , None)\r\n if db is not None:\r\n db.close()\r\n#This fuction is used to close the database after used\r\n\r\n@app.route('/')\r\ndef home():\r\n cursor = get_db().cursor()\r\n sql = 'SELECT * FROM comment'\r\n cursor.execute(sql)\r\n comments = cursor.fetchall()\r\n cursor = get_db().cursor()\r\n sql = 'SELECT * FROM Song'\r\n cursor.execute(sql)\r\n Songs = cursor.fetchall()\r\n return render_template(\"Garage Rock Public Library.html\" , comments=comments, Songs=Songs)\r\n# This function is used to connect to the html file, and adding the information in the database to the website \r\n\r\n@app.route('/add', methods=['GET','POST'])\r\ndef add():\r\n if request.method == 'POST':\r\n cursor = get_db().cursor()\r\n new_Song = request.form['item_Song']\r\n new_comment = request.form['item_comment']\r\n sql = 'INSERT INTO comment(Song,comment) VALUES (?,?)'\r\n cursor.execute(sql,(new_Song,new_comment))\r\n get_db().commit()\r\n return redirect('/')\r\n#This function is used to adding comment to the website and store it in database\r\n\r\n@app.route('/delete', methods=['GET','POST'])\r\ndef delete():\r\n if request.method =='POST':\r\n cursor = get_db().cursor()\r\n id = int(request.form['item_Song'])\r\n sql = 'DELETE FROM comment WHERE id=?'\r\n cursor.execute(sql,(id,))\r\n get_db().commit()\r\n return redirect('/')\r\n#This function is used to delete the comments from the website and the database\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","sub_path":"Flask.py","file_name":"Flask.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"196652711","text":"from __future__ import unicode_literals\n\nimport sys\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\nfrom PennTreeBankParser import PennTreeBankParser\nfrom ParserBase import ParserBase\nfrom IDMap import IDMap\nfrom constants import *\n\n__author__ = 'arvie'\n\n\n'''\n The bartha dataset is structured as\n icml14-data: as the root\n cs-en: etc. where the last listed language has the mono-language data\n 1m-mono: as the small dataset\n mono: as the large dataset (which was obtained from contacting Jan Botha)\n\nThis class works like the PennTreeBankParser with the expeption that\n\nset_current_dataset(data_set_langauge = 'cs-en', data_set_size = '1m-mono')\n\nmust be called before any of the parent class functions\n\n'''\nclass BothaParser(PennTreeBankParser):\n def __init__(self, special_list = [], in_path = '/u/arvie/PHD/Neural_Language_Models/botha_data/icml14-data/',\n out_root = '/u/arvie/PHD/Neural_Language_Models/botha_data/out/'):\n\n ParserBase.__init__(self, special_list=special_list)\n\n self.data_in_path = in_path\n self.data_out_root = out_root\n self.data_in_path_original = in_path\n self.data_out_root_original = out_root\n\n self.data_files = ['train.in', 'test.in', 'finaltest.in']\n self.extention_length = 3\n\n # the data set is the second one i.e en, cs, de, es, fr, ru\n self.data_set_languages = ['cs-en', 'en-cs', 'en-de', 'en-es', 'en-fr', 'en-ru']\n self.data_sets = ['1m-mono', 'mono']\n\n def get_language(self, lang):\n return lang.split('-')[1]\n\n def set_current_dataset(self, data_set_langauge = 'cs-en', data_set_size = '1m-mono'):\n if data_set_size not in self.data_sets:\n print('ERROR in BothaParser: incorect dataset size specified: ' + data_set_size)\n return\n if data_set_langauge not in self.data_set_languages:\n print('ERROR in BothaParser: incorect dataset language specified: ' + data_set_langauge)\n return\n\n self.data_in_path = self.data_in_path_original + data_set_langauge + '/' + data_set_size + '/'\n self.data_out_root = self.data_out_root_original + data_set_langauge + '/' + data_set_size + '/'\n self.update_out_path()\n\n\n def make_datasets_and_id_maps_for_all_data_sets(self, level_list = ['word_level', 'char_level', 'morph_level'],\n text_or_pickle = 'text',\n add_word_end_marker = True, add_word_start_marker = False,\n add_sentence_end_marker=False, add_sentence_start_marker=False,\n morph_train_params = {'count_func':'log'}):\n\n for set in self.data_sets:\n for lang in self.data_set_languages:\n self.set_current_dataset(lang, set)\n self.make_datasets_and_id_maps(level_list = level_list, text_or_pickle=text_or_pickle,\n add_word_end_marker = add_word_end_marker,\n add_word_start_marker=add_word_start_marker,\n add_sentence_end_marker=add_sentence_end_marker,\n add_sentence_start_marker=add_sentence_start_marker,\n morph_train_params=morph_train_params)\n\nif __name__ == \"__main__\":\n parser = BothaParser(special_list=[UNKOWN_WORD])\n parser.make_datasets_and_id_maps_for_all_data_sets(['word_level', 'char_level', 'morph_level'], add_word_end_marker=True, text_or_pickle = 'text')","sub_path":"data_processors/BothaParser.py","file_name":"BothaParser.py","file_ext":"py","file_size_in_byte":3674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"168358117","text":"import datetime\nimport unittest\nimport psycopg2\nimport socorro.cron.dailyMatviews # needed for Mock\nimport socorro.cron.dailyMatviews as dailyMatviews\n\nfrom socorro.lib.datetimeutil import utc_now\n\nfrom socorro.unittest.config.commonconfig import databaseHost\nfrom socorro.unittest.config.commonconfig import databaseName\nfrom socorro.unittest.config.commonconfig import databaseUserName\nfrom socorro.unittest.config.commonconfig import databasePassword\n\nfrom mock import patch\n\n\nclass mock_connection:\n def __init__(self, c):\n self.c = c\n\n def _void(self):\n pass\n\n commit = rollback = _void\n\n def cursor(self):\n return self.c\n\n\nclass mock_psycopg2:\n InternalError = Exception\n\n def __init__(self, cursor):\n self.cursor = cursor\n\n def connect(self, *args, **kwargs):\n return mock_connection(self.cursor)\n\n\nclass mock_cursor:\n def __init__(self, returns):\n self.returns = returns\n self.called = []\n\n def callproc(self, name, params):\n self.name = name\n self.called.append(name)\n\n def fetchone(self):\n if self.name in self.returns:\n return self.returns[self.name]\n return (True,)\n\n def execute(self, sql, params):\n pass\n\n\nclass TestCase(unittest.TestCase):\n def setUp(self):\n self.config = {\n 'databaseHost': '',\n 'databasePassword': '',\n 'databaseName': '',\n 'databaseUserName': '',\n }\n\n def test_failing__update_product_versions(self):\n cursor = mock_cursor({\n 'update_product_versions': (False,),\n })\n dailyMatviews.psycopg2 = mock_psycopg2(cursor)\n with patch('socorro.cron.dailyMatviews.logger') as mock_logger:\n dailyMatviews.update(self.config, 'some date')\n self.assertEqual(cursor.called, ['update_product_versions',\n 'update_signatures', 'update_os_versions', 'update_adu',\n 'update_daily_crashes', 'update_hang_report',\n 'update_rank_compare', 'update_nightly_builds'])\n self.assertEqual(mock_logger.info.call_count, 8)\n self.assertEqual(mock_logger.warn.call_count, 2)\n self.assertEqual(mock_logger.error.call_count, 0)\n\n def test_all_works(self):\n cursor = mock_cursor({})\n dailyMatviews.psycopg2 = mock_psycopg2(cursor)\n with patch('socorro.cron.dailyMatviews.logger') as mock_logger:\n dailyMatviews.update(self.config, 'some date')\n self.assertEqual(mock_logger.info.call_count, 9)\n self.assertEqual(mock_logger.warn.call_count, 0)\n self.assertEqual(mock_logger.error.call_count, 0)\n\n def test_mock_internal_error(self):\n cursor = mock_cursor({\n 'update_signatures': psycopg2.InternalError,\n })\n dailyMatviews.psycopg2 = mock_psycopg2(cursor)\n with patch('socorro.cron.dailyMatviews.logger') as mock_logger:\n dailyMatviews.update(self.config, 'some date')\n self.assertEqual(mock_logger.info.call_count, 8)\n self.assertEqual(mock_logger.warn.call_count, 1)\n self.assertEqual(mock_logger.error.call_count, 1)\n\n\nclass FunctionalTestCase(unittest.TestCase):\n\n connection = None\n\n def setUp(self):\n # create the tables\n self.config = {\n 'databaseHost': databaseHost.default,\n 'databaseName': databaseName.default,\n 'databaseUserName': databaseUserName.default,\n 'databasePassword': databasePassword.default,\n }\n\n if not self.connection:\n dsn = 'host=%(databaseHost)s '\\\n 'dbname=%(databaseName)s '\\\n 'user=%(databaseUserName)s '\\\n 'password=%(databasePassword)s' % self.config\n self.connection = psycopg2.connect(dsn)\n cursor = self.connection.cursor()\n cursor.execute(\"\"\"\nDROP TABLE IF EXISTS cronjobs;\nCREATE TABLE cronjobs (\n cronjob VARCHAR,\n last_target_time VARCHAR,\n last_success TIMESTAMP NULL,\n last_failure TIMESTAMP NULL,\n failure_message VARCHAR NULL\n);\nINSERT INTO cronjobs (cronjob) VALUES ('dailyMatviews:update_product_versions');\nINSERT INTO cronjobs (cronjob) VALUES ('dailyMatviews:update_os_versions');\nINSERT INTO cronjobs (cronjob) VALUES ('dailyMatviews:update_tcbs');\nINSERT INTO cronjobs (cronjob) VALUES ('dailyMatviews:update_signatures');\nINSERT INTO cronjobs (cronjob) VALUES ('dailyMatviews:update_adu');\nINSERT INTO cronjobs (cronjob) VALUES ('dailyMatviews:update_daily_crashes');\n CREATE OR REPLACE FUNCTION update_product_versions()\nRETURNS boolean AS $$\nBEGIN\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n CREATE OR REPLACE FUNCTION update_signatures(timestamp with time zone)\nRETURNS boolean AS $$\nBEGIN\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n CREATE OR REPLACE FUNCTION update_os_versions(timestamp with time zone)\nRETURNS boolean AS $$\nBEGIN\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n CREATE OR REPLACE FUNCTION update_tcbs(timestamp with time zone)\nRETURNS boolean AS $$\nBEGIN\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n CREATE OR REPLACE FUNCTION update_adu(timestamp with time zone)\nRETURNS boolean AS $$\nBEGIN\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n CREATE OR REPLACE FUNCTION update_daily_crashes(timestamp with time zone)\nRETURNS boolean AS $$\nBEGIN\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n CREATE OR REPLACE FUNCTION update_hang_report(timestamp with time zone)\nRETURNS boolean AS $$\nBEGIN\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n CREATE OR REPLACE FUNCTION update_rank_compare(timestamp with time zone)\nRETURNS boolean AS $$\nBEGIN\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n CREATE OR REPLACE FUNCTION update_nightly_builds(timestamp with time zone)\nRETURNS boolean AS $$\nBEGIN\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n\n \"\"\")\n self.connection.commit()\n\n def tearDown(self):\n # drop the table\n cursor = self.connection.cursor()\n cursor.execute(\"\"\"DROP TABLE cronjobs;\n DROP FUNCTION update_product_versions () ;\n DROP FUNCTION update_os_versions (timestamp with time zone) ;\n DROP FUNCTION update_signatures (timestamp with time zone) ;\n DROP FUNCTION update_tcbs (timestamp with time zone) ;\n DROP FUNCTION update_adu (timestamp with time zone) ;\n DROP FUNCTION update_daily_crashes (timestamp with time zone) ;\n DROP FUNCTION update_hang_report(timestamp with time zone) ;\n DROP FUNCTION update_rank_compare(timestamp with time zone) ;\n DROP FUNCTION update_nightly_builds(timestamp with time zone) ;\n \"\"\")\n self.connection.commit()\n\n def test_all_works_without_errors(self):\n with patch('socorro.cron.dailyMatviews.logger'):\n dailyMatviews.update(self.config, utc_now().date())\n cursor = self.connection.cursor()\n for each in ('dailyMatviews:update_product_versions',\n 'dailyMatviews:update_os_versions',\n 'dailyMatviews:update_adu',\n 'dailyMatviews:update_tcbs',\n 'dailyMatviews:update_signatures',\n ):\n cursor.execute(\n 'select last_success from cronjobs where cronjob=%s',\n [each]\n )\n last_success = cursor.fetchone()[0]\n self.assertTrue(last_success)\n\n def test_fail__update_product_versions(self):\n with patch('socorro.cron.dailyMatviews.logger'):\n cursor = self.connection.cursor()\n cursor.execute(\"\"\"\n CREATE OR REPLACE FUNCTION update_product_versions()\n RETURNS boolean AS $$\n BEGIN\n RETURN false;\n END;\n $$ LANGUAGE plpgsql;\n \"\"\")\n self.connection.commit()\n\n dailyMatviews.update(self.config, utc_now().date())\n cursor = self.connection.cursor()\n for each in ('dailyMatviews:update_os_versions',\n 'dailyMatviews:update_adu',\n 'dailyMatviews:update_signatures',\n ):\n cursor.execute(\n 'select last_success from cronjobs where cronjob=%s',\n [each]\n )\n last_success = cursor.fetchone()[0]\n self.assertTrue(last_success)\n\n for each in ('dailyMatviews:update_product_versions',\n 'dailyMatviews:update_tcbs',\n ):\n cursor.execute(\n 'select last_success from cronjobs where cronjob=%s',\n [each]\n )\n last_success = cursor.fetchone()[0]\n self.assertTrue(not last_success)\n","sub_path":"socorro/unittest/cron/testDailyMatviews.py","file_name":"testDailyMatviews.py","file_ext":"py","file_size_in_byte":8860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"486974286","text":"import csv\nimport datetime\nimport json\nimport os\nimport re\nimport secrets\nfrom collections import namedtuple\nfrom urllib import parse\nfrom requests import Session, Request, Response\nfrom scrappers.scrappers.config.http._aws import TransferManager\nfrom mimetypes import guess_type\nfrom scrappers.scrappers.config.http import user_agent\n\nBASE_PATH = os.path.dirname(os.path.abspath(__file__))\n\nenvironment = os.environ\n\nHOME_DRIVE = '%s\\\\Users\\\\%s\\\\Documents' % (\n environment.get('HOMEDRIVE'),\n environment.get('USERNAME')\n)\n\nOUTPUT_DIR = 'WTA_Data'\n\n# def file_opener(func):\n# def opener(values, path, mode='r'):\n# f = open(path, mode, encoding='utf-8')\n# func(values, f, indent=4)\n# return True\n# return opener\n\ndef image_cache(func):\n \"\"\"A simple cache decorator that saves the \n images locally in order to prevent having\n get them back while running the application\n \"\"\"\n def _cache(*args):\n cache = []\n for item in func():\n cache.append(item)\n return cache\n return _cache()\n\ndef writer(values, filename='', extension='txt'):\n \"\"\"A utility used to output data to a file\n \"\"\"\n filename = filename + '.%s' % extension\n with open(filename, 'w', newline='') as f:\n if extension == 'txt':\n for value in values:\n f.writelines(value)\n f.writelines('\\n')\n elif extension == 'csv':\n csv_file = csv.writer(f)\n for value in values:\n csv_file.writerow(value)\n\ndef guess_celebrity(url, pattern):\n \"\"\"Get the celebrity's name from the url,\n using a regex pattern\n \"\"\"\n celebrity = namedtuple('Celibrity', ['name', 'name_with_dash'])\n # ('', '/path/')\n parsed_url = parse.urlparse(url)\n unparsed_celebrity_name = re.search(pattern, parsed_url[2])\n if unparsed_celebrity_name:\n celebrity_name = unparsed_celebrity_name.group(0).split('-')\n for i in range(len(celebrity_name)):\n celebrity_name[i] = celebrity_name[i].lower()\n else:\n return 'Anonymous'\n\n normal = ' '.join(celebrity_name).strip().capitalize()\n dash = '-'.join(celebrity_name).strip()\n\n return celebrity(normal, dash)\n\ndef prepare_values(func):\n \"\"\"A decorator for a class function that prepares \n a set of values for writting in a CSV, TXT or JSON file\n\n Example\n -------\n\n class Test:\n @prepare_values\n def save(self):\n return values\n \"\"\"\n def prepare(self, celebrity=None, *headers):\n current_date = datetime.datetime.now()\n # Get values\n values = func(self)\n # Header [date, celibrity name]\n values_wrapper = [\n [f'{current_date}', f'{celebrity}']\n ]\n # values_wrapper = [\n # [header for header in headers]\n # ]\n # [[date, celibrity name], values]\n values_wrapper.append(values)\n\n with open(os.path.join(BASE_PATH, 'test.txt'), 'w', encoding='utf-8') as f:\n # Write [date, celibrity name]\n f.writelines(values_wrapper[0])\n f.writelines('\\n')\n \n # Write [[...], values]\n for value in values_wrapper[1]:\n f.writelines(value)\n f.writelines('\\n')\n # NOTE: Return values. \n # Not really necessary\n return values_wrapper\n return prepare\n\n# @file_opener\n# def write_to_json(path):\n# # json.dump(refactored_stats, f, indent=4)\n# return json.dumps\n# write_to_json\n\ndef check_path(folder_or_file):\n \"\"\"Checks if the path exists and creates the required files.\n \n The `folder_or_file` parameter should be a folder or file name that\n is checked in the `HOMEDRIVE` of the user.\n\n Output\n ------\n\n E:\\\\path\\\\to\\\\use\n \"\"\"\n path = os.path.join(HOME_DRIVE, folder_or_file)\n path_exists = os.path.exists(path)\n if not path_exists:\n user_input = input('The path (%s) does not exist. '\n 'Do you wish to create it? (Y/N) ' % folder_or_file)\n\n if user_input == 'Y':\n # Create\n os.makedirs(path)\n print('Created!')\n return path\n elif user_input == 'N':\n quit\n else:\n quit\n else:\n return path\n\ndef new_filename(name):\n \"\"\"Create a new file name such as `name_2019_05_AVSOIV`\n \"\"\" \n current_date = datetime.datetime.now()\n token = secrets.token_hex(3)\n return f'{name.lower()}_{current_date.year}_{current_date.month}_{token}.json'\n\n# class EnrichPlayer:\n# \"\"\"\n# \"\"\"\n# def __init__(self, player_name):\n# try:\n# from googlesearch import search, search_images\n# except ImportError:\n# raise\n\n# # response = search(player_name, stop=5, pause=2)\n# response = search_images(player_name, stop=5, pause=2, extra_params={'biw':1024,'bih':768})\n# print(list(response))\n\ndef position_to_number(func):\n \"\"\"Decorator that transforms volleyball positions\n into numerical positions.\n\n Description\n -----------\n\n The usal positions on a volleyball court are:\n\n 4 3 2\n -----------\n 5 6 1\n\n Setter -> 1\n Outside Hitter -> 2\n Middle Blocker -> 3\n Universal -> 4\n Libero -> 6\n \"\"\"\n def convert(self, position):\n if not isinstance(position, int):\n raise TypeError\n \n positions = ['Setter', 'Outside Hitter', 'Middle Blocker']\n\n if position == 'Universal':\n return 4\n \n if position in positions:\n return positions.index(position) + 1\n \n return None\n return convert\n\ndef create_request(url, data=False):\n \"\"\"A reusable method to create requests\n\n Description\n -----------\n\n This definition was created in order to customize the\n headers and various different elements of the requests\n method\n \"\"\"\n session = Session()\n\n headers = {\n 'User-Agent': user_agent.get_rand_agent()\n }\n\n print('[REQUEST]: GET 1/1: %s' % url)\n\n request = Request('GET', url, headers)\n prepared_request = request.prepare()\n response = session.send(prepared_request)\n # return '[%s]' % response.status_code\n\n if data:\n return response.content\n \n return response\n\ndef prepare_for_s3(func):\n def read_and_transfer(self, manager=TransferManager, **kwargs):\n \"\"\"Use this decorator function to read an image from an url in order\n to upload it to an Amazon S3 bucket.\n\n Parameters\n ----------\n\n The `manager` parameter accepts a class that structures a logic\n that can be used to upload an image to a bucket of your choice.\n\n The default bucket is the AWS S3.\n\n The class should be structured such as an `upload` function could\n be used to upload the content:\n\n class YourClass:\n def __init__(self):\n pass\n\n def upload(self):\n pass\n\n The `kwargs` are any additional pieces of information\n (access key, secret key...) that can be used to successfully connect\n to your bucket or cloud. Note that generally, these services often require\n an access key and/or secret key and are checked by default.\n \"\"\"\n\n @image_cache\n def images():\n return func(self)\n\n if not callable(manager) and not isinstance(manager, type):\n pass\n\n Klass_dict = manager.__dict__\n\n print(Klass_dict)\n\n if 'upload' in Klass_dict:\n try:\n access_key = kwargs['access_key']\n secret_key = kwargs['secret_key']\n region = kwargs['region']\n bucket = kwargs['bucket']\n except KeyError:\n pass\n else:\n # Create and instance of the class\n Klass = manager(access_key, secret_key, region, bucket)\n else:\n pass \n\n for url in images:\n print('[IMAGE]: uploading - %s' % url)\n response = create_request(url)\n # image_content = response.iter_content(chunk_size=1024)\n\n try:\n name = re.match(r'(?:\\/\\d+\\/\\d+\\/)((?:\\w+\\-?\\w+\\-?)+\\.\\w+)', url)\n except:\n pass\n else:\n contenttype = guess_type(name)\n\n Klass.upload(response.content, '/', contenttype[0])\n \n return True\n return read_and_transfer\n","sub_path":"apps/config/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":8648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"147327450","text":"#!/usr/bin/env python\n\n#import win32com.client\n#\n#\n#cat = win32com.client.Dispatch(r'ADOX.Catalog')\n#cat.Create(\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db.mdb\")\n\nimport pyodbc\n\ncon = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb)};Dbq=db.mdb;Uid=;Pwd=;')\n\n\ncur = con.cursor()\nstring = \"CREATE TABLE TestTable(symbol varchar(15), leverage double, shares integer, price double)\"\ncur.execute(string)\n\ncon.commit()\n\n\n","sub_path":"dpid/mdb_create.py","file_name":"mdb_create.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"375809514","text":"import glob\nimport numpy as np\nimport os\nimport random\nimport librosa\n\nVALIDATION_SET_SIZE = 0.2\n\ndef bool_random(prob):\n r = random.random()\n if r <= prob:\n return True\n else:\n return False\n\n\ndef read_voice_files(dir_path):\n filenames = glob.glob(dir_path + \"*.wav\")\n name_to_files = dict()\n for i in range(len(filenames)):\n filepath = filenames[i]\n person_name = filepath.split(\"\\\\\")[-1].split(\".\")[0].split(\"-\")[:2]\n person_name = person_name[0] + \"-\" + person_name[1]\n if person_name in name_to_files.keys():\n name_to_files[person_name].append(filepath)\n else:\n name_to_files[person_name] = [filepath]\n return name_to_files\n\n\ndef train_validation_split(validation_size, name_to_files):\n X_t = dict()\n X_v = dict()\n for k, v in name_to_files.items():\n for f in v:\n belongs_to_validation = bool_random(validation_size)\n if belongs_to_validation:\n if k in X_v:\n X_v[k].append(f)\n else:\n X_v[k] = [f]\n else:\n if k in X_t:\n X_t[k].append(f)\n else:\n X_t[k] = [f]\n\n return X_t, X_v\n\n# Given folder containing audio files (*.wav)\n# returns split filenames into training and validation sets\ndef get_data(audio_folder):\n files_dict = read_voice_files(audio_folder)\n return train_validation_split(VALIDATION_SET_SIZE, files_dict)","sub_path":"src/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"156473149","text":"def get_min(current_x, current_y, sequence_a, sequence_b, matrix):\n \"\"\"\n\n :param current_x: the current x value in respect to the matrix\n :param current_y: the current y value in respect to the matrix\n :param sequence_a: the sequence a which is currently encoded in the matrix\n :param sequence_b: the sequence b which is currently encoded in the matrix\n :param matrix: the matrix which is used of DP of the NW algorithm\n :return: the minimum of the values\n \"\"\"\n\n top_left = matrix[current_x - 1][current_y - 1]\n left = matrix[current_x - 1][current_y] + 1\n top = matrix[current_x][current_y - 1] + 1\n if sequence_b[current_x - 1] != sequence_a[current_y - 1]:\n top_left += 1\n return min(top_left, left, top)\n\n\ndef backtrace(solution, sequence_a, sequence_b, matrix, x, y, str_res):\n \"\"\"\n\n :param solution: where the solution will be stored array of strings\n :param sequence_a: the sequence a which is currently encoded in the matrix\n :param sequence_b: the sequence b which is currently encoded in the matrix\n :param matrix: the matrix which is used of DP of the NW algorithm\n :param x: the current value of the x backtrace\n :param y: the current value of the y backtrace\n :param str_res: the result string\n :return: nothing, all happens with side effects\n \"\"\"\n\n if x == 0 and y == 0:\n return\n if x == 0:\n str_res.append(\"top\")\n solution.insert(0, {\"kind\": \"delete\", \"data\": int(sequence_b[y - 1])})\n y = y - 1\n return backtrace(solution, sequence_a, sequence_b, matrix, x, y, str_res)\n if y == 0:\n str_res.append(\"left\")\n solution.insert(0, {\"kind\": \"insert\", \"data\": int(sequence_a[x - 1])})\n x = x - 1\n return backtrace(solution, sequence_a, sequence_b, matrix, x, y, str_res)\n if matrix[y - 1][x - 1] <= matrix[y][x - 1] and matrix[y - 1][x - 1] <= matrix[y - 1][x]:\n if matrix[y][x] == matrix[y - 1][x - 1]:\n str_res.append(\"keep\")\n solution.insert(0, {\"kind\": \"keep\", \"data\": int(sequence_a[x - 1])})\n x = x - 1\n y = y - 1\n return backtrace(solution, sequence_a, sequence_b, matrix, x, y, str_res)\n if matrix[y][x - 1] <= matrix[y - 1][x]:\n str_res.append(\"left\")\n solution.insert(0, {\"kind\": \"insert\", \"data\": int(sequence_a[x - 1])})\n x = x - 1\n return backtrace(solution, sequence_a, sequence_b, matrix, x, y, str_res)\n else:\n str_res.append(\"top\")\n solution.insert(0, {\"kind\": \"delete\", \"data\": int(sequence_b[y - 1])})\n y = y - 1\n return backtrace(solution, sequence_a, sequence_b, matrix, x, y, str_res)\n\n\ndef needleman_wunsch(sequence_a, sequence_b):\n \"\"\"\n\n :param sequence_a: The sequence to analyse\n :param sequence_b: The sequence to analyse with\n :return: minimal bets fitting overlay\n \"\"\"\n matrix = []\n for j in range(0, len(sequence_b)+1):\n tmp = [0]*(len(sequence_a)+1)\n matrix.append(tmp)\n\n for j in range(1, len(sequence_b)+1):\n matrix[j][0] = j\n\n for i in range(1, len(sequence_a)+1):\n matrix[0][i] = i\n\n for j in range(1, len(sequence_b)+1):\n for i in range(1, len(sequence_a)+1):\n matrix[j][i] = get_min(j, i, sequence_a, sequence_b, matrix)\n\n solution = []\n str_res = []\n backtrace(solution, sequence_a, sequence_b, matrix, len(sequence_a), len(sequence_b), str_res)\n return solution\n\n\ndef round_with_offset(offset, rounding, value):\n \"\"\"\n\n :param offset: offset for the first rounding value\n :param rounding: rounding value\n :param value: the value which to round\n :return: the rounded value\n \"\"\"\n\n tmp1 = value\n tmp2 = tmp1 % rounding\n tmp3 = (tmp1 - tmp2) + offset\n return tmp3\n\n\ndef to_usable_buffer(solution_buffer, use_deleted=True):\n \"\"\"\n\n :param solution_buffer: buffer which will be filtered\n :param use_deleted: use the deleted to display\n :return: return the filtered buffer\n \"\"\"\n\n usable_buffer = []\n for i in range(0, len(solution_buffer)):\n if not use_deleted and solution_buffer[i][\"kind\"] == \"delete\":\n continue\n usable_buffer.append(solution_buffer[i][\"data\"])\n return usable_buffer\n\n\ndef get_color(kind):\n \"\"\"\n\n :param kind: kind of the node in respect to NW algorithm\n :return: the color\n \"\"\"\n\n if kind == \"delete\":\n return 1, 0, 0, 1\n if kind == \"insert\":\n return 0, 1, 0, 1\n if kind == \"missmatch\":\n return 0, 0, 1, 1\n return 0, 0, 0, 1\n\n\n","sub_path":"REyeker-DataAnalyses-Python/modules/NeedlemanWunsch.py","file_name":"NeedlemanWunsch.py","file_ext":"py","file_size_in_byte":4731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"281503615","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ntf.set_random_seed(1)\nnp.random_seed(1)\n\nx = np.linspace(-1,1,100)[:,np.newaxis]\n#Simply put, the newaxis is used to increase the dimension of the existing array by one more dimension, when used once\n\nnoise = np.random_normal(0,0.1,size = x.shape)\ny = np.power(x,2)+noise\n\n#plot\nplt.scatter(x,y)\nplt.show()\n\ntf_x = tf.placeholder(tf.float32,x.shape)\ntf_y = tf.placeholder(tf.float32,y.shape)\n\n# nn layers\nl1 = tf.layers.dense(tf_x,10,tf.nn.relu) #hidden layer\noutput = tf.layers.dense(l1,1) # output layer\n\nloss= tf.losses.mean_squared_error(tf_y,output)\noptimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.5)\ntrain_op = optimizer.minimize(loss)\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\nfor step in range(100):\n _,l,pred = sess.run([train_op,loss,output],{tf_x:x,tf_y:y})\n if step % 10 == 0:\n plt.cla()\n plt.scatter(x,y)\n plt.plot(x,pred,'r-',lw=5)\n plt.text(0.5,0,'Loss=%.4f'%l,fontdict={'size':20,'color':'red'})\n plt.pause(0.1)\nplt.ioff()\nplt.show()\n","sub_path":"regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"386960235","text":"from common.http_request_new import Request\nfrom common.read_xls_news import Read_xls\nfrom common.list_dict import Conversion\nfrom common.log import Logger\nimport re,json\n\nfilepath='E:\\\\python_space\\\\AITEST\\\\testdata\\\\testdata1.xls'\ndef DataConversion(filepath,n=None,l=None):\n if n==None:\n n=2\n if l==None:\n l=8\n testdata=Read_xls(filepath).read_data(start_line=2)\n # testdata1=testdata[redis_case]\n key_list=testdata[0][n:(n+l)]\n data_list=testdata[1:]\n list_datas = []\n for each in data_list:\n data = {}\n data['id']=each[0]\n data[\"场景描述\"]=each[1]\n # data[\"校验\"]=each[-redis_case]\n m = len(each) // l\n for i in range(0, m):\n if i == 0:\n list0 = each[n:(n+l)]\n else:\n list0 = each[i*l+n:(i+1)*l+n]\n onedata_dict=Conversion().list_dict(list0,key_list)\n data[\"接口%s\"%(i+1)]=onedata_dict\n i+=1\n data[\"期望值\"] = each[-1]\n # list_datas.append(str(data))\n list_datas.append(data)\n # Logger().log(\"测试数据读取完毕!\")\n return list_datas\n\nif __name__==\"__main__\":\n data=DataConversion(filepath)\n print(data)\n\ndata11={\n\t\t'url': 'http://bkt.jeagine.com/api/user/signin',\n\t\t'type': 'get',\n\t\t'header': '',\n\t\t'参数': \"{'account': '13017600000', 'appKey': 'all', 'category_id': 80, 'password': '123456', 'terminal': 2}\",\n\t\t'继承参数': '',\n\t\t'调用参数': '',\n\t\t'下传参数': '{\"uid\":\"user=>id\"}',\n '校验': ''\n\t}\n\ndef OnlyInterface(**data):\n url = data['url']\n type = data['type']\n header = data['header']\n testdata = data['参数']\n check=data['校验']\n if isinstance(testdata,dict):\n pass\n else:\n try:\n testdata = eval(testdata)\n except Exception as e:\n Logger().error(e)\n testdata={}\n\n up_data = data['继承参数']\n if up_data == '':\n up_data={}\n else:\n try:\n up_data = eval(up_data)\n except Exception as e:\n Logger().error(e)\n up_data={}\n # raise e\n\n parameter = data['调用参数']\n downdata = data['下传参数']\n if header == '':\n header = {}\n else:\n try:\n header = eval(header)\n except Exception as e:\n Logger().error(e)\n header = {}\n if parameter=='':\n testdata = testdata\n else:\n try:\n parameter = eval(parameter)\n except Exception as e:\n Logger().error(e)\n parameter = ''\n else:\n for each in parameter:\n testdata[each] = up_data[each]\n respone = Request().requests(url, testdata, type,headers=header)\n respone=json.loads(respone)\n if check!='':\n try:\n check = eval(check)\n except Exception as e:\n Logger().error(e)\n check = {}\n for each in check.keys():\n try :\n assert respone[each]==check[each],\"接口【%s】响应校验失败\"%url\n except Exception as e:\n Logger().error(e)\n else:\n if downdata != '':\n try:\n downdata=eval(downdata)\n except Exception as e:\n downdata={}\n Logger.error(e)\n else:\n for key in downdata.keys():\n down_value = downdata[key].split(\"=>\")\n s=respone\n for i in range(0,len(down_value)):\n s=s[down_value[i]]\n i+=1\n downdata[key] = s\n up_data.update(downdata)\n result = [respone,up_data]\n return result\nif __name__==\"__main__\":\n a=OnlyInterface(**data11)\n print(a)\n\n\ndata2=\t{'接口1': {\n 'url': 'http://bkt.jeagine.com/api/user/signin',\n 'type': 'get',\n 'header': '',\n '参数': \"{'account': '13017600000', 'appKey': 'all', 'category_id': 80, 'password': '123456', 'terminal': 2}\",\n '继承参数': '',\n '调用参数': '',\n '下传参数': '{\"uid\":\"user=>id\"}',\n '校验': ''\n\t},\n\t'接口2': {\n\t'url': 'http://bkt.jeagine.com/api/user/mission/list',\n\t'type': 'get',\n\t'header': '',\n\t'参数': '{\"uid\": \"\"}',\n\t'继承参数': '',\n\t'调用参数': '[\"uid\"]',\n\t'下传参数': '',\n\t'校验': '{\"code\":redis_case}'\n}\n}\n\ndef InterfaceProcess(**data2):\n global up_data\n d_list=[]\n for each in data2.values():\n d_list.append(each)\n for i in range(0,len(d_list)):\n # print(\"======%s\"%i)\n if i==0:\n result=OnlyInterface(**d_list[i])\n up_data=result[1]\n else:\n url=d_list[i]['url']\n if url!=\"\":\n try:\n parameter=eval(d_list[i]['调用参数'])\n except Exception as e:\n Logger().error(e)\n parameter={}\n # data=eval(d_list[i]['参数'])\n up_data1=d_list[i]['继承参数']\n if up_data1 == '':\n up_data1 = up_data\n else:\n try:\n up_data1=eval(up_data1)\n except Exception as e:\n Logger().error(e)\n up_data1={}\n finally:\n up_data1.update(up_data)\n # for each in parameter:\n # data[each]=up_data1[each]\n # d_list[i]['参数']=str(data)\n d_list[i]['继承参数']=str(up_data1)\n up_data = str(up_data1)\n result = OnlyInterface(**d_list[i])\n # else\n i += 1\n return result\n# if __name__==\"__main__\":\n# a=InterfaceProcess(**data2)\n# print(a)\n\n","sub_path":"AITEST/common/Interface_process1.py","file_name":"Interface_process1.py","file_ext":"py","file_size_in_byte":5956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"269621247","text":"from contextlib import contextmanager, closing\nfrom ctypes import *\nfrom platform import system\nfrom ..shared_library import *\nfrom .enum import *\n\n\n@contextmanager\ndef cufft(libpath=None):\n \"\"\" get cufft shared library \"\"\"\n def _get_cufft(libpath=None):\n if libpath:\n return libpath\n else:\n libname = {\n \"Linux\": \"libcufft.so\",\n \"Windows\": find_windll(\"cufft.*\\.dll\"),\n \"Darwin\": \"libcufft.dylib\"\n }\n return libname[system()]\n ###\n with shared_library(_get_cufft()) as _lib:\n _lib.cufftPlan1d.argtypes = [c_void_p, c_int, c_int, c_int]\n _lib.cufftPlan2d.argtypes = [c_void_p, c_int, c_int, c_int]\n _lib.cufftPlan3d.argtypes = [c_void_p, c_int, c_int, c_int, c_int]\n _lib.cufftPlanMany.argtypes = [POINTER(c_int), c_int, POINTER(c_int), POINTER(c_int), c_int, c_int, POINTER(c_int), c_int, c_int, c_int, c_int]\n _lib.cufftMakePlan1d.argtypes = [c_int, c_int, c_int, c_int, c_void_p]\n _lib.cufftMakePlan2d.argtypes = [c_int, c_int, c_int, c_int, c_void_p]\n _lib.cufftMakePlan3d.argtypes = [c_int, c_int, c_int, c_int, c_int, c_void_p]\n _lib.cufftMakePlanMany.argtypes = [c_int, c_int, c_void_p, c_void_p, c_int, c_int, c_void_p, c_int, c_int, c_int, c_int, c_void_p]\n _lib.cufftMakePlanMany64.argtypes = [c_int, c_int, POINTER(c_longlong),\n POINTER(c_longlong), c_longlong, c_longlong,\n POINTER(c_longlong), c_longlong, c_longlong,\n c_int, c_longlong, POINTER(c_size_t)]\n _lib.cufftXtMakePlanMany.argtypes = [c_int, c_int, POINTER(c_longlong),\n POINTER(c_longlong), c_longlong, c_longlong, c_int,\n POINTER(c_longlong), c_longlong, c_longlong, c_int,\n c_longlong, POINTER(c_size_t), c_int]\n _lib.cufftGetSizeMany64.argtypes = _lib.cufftMakePlanMany64.argtypes\n _lib.cufftEstimate1d.argtypes = [c_int, c_int, c_int, c_void_p]\n _lib.cufftEstimate2d.argtypes = [c_int, c_int, c_int, c_void_p]\n _lib.cufftEstimate3d.argtypes = [c_int, c_int, c_int, c_int, c_void_p]\n _lib.cufftEstimateMany.argtypes = [c_int, c_void_p, c_void_p, c_int, c_int, c_void_p, c_int, c_int, c_int, c_int, c_void_p]\n _lib.cufftCreate.argtypes = [c_void_p]\n _lib.cufftGetSize1d.argtypes = _lib.cufftMakePlan1d.argtypes\n _lib.cufftGetSize2d.argtypes = _lib.cufftMakePlan2d.argtypes\n _lib.cufftGetSize3d.argtypes = _lib.cufftMakePlan3d.argtypes\n _lib.cufftGetSizeMany.argtypes = _lib.cufftMakePlanMany.argtypes\n _lib.cufftGetSize.argtypes = [c_void_p, c_void_p]\n _lib.cufftSetWorkArea.argtypes = [c_void_p, c_void_p]\n _lib.cufftSetAutoAllocation.argtypes = [c_void_p, c_int]\n _lib.cufftExecC2C.argtypes = [c_int, c_void_p, c_void_p, c_int]\n _lib.cufftExecR2C.argtypes = [c_int, c_void_p, c_void_p]\n _lib.cufftExecC2R.argtypes = [c_int, c_void_p, c_void_p]\n _lib.cufftExecZ2Z.argtypes = [c_int, c_void_p, c_void_p, c_int]\n _lib.cufftExecD2Z.argtypes = [c_int, c_void_p, c_void_p]\n _lib.cufftExecZ2D.argtypes = [c_int, c_void_p, c_void_p]\n _lib.cufftSetStream.argtypes = [c_void_p, c_int]\n _lib.cufftDestroy.argtypes = [c_int]\n _lib.cufftGetVersion.argtypes = [c_void_p]\n _lib.cufftGetProperty.argtypes = [c_int, c_void_p]\n yield _lib\n\n\ndef checkcufft(ret):\n if ret != CUFFT_SUCCESS:\n raise ValueError(ret)\n","sub_path":"cufft/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"557258689","text":"from flask import Flask, request, redirect, url_for, render_template, flash\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField\nfrom werkzeug.utils import secure_filename\nimport requests\n\nALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}\n\n\napp = Flask(__name__)\napp.secret_key = \"super secret key\"\napp.config['SESSION_TYPE'] = 'filesystem'\n\n# Form\nclass FileForm(FlaskForm):\n url = StringField('URL')\n\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef index():\n form = FileForm(csrf_enabled=False)\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n if form.url.data == '':\n return render_template('test.html', form=form, text='No selected data')\n else:\n r = requests.get(form.url.data)\n if r.status_code == 200:\n with open('temp.jpg', 'wb') as f:\n for chunk in r.iter_content(1024):\n f.write(chunk)\n return render_template('test.html', form=form, text='Изображение загружено!')\n file = request.files['file']\n # if user does not select file, browser also\n # submit a empty part without filename\n if file.filename == '':\n return render_template('test.html', form=form, text='No selected data')\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save('temp.jpg')\n return render_template('test.html', form=form, text='Изображение загружено!')\n return render_template('test.html', form=form)\n\n\napp.run(debug=True)","sub_path":"web_form.py","file_name":"web_form.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"331401088","text":"#coding: utf-8\nimport torch\nimport torch.nn as nn\nimport torch as t\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\n'''\n1.使用torchvision加载并预处理CIFAR-10数据集\n2.定义网络\n3.定义损失函数和优化器\n4.训练网络并更新网络参数\n5.测试网络\n'''\n\nclass Net(nn.Module):\n def __init__(self):\n # nn.Module子类的函数必须在构造函数中执行父类的构造函数\n # 下式等价于nn.Module.__init__(self)\n super(Net, self).__init__()\n\n # 卷积层 '1'表示输入图片为单通道, '6'表示输出通道数,'5'表示卷积核为5*5\n self.conv1 = nn.Conv2d(1, 6, 5)\n # 卷积层\n self.conv2 = nn.Conv2d(6, 16, 5)\n # 仿射层/全连接层,y = Wx + b\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n\n def forward(self, x):\n # 卷积 -> 激活 -> 池化\n x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))\n x = F.max_pool2d(F.relu(self.conv2(x)), 2)\n # reshape,‘-1’表示自适应\n x = x.view(x.size()[0], -1)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\nnet = Net()\nprint(net)\n\nparams = list(net.parameters())\nprint(len(params))\n\nfor name, parameters in net.named_parameters():\n print(name, ':', parameters.size())\nprint(\"=======================================================\\n\")\n\n# input = Variable(t.randn(1, 1, 32, 32))\n# out = net(input)\n# out.size()\n#\n#\n# net.zero_grad() #所有参数的梯度清零\n# out.backward(Variable(t.ones(1, 10)))#bp\n#\n# #loss function\n# output = net(input)\n# target = Variable(t.arange(0,10))\n# criterion = nn.MSELoss()\n# loss = criterion(output, target)\n# print(loss)\n#\n# print(\"=======================================================\\n\")\n#\n# net.zero_grad()\n# print('方向传播前conv1.bias的梯度')\n# print(net.conv1.bias.grad)\n# loss.backward()\n# print('方向传播后conv1.bias的梯度')\n# print(net.conv1.bias.grad)\n\n\nimport torch.optim as optim\n#新建一个优化器,指定要调整的参数和学习率\noptimizer = optim.SGD(net.parameters(), lr = 0.01)\n\n# 在训练过程中\n# 先梯度清零(与net.zero_grad()效果一样)\noptimizer.zero_grad()\n\n# 计算损失\noutput = net(input)\n#loss = criterion(output, target)\n\n#反向传播\nloss.backward()\n\n#更新参数\noptimizer.step()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ch02/nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"427337866","text":"\r\n# part -1 data preprocessing\r\n\r\n# importing libraries\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n# reading data set\r\ndata = pd.read_csv('Churn_Modelling.csv')\r\nX = data.iloc[:,3:13].values\r\ny = data.iloc[:,-1:].values\r\n\r\n\r\n# Encoding categorial data\r\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\r\nlabel_encoder1=LabelEncoder()\r\nlabel_encoder2=LabelEncoder()\r\nX[:,1]=label_encoder1.fit_transform(X[:,1])\r\nX[:,2]=label_encoder2.fit_transform(X[:,2])\r\nonehotencoder=OneHotEncoder(categorical_features=[1])\r\nX =onehotencoder.fit_transform(X).toarray()\r\nX =X[:,1:]\r\n\r\n# training and testing data splittting\r\nfrom sklearn.model_selection import train_test_split\r\ntrain_X, test_X, train_Y, test_Y =train_test_split(X ,y ,test_size=0.20 ,random_state=0)\r\n\r\n# feature scaling\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc_x = StandardScaler()\r\ntrain_X = sc_x.fit_transform(train_X)\r\ntest_X = sc_x.transform(test_X)\r\n\r\n\r\n# part -2 Now make an ANN network\r\n\r\n#import keras libraries and packages\r\n\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense \r\n\r\n#initialising ANN\r\nclassifier=Sequential()\r\n\r\n# adding input layer that is input layer #unit means output nodes and input sim is input nodes\r\nclassifier.add(Dense(units=6, activation='relu',input_dim=11 ))\r\n#adding secoung hidden layer\r\nclassifier.add(Dense(units=6, activation='relu' ))\r\n#adding output result\r\nclassifier.add(Dense(units=1,activation='sigmoid'))\r\n\r\n#compiling ANN\r\nclassifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\r\n\r\n\r\n#fitting ANN to training set\r\nclassifier.fit(train_X,train_Y, epochs=40, batch_size=30)\r\n\r\n# part -3 making prediction and result\r\n\r\n#predictions of result\r\ny_pred =classifier.predict(test_X)\r\ny_pred=(y_pred>0.5)\r\n\r\n#confusion matrix\r\nfrom sklearn.metrics import confusion_matrix,accuracy_score\r\ncm =confusion_matrix(test_Y ,y_pred)\r\naccuracy_score(test_Y,y_pred)*100","sub_path":"ann_self.py","file_name":"ann_self.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"58389862","text":"from math import pi, cos, sin, acos, atan2, sqrt\nimport matplotlib.pyplot as plt\n\nclass outlierClass:\n\tdef __init__(self, freq, vel, fileName):\n\t\tdt = freq;\t\t# Hz\n\t\tvelocity = vel;\t# m/s\n\t\tx = [];\n\t\ty = [];\n\t\tz = [];\n\t\themi = [];\n\t\tzone = [];\n\t\tlett = [];\n\t\txCorr = [];\n\t\tyCorr = [];\n\t\t\n\t\tfData = open(fileName, 'r');\n\t\tfor line in fData :\n\t\t\tcsv = line.split(',');\n\t\t\tx.append(float(csv[0]));\n\t\t\ty.append(float(csv[1]));\n\t\t\tz.append(float(csv[2]));\n\t\t\themi.append(csv[3]);\n\t\t\tzone.append(int(csv[4]));\n\t\t\tlett.append(csv[5]);\n\t\tfData.close;\n\n\t\tfCorr = open(fileName.replace(\".csv\", \"\")+\"_corrected.csv\", 'w',newline='');\n\n\t\tcOld = sqrt(x[0]**2+y[0]**2);\n\t\tfor i in range(0,len(x)):\n\t\t\tcNew = sqrt(x[i]**2 + y[i]**2);\n\t\t\tif( (cNew - cOld) < velocity*dt ):\n\t\t\t\tfCorr.write(str(x[i]));\n\t\t\t\tfCorr.write(',');\n\t\t\t\tfCorr.write(str(y[i]));\n\t\t\t\tfCorr.write(',');\n\t\t\t\tfCorr.write(str(z[i]));\n\t\t\t\tfCorr.write(',');\n\t\t\t\tfCorr.write(str(hemi[i]));\n\t\t\t\tfCorr.write(',');\n\t\t\t\tfCorr.write(str(zone[i]));\n\t\t\t\tfCorr.write(',');\n\t\t\t\tfCorr.write(lett[i]);\n\t\t\t\t#fCorr.write('\\n');\t\t#Line break is needed if last write is not a letter.\n\t\t\t\txCorr.append(x[i]);\n\t\t\t\tyCorr.append(y[i]);\n\t\t\tcOld = cNew;\n\t\tfCorr.close();\n\n\t\tfig, axs = plt.subplots(nrows=2)\n\t\tfig.suptitle(\"Graph for UTM data before and after removing outliers\");\n\t\taxs[0].scatter(x, y);\n\t\taxs[0].set_title(\"Uncorrected UTM data\");\n\t\taxs[0].axis('equal')\n\t\taxs[0].set_xlabel('N');\n\t\taxs[0].set_ylabel('E');\n\t\taxs[1].scatter(xCorr, yCorr);\n\t\taxs[1].set_title(\"Corrected UTM data\");\n\t\taxs[1].axis('equal');\n\t\taxs[1].set_xlabel('N');\n\t\taxs[1].set_ylabel('E');\n\t\tplt.show()\n\n","sub_path":"UTMHandling/correct/outlierClass.py","file_name":"outlierClass.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"596819129","text":"\"\"\"\n给定一个字符串数组,将字母异位词组合在一起。\n\"\"\"\nfrom collections import defaultdict\n\ndef groupAnagrams(strs):\n dic = defaultdict(list)\n for st in strs:\n count = [0] * 26\n for ch in st:\n count[ord(ch) - ord('a')] += 1\n # 将list类型转为tuple进行哈希\n dic[tuple(count)].append(st)\n return list(dic.values())\n\n\nif __name__ == \"__main__\":\n strs = [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]\n print(groupAnagrams(strs))","sub_path":"String/groupAnagrams.py","file_name":"groupAnagrams.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"244017134","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author:Data Scientist\r\nif you have any question My Email is:\r\ngheffari.abdelfattah@gmail.com \r\n\r\n\"\"\"\r\n\r\nfrom keras.preprocessing import sequence\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense ,Dropout , Embedding , SimpleRNN, Bidirectional,SpatialDropout1D\r\nimport codecs\r\nfrom sklearn.datasets import load_files\r\nfrom sklearn.model_selection import train_test_split\r\nfrom keras.preprocessing.text import Tokenizer\r\nimport re \r\nfrom keras.callbacks import TensorBoard\r\nfrom keras.callbacks import EarlyStopping\r\nimport matplotlib.pyplot as plt \r\nimport pretraitement as pt\r\nimport report_metrics as report \r\n\r\n#Path=r\"Path of DataSet\"\r\n#Load the DataSet\r\nMyDataSet=load_files(Path,decode_error='ignore' ,shuffle=True,encoding='utf-8')\r\nmydata=MyDataSet.data\r\nstop_words=pt.get_stop_words() \r\ndata_clean=[]\r\n#Cleaning the Data\r\nfor tweet in mydata:\r\n tweet=pt.pretraitement(tweet)\r\n tweet_split= tweet.split()\r\n tweet=[] \r\n for word in tweet_split:\r\n word=word.replace(u'\\ufeff', '')\r\n tweet.append(word)\r\n data_clean.append(tweet)\r\n \r\nfor i in range (len(data_clean)):\r\n MyDataSet.data[i]=data_clean[i]\r\n MyDataSet.data[i]=' '.join(MyDataSet.data[i]) \r\n\r\n\r\n#Hyper-Parameters\r\nmax_features =5000\r\nnum_classes=1\r\nmax_length=100\r\nbatch_size=64\r\nembidding_dim=16 #choose number multiple of 2 like The machine (2^N)32 or 64 or 128 .....\r\ndropout_rate=0.5 #Dropout_Layer\r\nhidden_layer_size=256\r\nnum_epochs=50\r\n\r\n\r\n#Tokenization\r\ntok = Tokenizer(num_words=max_features )\r\ntok.fit_on_texts(MyDataSet.data)\r\n\r\n#make Sequence for each text\r\nsequences = tok.texts_to_sequences(MyDataSet.data)\r\nsequences_matrix = sequence.pad_sequences(sequences,maxlen=max_length)\r\n\r\n#number of words \r\nvocab_size=len(tok.index_word)+1\r\n\r\n\r\n#Design Neural Network Architecture with SimpleRNN \r\n\r\nSimpleRNN_model = Sequential()\r\n\r\nSimpleRNN_model.add(Embedding(vocab_size, embidding_dim,input_length =max_length))\r\n\r\nSimpleRNN_model.add(Dropout(dropout_rate))\r\n\r\nSimpleRNN_model.add(SimpleRNN(32))\r\n\r\nSimpleRNN_model.add(Dropout(dropout_rate))\r\n\r\nSimpleRNN_model.add(Dense(num_classes,activation='sigmoid'))\r\n\r\nSimpleRNN_model.compile(loss = 'binary_crossentropy', optimizer='adam',metrics=['accuracy',report.f1_m,report.recall_m,report.precision_m])\r\n\r\nprint(SimpleRNN_model.summary())\r\n\r\n#Train Test\r\nX_train, X_test,target_train,target_test=train_test_split(sequences_matrix,MyDataSet.target,test_size=0.2)\r\n\r\n#Train Validation\r\nX_train,X_val, target_train ,target_val=train_test_split(X_train,target_train,test_size=0.2)\r\n\r\n#EarlyStopping Regularization\r\nes= EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=3,min_delta=0.0001)\r\n\r\n#history\r\nhistory=SimpleRNN_model.fit(X_train, target_train, epochs =1, batch_size=batch_size,validation_data=(X_val,target_val),callbacks=[es])\r\n\r\n\r\nloss, acc ,F1,recall,precision = SimpleRNN_model.evaluate(X_test, target_test, batch_size=batch_size)\r\n\r\n\r\n\r\n \r\nprint('Test accuracy:', acc) \r\nprint('Test score:', loss)\r\nprint('Test F1:', F1)\r\nprint('Test recall:', recall)\r\nprint('Test precision:', precision)\r\n\r\n#\"Accuracy\"\r\nplt.plot(history.history['accuracy'])\r\nplt.plot(history.history['val_accuracy'])\r\nplt.title('model accuracy')\r\nplt.ylabel('accuracy')\r\nplt.xlabel('epoch')\r\nplt.legend(['train', 'validation'], loc='upper left')\r\nplt.show()\r\n\r\n#\"Loss\"\r\nplt.plot(history.history['loss'])\r\nplt.plot(history.history['val_loss'])\r\nplt.title('model loss')\r\nplt.ylabel('loss')\r\nplt.xlabel('epoch')\r\nplt.legend(['train', 'validation'], loc='upper left')\r\nplt.show()\r\n\r\n#We Can ploting F1 & recall & precision","sub_path":"Sentiment analysis using SimpleRNN.py","file_name":"Sentiment analysis using SimpleRNN.py","file_ext":"py","file_size_in_byte":3636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"474465219","text":"#!/usr/bin/env python3.7\nimport sys\nsys.path.append(\"../../Bibliotecas/\") \nimport ClasseDados as cla\nfrom matplotlib import pyplot as plt\n\n#######################################################################\n## Item A ##\n#######################################################################\nprint(\"+++++++++ Item A +++++++++\")\nread1 = cla.OsciloscopioCSV(\"../raw_files/scope_14.csv\")\nread1.GetNChannels()\n\n# Le os dados salvos no csv\ntime_1 = read1.GetVoltageArray(0)\nv1_1 = read1.GetVoltageArray(1)\nv2_1= read1.GetVoltageArray(2)\n\n# Plota e printa os graficos\nplt.figure(0)\nplt.plot(time_1,v1_1,label=\"Canal 1\")\nplt.plot(time_1,v2_1,label=\"Canal 2\")\nplt.grid()\nplt.legend()\nplt.xlabel('tempo [s]')\nplt.ylabel('tensão [V]') \n\nplt.savefig(\"../Imagens/Ex1itemA.png\")\n\n\n#######################################################################\n## Item B ##\n#######################################################################\nprint(\"+++++++++ Item B +++++++++\")\nread2 = cla.OsciloscopioCSV(\"../raw_files/scope_16.csv\")\nread2.GetNChannels()\n\n# Le os dados salvos no csv\ntime_2 = read2.GetVoltageArray(0)\nv1_2 = read2.GetVoltageArray(1)\nv2_2= read2.GetVoltageArray(2)\n\n# Plota e printa os graficos\nplt.figure(1)\nplt.plot(time_2,v1_2,label=\"Canal 1\")\nplt.plot(time_2,v2_2,label=\"Canal 2\")\nplt.grid()\nplt.legend()\nplt.xlabel('tempo [s]')\nplt.ylabel('tensão [V]') \n\nplt.savefig(\"../Imagens/Ex1itemB.png\")\n\n\n#######################################################################\n## Item C ##\n#######################################################################\nprint(\"+++++++++ Item C +++++++++\")\nread3 = cla.OsciloscopioCSV(\"../raw_files/scope_18.csv\")\nread3.GetNChannels()\n\n# Le os dados salvos no csv\ntime_3 = read3.GetVoltageArray(0)\nv1_3 = read3.GetVoltageArray(1)\nv2_3= read3.GetVoltageArray(2)\n\n# Plota e printa os graficos\nplt.figure(2)\nplt.plot(time_3,v1_3,label=\"Canal 1\")\nplt.plot(time_3,v2_3,label=\"Canal 2\")\nplt.grid()\nplt.legend()\nplt.xlabel('tempo [s]')\nplt.ylabel('tensão [V]') \n\nplt.savefig(\"../Imagens/Ex1itemC.png\")\n\n\n#######################################################################\n## comparison ##\n#######################################################################\nplt.figure(3)\n\nplt.plot(time_1,v1_1,label=\"Tensão da fonte\")\nplt.plot(time_1,v2_1,label=\"Sinal retificado\")\n\nplt.plot(time_2,v2_2,label=\"Sinal retificado, com capacitor\")\n\nplt.plot(time_3,v2_3,label=\"Sinal retificado, com capacitor e resitor\")\n\nplt.grid()\nplt.legend()\nplt.xlabel('tempo [s]')\nplt.ylabel('tensão [V]') \nplt.savefig(\"../Imagens/Ex1COMPARE.png\")\n\nplt.show() \t","sub_path":"DE_Experimento3/code/Exercicio1.py","file_name":"Exercicio1.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"243894342","text":"\nimport os\nimport sys\nimport random\nimport math\nimport numpy as np\nimport scipy.misc\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport argparse\n\n\n\nimport coco\nimport utils\nimport model as modellib\nimport visualize\nfrom tensorflow.python.ops.metrics_impl import sensitivity_at_specificity\n\n\nclass InferenceConfig(coco.CocoConfig):\n # Set batch size to 1 since we'll be running inference on\n # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n\n\nclass readable_dir(argparse.Action):\n def __call__(self, parser, namespace, values, option_string=None):\n prospective_dir=values\n if not os.path.isdir(prospective_dir):\n raise argparse.ArgumentTypeError(\"readable_dir:{0} is not a valid path\".format(prospective_dir))\n if os.access(prospective_dir, os.R_OK):\n setattr(namespace,self.dest,prospective_dir)\n else:\n raise argparse.ArgumentTypeError(\"readable_dir:{0} is not a readable dir\".format(prospective_dir))\n\nclass readable_file(argparse.Action):\n def __call__(self, parser, namespace, values, option_string=None):\n prospective_file=values\n if not os.path.isfile(prospective_file):\n raise argparse.ArgumentTypeError(\"readable_file:{0} is not a valid path\".format(prospective_file))\n if os.access(prospective_file, os.R_OK):\n setattr(namespace,self.dest,prospective_file)\n else:\n raise argparse.ArgumentTypeError(\"readable_file:{0} is not a readable dir\".format(prospective_file))\n\n \nclass defaultDirectory(object):\n \n def __init__(self,inputDir, outputDir):\n self.inputDir= inputDir\n self.outputDir= outputDir\n \n \n def get_outputDir(self):\n return self.outputDir\n \n def get_inputDir(self):\n return self.inputDir\n\n\ndef main(): \n \n parser = argparse.ArgumentParser(description='tool for processing a folder of image with MaskRCNN')\n parser.add_argument('-i', '--inputDir', action=readable_dir, help='input directory to process')\n parser.add_argument('-o', '--outputDir', action=readable_dir, help='output directory to process')\n parser.add_argument('-l', '--inputFileList', action=readable_file, help='input file with a list of images')\n \n args = parser.parse_args()\n dirs= defaultDirectory(args.inputDir, args.outputDir)\n IMAGETest_DIR =dirs.get_inputDir()\n IMAGETestResult_DIR=dirs.get_outputDir()\n \n fileOfInputImages=\"\"\n if args.inputFileList != None:\n fileOfInputImages=args.inputFileList\n \n # Root directory of the project\n ROOT_DIR = os.getcwd() \n\n # Directory to save logs and trained model\n MODEL_DIR = os.path.join(ROOT_DIR, \"logs\")\n \n # Path to trained weights file\n # Download this file and place in the root of your \n # project (See README file for details)\n COCO_MODEL_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\n \n # Directory of images to run detection on\n IMAGE_DIR = os.path.join(ROOT_DIR, \"imagetest\")\n \n \n \n \n \n \n \n \n \n \n \n \n config = InferenceConfig()\n config.print()\n # Create model object in inference mode.\n model = modellib.MaskRCNN(mode=\"inference\", model_dir=MODEL_DIR, config=config)\n \n # Load weights trained on MS-COCO\n model.load_weights(COCO_MODEL_PATH, by_name=True)\n \n # COCO Class names\n # Index of the class in the list is its ID. For example, to get ID of\n # class, use: class_names.index('teddy bear')\n class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',\n 'bus', 'train', 'truck', 'boat', 'traffic light',\n 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',\n 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',\n 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',\n 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',\n 'kite', 'baseball bat', 'baseball glove', 'skateboard',\n 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',\n 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',\n 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',\n 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',\n 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',\n 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',\n 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',\n 'teddy bear', 'hair drier', 'toothbrush']\n \n \n \n \n if fileOfInputImages!=\"\":\n with open(fileOfInputImages) as file:\n for index, line in enumerate(file):\n ImagePath = line.strip() \n \n baseDir, file_name = os.path.split(ImagePath)\n \n #debug test 10\n #if index == 10: \n # break\n \n if os.path.isfile(ImagePath):\n #print(ImagePath)\n image = scipy.misc.imread(ImagePath)\n \n # Run detection\n results = model.detect([image], verbose=1)\n # Visualize results\n r = results[0]\n print(\"Counter\",index )\n \n saveImageDir=os.path.join(IMAGETestResult_DIR, file_name)\n \n saveJSONDir=os.path.join(IMAGETestResult_DIR,file_name.replace('.png','.json'))\n visualize.save_instances(saveImageDir ,saveJSONDir ,file_name, image, r['rois'], r['masks'], r['class_ids'],class_names, r['scores'])\n \n else:\n print(\"Error finding\", ImagePath)\n \n else:\n print(\"Error\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ImageParser.py","file_name":"ImageParser.py","file_ext":"py","file_size_in_byte":6025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"396717929","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom pathlib import Path\n\nimport cv2\nimport torch\n\n__author__ = \"Christian Heider Nielsen\"\n__doc__ = \"\"\n\nfrom draugr.torch_utilities.images.conversion import quick_to_pil_image\n\nfrom data.segmentation import PennFudanDataset\n\nfrom tqdm import tqdm\n\nfrom draugr.opencv_utilities import frame_generator, draw_bounding_boxes\nfrom draugr.torch_utilities import (\n global_torch_device,\n torch_seed,\n TorchEvalSession,\n to_tensor_generator,\n hwc_to_chw_tensor,\n uint_hwc_to_chw_float_tensor\n )\nfrom draugr.torch_utilities import Split, load_model\n\nfrom neodroidvision import PROJECT_APP_PATH\nfrom neodroidvision.detection.two_stage.mask_rcnn.architecture import (\n get_pretrained_instance_segmentation_maskrcnn,\n )\n\nif __name__ == \"__main__\":\n\n def main(model_name: str = \"maskrcnn_pennfudanped\", score_threshold=0.55):\n base_path = PROJECT_APP_PATH.user_data / 'maskrcnn'\n dataset_root = Path.home() / \"Data\"\n\n torch_seed(3825)\n\n dataset = PennFudanDataset(dataset_root / \"PennFudanPed\", Split.Training)\n categories = dataset.categories\n\n if True:\n model = load_model(model_name=model_name, model_directory=base_path / 'models')\n else:\n model = get_pretrained_instance_segmentation_maskrcnn(dataset.response_channels)\n\n model.to(global_torch_device())\n cpu_device = torch.device(\"cpu\")\n\n with torch.no_grad():\n with TorchEvalSession(model):\n for image in tqdm(\n to_tensor_generator(\n frame_generator(cv2.VideoCapture(0)),\n device=global_torch_device(),\n )\n ):\n prediction = model(\n # torch_vision_normalize_batch_nchw(\n uint_hwc_to_chw_float_tensor(image).unsqueeze(0)\n # )\n )[0]\n\n (boxes, labels, scores) = (\n prediction[\"boxes\"].to(cpu_device).numpy(),\n prediction[\"labels\"].to(cpu_device).numpy(),\n torch.sigmoid(prediction[\"scores\"]).to(cpu_device).numpy(),\n )\n\n indices = scores > score_threshold\n\n cv2.namedWindow(model_name, cv2.WINDOW_NORMAL)\n cv2.imshow(\n model_name,\n draw_bounding_boxes(\n quick_to_pil_image(image),\n boxes[indices],\n labels=labels[indices],\n scores=scores[indices],\n categories=categories,\n )\n )\n\n if cv2.waitKey(1) == 27:\n break # esc to quit\n\n\n main()\n","sub_path":"samples/detection/two_stage/person_detection/maskrcnn_webcam_demo.py","file_name":"maskrcnn_webcam_demo.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"137455707","text":"import json\nimport csv\nfrom os import write\n\nwith open('covid_cases.json', 'r') as json_file:\n num_json = json.load(json_file)\n\ndata_covid = num_json['records']\n\ncovid_cases = open('covid_cases.csv', 'w')\n\nwrite_csv = csv.writer(covid_cases)\n\ncount = 0\nfor i in data_covid:\n if count == 0:\n header = i.keys()\n write_csv.writerow(header)\n\n write_csv.writerow(i.values())\n\ncovid_cases.close\n\n\n","sub_path":"covid_casesparsejon.py","file_name":"covid_casesparsejon.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"4036236","text":"\nnumbers = [1,2,3,4,5]\n\n# random indexing --> O(1) get items if we know the index !!\n# print(numbers[0])\n\n# for loop\n# for num in numbers:\n# print(num)\n\n# for sequence\n# for i in range(len(numbers)):\n# print(numbers[i])\n\n# [start index : end index]\nprint(numbers[0:2])\n\n# [:] all fo the items\nprint(numbers[:])\n\n# O(N) search running time\nmaximum = numbers[0]\nfor num in numbers:\n if num > maximum:\n maximum = num\n \nprint(maximum)\n\n","sub_path":"Arrays/arrays.py","file_name":"arrays.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"395487613","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n# Generated file, DO NOT EDIT\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass ServiceEndpointExecutionRecord(Model):\n \"\"\"ServiceEndpointExecutionRecord.\n\n :param data:\n :type data: :class:`ServiceEndpointExecutionData `\n :param endpoint_id:\n :type endpoint_id: str\n \"\"\"\n\n _attribute_map = {\n 'data': {'key': 'data', 'type': 'ServiceEndpointExecutionData'},\n 'endpoint_id': {'key': 'endpointId', 'type': 'str'}\n }\n\n def __init__(self, data=None, endpoint_id=None):\n super(ServiceEndpointExecutionRecord, self).__init__()\n self.data = data\n self.endpoint_id = endpoint_id\n","sub_path":"vsts/vsts/task_agent/v4_0/models/service_endpoint_execution_record.py","file_name":"service_endpoint_execution_record.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"587542876","text":"#二分法 +降维\nclass Solution:\n # 2019/8/30\n \"\"\"\n @param matrix: matrix, a list of lists of integers\n @param target: An integer\n @return: a boolean, indicate whether matrix contains target\n \"\"\"\n def searchMatrix(matrix, target):\n if not matrix:\n return False\n m,n = len(matrix),len(matrix[0])##行 列\n start, end = 0,m*n-1\n\n while start +1 < end:\n mid = start +(end-start)//2\n print(\"mid: \",mid)\n x,y = mid//n,mid%n\n print(\"x_y: \",x,y)\n if matrix[x][y] == target:\n return True\n elif matrix[x][y] > target:\n end = mid\n else:\n start = mid\n return True if matrix[start//n][start%n] == target or matrix[end//n][end%n] == target else False\n\n if __name__ == \"__main__\":\n\n target = 10\n array =[\n [1, 3, 5, 7],\n [10, 11, 16, 20],\n [23, 30, 34, 50]\n]\n print(searchMatrix(array, target))\n\n\n\n","sub_path":"lintcode/第一层/28_搜索二维矩阵.py","file_name":"28_搜索二维矩阵.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"335753603","text":"'''\nQuestion link: https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/\n\n\nGiven an integer number n, return the difference between the product of its digits and the sum of its digits.\n \n'''\n\n\nclass Solution:\n def subtractProductAndSum(self, n: int) -> int:\n add=0\n multiply=1\n \n while n!=0:\n temp=n%10\n multiply*=temp\n add+=temp\n n=n//10\n return multiply-add\n","sub_path":"Leetcode/diffProductAndSum.py","file_name":"diffProductAndSum.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"305774446","text":"import redis\nimport json\nimport time\nimport numpy as np\nimport requests\nfrom copy import deepcopy\nimport matplotlib.pyplot as plt\nimport gc\nimport os\n\naddr = 'localhost'\nport = 6379\ndb = 1\nkey = 'APTPath'\nkeyFlow = 'APTFlow'\ncommand = 'test $(/home/miguel/presto/script_enlaces.awk /home/miguel/presto/ONOSenlaces.txt | tail -n1) -eq 8'\n\n\ndef beep(duration, freq):\n os.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))\n\n\ndef loadP4DBFlow():\n flow = {\"origin\": \"00:00:00:00:00:01/None\", \"destiny\": \"00:00:00:00:00:39/None\"}\n client = redis.Redis(addr, port, db)\n client.set(keyFlow, json.dumps(flow))\n\n\ndef loadP4DB():\n client = redis.Redis(addr, port, db)\n client.flushdb()\n\n for i in range(100):\n path = {}\n for j in [1, 2, 4096, 4097]:\n path[\"device:bmv2:%d\" % j] = {\n \"LT_pkts\": 114,\n \"in_queue\": 15,\n \"eg_queue\": 60,\n \"Timedelta\": 117,\n \"LT_entries\": 2\n }\n client.rpush(key, path)\n\n\ndef plot(p4DBdata, dpid):\n a = str(int(time.time()))\n\n plt.style.use('dark_background')\n\n fig1 = plt.figure()\n plt.plot(range(len(p4DBdata[\"device:bmv2:1\"][\"LT_entries\"])),\n p4DBdata[\"device:bmv2:1\"][\"LT_entries\"], 'r-',\n label='LT en bmv2:1', linewidth=0.5)\n plt.plot(range(len(p4DBdata[\"device:bmv2:2\"][\"LT_entries\"])),\n p4DBdata[\"device:bmv2:2\"][\"LT_entries\"], 'g-',\n label='LT en bmv2:2', linewidth=0.5)\n plt.plot(range(len(p4DBdata[dpid][\"LT_entries\"])),\n p4DBdata[dpid][\"LT_entries\"], 'm-',\n label='LT en '+dpid[7:], linewidth=0.5)\n plt.title(\"Tamaño LT\")\n plt.xlabel(\"Nº de notificación\")\n plt.ylabel(\"# entradas LT\")\n plt.legend(loc=\"best\", fontsize='small')\n plt.grid(True)\n # plt.show()\n fig1.savefig('/home/miguel/presto/' + a + 'LT.png', dpi=200)\n fig1.clear()\n plt.close(fig1)\n\n fig1 = plt.figure()\n plt.plot(range(len(p4DBdata[\"device:bmv2:1\"][\"LT_entries\"][700:1500])),\n p4DBdata[\"device:bmv2:1\"][\"LT_entries\"][700:1500], 'r+',\n label='LT en bmv2:1', linewidth=0.5)\n plt.plot(range(len(p4DBdata[\"device:bmv2:2\"][\"LT_entries\"][700:1500])),\n p4DBdata[\"device:bmv2:2\"][\"LT_entries\"][700:1500], 'g+',\n label='LT en bmv2:2', linewidth=0.5)\n plt.plot(range(len(p4DBdata[dpid][\"LT_entries\"][700:1500])),\n p4DBdata[dpid][\"LT_entries\"][700:1500], 'm+',\n label='LT en '+dpid[7:], linewidth=0.5)\n plt.title(\"Tamaño LT\")\n plt.xlabel(\"Nº de notificación\")\n plt.ylabel(\"# entradas LT\")\n plt.legend(loc=\"best\", fontsize='small')\n plt.grid(True)\n # plt.show()\n fig1.savefig('/home/miguel/presto/' + a + 'LTexp.png', dpi=200)\n fig1.clear()\n plt.close(fig1)\n\n '''fig1 = plt.figure()\n plt.plot(range(len(p4DBdata[\"device:bmv2:1\"][\"LT_pkts\"])),\n p4DBdata[\"device:bmv2:1\"][\"LT_pkts\"], 'r-',\n label='Tramas encaminadas en bmv2:1', linewidth=0.5)\n plt.plot(range(len(p4DBdata[\"device:bmv2:2\"][\"LT_pkts\"])),\n p4DBdata[\"device:bmv2:2\"][\"LT_pkts\"], 'g-',\n label='Tramas encaminadas en bmv2:2', linewidth=0.5)\n plt.title(\"Tramas encaminadas por ARP-Path\")\n plt.xlabel(\"Nº de notificación\")\n plt.ylabel(\"# tramas\")\n plt.legend(loc=\"best\", fontsize='small')\n plt.grid(True)\n # plt.show()\n fig1.savefig('/home/miguel/presto/' + a + 'tramas.png', dpi=250)\n fig1.clear()\n plt.close(fig1)'''\n\n '''fig1 = plt.figure()\n plt.plot(range(len(p4DBdata[\"device:bmv2:1\"][\"Timedelta\"])),\n p4DBdata[\"device:bmv2:1\"][\"Timedelta\"], 'r-',\n label='Latencia (us) en bmv2:1', linewidth=0.5)\n plt.plot(range(len(p4DBdata[\"device:bmv2:2\"][\"Timedelta\"])),\n p4DBdata[\"device:bmv2:2\"][\"Timedelta\"], 'g-',\n label='Latencia (us) en bmv2:2', linewidth=0.5)\n plt.title(\"Latencia de procesado\")\n plt.xlabel(\"Nº de notificación\")\n plt.ylabel(\"Tiempo (us)\")\n plt.legend(loc=\"best\", fontsize='small')\n plt.grid(True)\n # plt.show()\n fig1.savefig('/home/miguel/presto/' + a + 'latencias.png', dpi=250)\n fig1.clear()\n plt.close(fig1)'''\n\n gc.collect()\n\n\ndef main():\n client = redis.Redis(addr, port, db)\n\n template = {\n \"in_queue\": [],\n \"eg_queue\": [],\n \"LT_entries\": [],\n \"LT_pkts\": [],\n \"Timedelta\": []\n }\n p4DBdata = {\n \"device:bmv2:1\": deepcopy(template),\n \"device:bmv2:2\": deepcopy(template),\n \"device:bmv2:4096\": deepcopy(template),\n \"device:bmv2:4097\": deepcopy(template)\n }\n\n for i in client.lrange(key, 1, -1):\n data = str(i)[2:-1].replace(\"'\", '\"')\n data = json.loads(data)\n for j in [\"device:bmv2:1\", \"device:bmv2:2\", \"device:bmv2:4096\", \"device:bmv2:4097\"]:\n try:\n p4DBdata[j][\"in_queue\"].append(data[j][\"in_queue\"])\n p4DBdata[j][\"eg_queue\"].append(data[j][\"eg_queue\"])\n p4DBdata[j][\"LT_entries\"].append(data[j][\"LT_entries\"])\n p4DBdata[j][\"LT_pkts\"].append(data[j][\"LT_pkts\"])\n p4DBdata[j][\"Timedelta\"].append(data[j][\"Timedelta\"])\n except KeyError:\n pass\n\n client.delete(key)\n\n # Calcular media\n # TODO: devest\n line = ''\n blockedq = {}\n blockedt = {}\n for i in [\"device:bmv2:1\", \"device:bmv2:2\", \"device:bmv2:4096\", \"device:bmv2:4097\"]:\n try:\n nb_elem = len(p4DBdata[i][[*p4DBdata[i]][0]])\n if nb_elem:\n a = np.asarray(p4DBdata[i][\"eg_queue\"][int(nb_elem * 0.44):])\n #blockedq[i] = ((a > 70).sum() / nb_elem) * 100\n blockedq[i] = np.mean(a)\n a = np.asarray(p4DBdata[i][\"Timedelta\"][int(nb_elem * 0.44):])\n blockedt[i] = ((a > 50).sum() / nb_elem) * 100\n line += (str(np.mean(p4DBdata[i][\"in_queue\"][int(nb_elem * 0.44):])) + ' ')\n line += (str(np.mean(p4DBdata[i][\"eg_queue\"][int(nb_elem * 0.44):])) + ' ')\n line += (str(np.mean(p4DBdata[i][\"LT_entries\"][int(nb_elem * 0.44):])) + ' ')\n line += (str(np.mean(p4DBdata[i][\"Timedelta\"][int(nb_elem * 0.44):])) + ' ')\n line += (str(p4DBdata[i][\"LT_pkts\"][-1]) + ' ')\n time.sleep(1)\n except:\n pass\n line += '\\n'\n\n with open('/home/miguel/presto/P4DB.txt', 'a+') as fd:\n fd.write(line)\n\n if os.system(command):\n beep(1, 200)\n return\n\n if len(p4DBdata[\"device:bmv2:4096\"][\"LT_entries\"]):\n dpid = \"device:bmv2:4096\"\n else:\n dpid = \"device:bmv2:4097\"\n\n nb_elem = len(p4DBdata[dpid][[*p4DBdata[dpid]][0]])\n print(nb_elem)\n if not nb_elem:\n return\n\n field1 = str(blockedt[\"device:bmv2:1\"])\n field2 = str(blockedt[\"device:bmv2:2\"])\n field3 = str(blockedq[\"device:bmv2:1\"])\n field4 = str(blockedq[\"device:bmv2:2\"])\n if nb_elem:\n field5 = str(np.mean(p4DBdata[dpid][\"LT_entries\"][int(nb_elem * 0.44):]))\n else:\n field5 = '0'\n\n if p4DBdata[\"device:bmv2:1\"][\"LT_pkts\"][-1] != 0:\n field6 = str(100 * (p4DBdata[\"device:bmv2:1\"][\"LT_pkts\"][-1] - p4DBdata[\"device:bmv2:2\"][\"LT_pkts\"][-1])\n / p4DBdata[\"device:bmv2:1\"][\"LT_pkts\"][-1])\n else:\n field6 = '0'\n\n field7 = str(max(\n p4DBdata[\"device:bmv2:1\"][\"Timedelta\"][int(nb_elem * 0.44):] + p4DBdata[\"device:bmv2:2\"][\"Timedelta\"][\n int(nb_elem * 0.44):]) / 1000)\n field8 = str(max(p4DBdata[dpid][\"Timedelta\"][int(nb_elem * 0.44):]) / 1000)\n\n requests.get('https://api.thingspeak.com/update?api_key=A44KQ62IIRNTD08Q'\n + '&field1=' + field1\n + '&field2=' + field2\n + '&field3=' + field3\n + '&field4=' + field4\n + '&field5=' + field5\n + '&field6=' + field6\n + '&field7=' + field7\n + '&field8=' + field8)\n\n plot(p4DBdata, dpid)\n beep(1, 2500)\n\n\nif __name__ == '__main__':\n print('Starting P4DB dumper')\n # loadP4DBFlow()\n # loadP4DB()\n main()\n","sub_path":"P4DBdumper.py","file_name":"P4DBdumper.py","file_ext":"py","file_size_in_byte":8247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"555412550","text":"string = 'pop this tacocat seems nice at noon'\n\npalindromes = {}\npal = dict()\n\nfor i in range(len(string)):\n\tfor j in range(i+2, len(string)+1):\n\t\tsubstr = string[i:j]\n\t\tprint(substr)\n\t\tmid = int(len(substr)/2)\n\t\tif len(substr)%2 == 0:\n\t\t\tif substr[:mid] == substr[mid:][::-1]:\n\t\t\t\tpal[i,j] = substr\n\t\telse:\n\t\t\tif substr[:mid] == substr[mid+1:][::-1]:\n\t\t\t\tpal[i,j] = substr\n\nprint(pal)\n","sub_path":"palindromes.py","file_name":"palindromes.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"76741547","text":"import json\nimport csv\n\ninput = 'results.json'\noutput = 'results.csv'\nnoname = 'None Removed'\nif __name__=='__main__':\n with open(input,'r') as fin:\n indata = json.load(fin)\n # First pass normalizes names and builds a name dictionary and field list.\n year = 0;\n names = set()\n years = list()\n names.add(noname)\n count = 0\n for key in indata.keys():\n d = key.split('_')[2].split('.')[0]\n y = d.split('-')[0]\n print(y)\n count += 1\n if int(y)>int(year):\n year = y\n #print(year)\n print(count)\n\n\n\n","sub_path":"results/results-phase2/results_counter.py","file_name":"results_counter.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"219081589","text":"import os\n\nimport torch\nfrom torch import nn\nfrom torch.optim import Adam, lr_scheduler\nfrom torch.autograd import Variable\nfrom torchvision import transforms, datasets\n\nfrom capsuleclassification import DenseCapsule\nfrom feature_extraction_capsule_layers import FeatureExtractionConvolution\n\n\nclass _CapsuleNet(nn.Module):\n \"\"\"\n A Capsule Network on MNIST.\n :param input_size: data size = [channels, width, height]\n :param classes: number of classes\n :param routings: number of routing iterations\n Shape:\n - Input: (batch, channels, width, height), optional (batch, classes) .\n - Output:((batch, classes), (batch, channels, width, height))\n \"\"\"\n\n def __init__(self, input_size, classes, routings):\n super(_CapsuleNet, self).__init__()\n self.input_size = input_size\n self.classes = classes\n self.routings = routings\n self.USE_CUDA = torch.cuda.is_available()\n\n # Layer 1: Just a conventional Conv2D layer\n self.conv1 = nn.Conv2d(input_size[0], 256, kernel_size=9, stride=1, padding=0)\n\n # Layer 2: Conv2D layer with `squash` activation, then reshape to [None, num_caps, dim_caps]\n self.primarycaps = FeatureExtractionConvolution(256, 256, 8, kernel_size=9, stride=2, padding=0)\n\n # Layer 3: Capsule layer. Routing algorithm works here.\n self.digitcaps = DenseCapsule(in_num_caps=32 * 6 * 6, in_dim_caps=8,\n out_num_caps=classes, out_dim_caps=16, routings=routings)\n\n # Decoder network.\n self.decoder = nn.Sequential(\n nn.Linear(16 * classes, 512),\n nn.ReLU(inplace=True),\n nn.Linear(512, 1024),\n nn.ReLU(inplace=True),\n nn.Linear(1024, input_size[0] * input_size[1] * input_size[2]),\n nn.Sigmoid()\n )\n\n self.relu = nn.ReLU()\n\n def forward(self, x, y=None):\n x = self.relu(self.conv1(x))\n x = self.primarycaps(x)\n x = self.digitcaps(x)\n length = x.norm(dim=-1)\n if y is None: # during testing, no label given. create one-hot coding using `length`\n index = length.max(dim=1)[1]\n if self.USE_CUDA:\n y = Variable(torch.zeros(length.size()).scatter_(1, index.view(-1, 1).cpu().data, 1.).cuda())\n else:\n y = Variable(torch.zeros(length.size()).scatter_(1, index.view(-1, 1).cpu().data, 1.))\n reconstruction = self.decoder((x * y[:, :, None]).view(x.size(0), -1))\n return length, reconstruction.view(-1, *self.input_size)\n\n\nclass MNISTCapsuleClassifierConfiguration:\n epochs = 2\n batch_size = 100\n lr = 0.001\n lr_decay = 0.9\n lam_recon = 0.0005 * 784\n routings = 3\n shift_pixels = 2\n data_dir = './data'\n download = True\n save_dir = './result'\n\n input_size=[1, 28, 28]\n classes = 10\n routings = 3\n\n\nclass MNISTCapsuleClassifier:\n def __init__(self, input_size=[1, 28, 28], classes=10, routings=3, configuration=None, model_path=None):\n\n if configuration is None:\n self.config = MNISTCapsuleClassifierConfiguration()\n else:\n self.config = configuration\n\n print(self.config)\n if not os.path.exists(self.config.save_dir):\n os.makedirs(self.config.save_dir)\n\n self.model = _CapsuleNet(input_size=input_size, classes=classes, routings=routings)\n self.use_cuda = torch.cuda.is_available()\n self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n if self.use_cuda:\n self.model.cuda()\n print(self.model)\n\n if model_path:\n self.model.load_state_dict(torch.load(model_path, map_location=self.device))\n\n def caps_loss(self, y_true, y_pred, x, x_recon, lam_recon):\n \"\"\"\n Capsule loss = Margin loss + lam_recon * reconstruction loss.\n :param y_true: true labels, one-hot coding, size=[batch, classes]\n :param y_pred: predicted labels by CapsNet, size=[batch, classes]\n :param x: input data, size=[batch, channels, width, height]\n :param x_recon: reconstructed data, size is same as `x`\n :param lam_recon: coefficient for reconstruction loss\n :return: Variable contains a scalar loss value.\n \"\"\"\n L = y_true * torch.clamp(0.9 - y_pred, min=0.) ** 2 + \\\n 0.5 * (1 - y_true) * torch.clamp(y_pred - 0.1, min=0.) ** 2\n L_margin = L.sum(dim=1).mean()\n\n L_recon = nn.MSELoss()(x_recon, x)\n\n return L_margin + lam_recon * L_recon\n\n def show_reconstruction(self, test_loader, n_images):\n import matplotlib.pyplot as plt\n from utils import combine_images\n from PIL import Image\n import numpy as np\n\n self.model.eval()\n for x, _ in test_loader:\n if self.use_cuda:\n x = Variable(x[:min(n_images, x.size(0))].cuda(), volatile=True)\n else:\n x = Variable(x[:min(n_images, x.size(0))], volatile=True)\n _, x_recon = self.model(x)\n data = np.concatenate([x.data.cpu(), x_recon.data.cpu()])\n img = combine_images(np.transpose(data, [0, 2, 3, 1]))\n image = img * 255\n Image.fromarray(image.astype(np.uint8)).save(self.config.save_dir + \"/real_and_recon.png\")\n print()\n print('Reconstructed images are saved to %s/real_and_recon.png' % config.save_dir)\n print('-' * 70)\n plt.imshow(plt.imread(config.save_dir + \"/real_and_recon.png\", ))\n plt.show()\n break\n\n def test(self,test_loader):\n self.model.eval()\n test_loss = 0\n correct = 0\n for x, y in test_loader:\n y = torch.zeros(y.size(0), 10).scatter_(1, y.view(-1, 1), 1.)\n if self.use_cuda:\n x, y = Variable(x.cuda(), volatile=True), Variable(y.cuda())\n else:\n x, y = Variable(x, volatile=True), Variable(y)\n y_pred, x_recon = self.model(x)\n test_loss += self.caps_loss(y, y_pred, x, x_recon, self.config.lam_recon).data.item() * x.size(0) # sum up batch loss\n y_pred = y_pred.data.max(1)[1]\n y_true = y.data.max(1)[1]\n correct += y_pred.eq(y_true).cpu().sum()\n\n test_loss /= len(test_loader.dataset)\n return test_loss, correct.item() / len(test_loader.dataset)\n\n def train(self, train_loader, test_loader):\n \"\"\"\n Training a CapsuleNet\n :param model: the CapsuleNet model\n :param train_loader: torch.utils.data.DataLoader for training data\n :param test_loader: torch.utils.data.DataLoader for test data\n :param args: arguments\n :return: The trained model\n \"\"\"\n print('Begin Training' + '-' * 70)\n from time import time\n\n t0 = time()\n optimizer = Adam(self.model.parameters(), lr=self.config.lr)\n lr_decay = lr_scheduler.ExponentialLR(optimizer, gamma=self.config.lr_decay)\n best_val_acc = 0.\n for epoch in range(self.config.epochs):\n self.model.train() # set to training mode\n lr_decay.step() # decrease the learning rate by multiplying a factor `gamma`\n ti = time()\n training_loss = 0.0\n for i, (x, y) in enumerate(train_loader): # batch training\n y = torch.zeros(y.size(0), 10).scatter_(1, y.view(-1, 1), 1.) # change to one-hot coding\n if self.use_cuda:\n x, y = Variable(x.cuda()), Variable(y.cuda()) # convert input data to GPU Variable\n else:\n x, y = Variable(x), Variable(y)\n\n optimizer.zero_grad() # set gradients of optimizer to zero\n y_pred, x_recon = self.model(x, y) # forward\n loss = self.caps_loss(y, y_pred, x, x_recon, self.config.lam_recon) # compute loss\n loss.backward() # backward, compute all gradients of loss w.r.t all Variables\n training_loss += loss.data.item() * x.size(0) # record the batch loss\n optimizer.step() # update the trainable parameters with computed gradients\n print(\"epoch {}, minibatch {}, loss {}\".format(epoch, i, loss.data.item()))\n\n # compute validation loss and acc\n val_loss, val_acc = self.test(test_loader)\n print(\"==> Epoch %02d: loss=%.5f, val_loss=%.5f, val_acc=%.4f, time=%ds\"\n % (epoch, training_loss / len(train_loader.dataset),\n val_loss, val_acc, time() - ti))\n if val_acc > best_val_acc: # update best validation acc and save model\n best_val_acc = val_acc\n torch.save(self.model.state_dict(), self.config.save_dir + '/epoch%d.pkl' % epoch)\n print(\"best val_acc increased to %.4f\" % best_val_acc)\n torch.save(self.model.state_dict(), self.config.save_dir + '/trained_model.pkl')\n print('Trained model saved to \\'%s/trained_model.h5\\'' % self.config.save_dir)\n print(\"Total time = %ds\" % (time() - t0))\n print('End Training' + '-' * 70)\n\n\n\nif __name__ == \"__main__\":\n def load_mnist(path='./data', download=False, batch_size=100, shift_pixels=2):\n \"\"\"\n Construct dataloaders for training and test data. Data augmentation is also done here.\n :param path: file path of the dataset\n :param download: whether to download the original data\n :param batch_size: batch size\n :param shift_pixels: maximum number of pixels to shift in each direction\n :return: train_loader, test_loader\n \"\"\"\n kwargs = {'num_workers': 1, 'pin_memory': True}\n\n train_loader = torch.utils.data.DataLoader(\n datasets.MNIST(path, train=True, download=download,\n transform=transforms.Compose([transforms.RandomCrop(size=28, padding=shift_pixels),\n transforms.ToTensor()])),\n batch_size=batch_size, shuffle=True, **kwargs)\n test_loader = torch.utils.data.DataLoader(\n datasets.MNIST(path, train=False, download=download,\n transform=transforms.ToTensor()),\n batch_size=batch_size, shuffle=True, **kwargs)\n\n return train_loader, test_loader\n\n\n mode = 'test'\n config = MNISTCapsuleClassifierConfiguration()\n train_loader, test_loader = load_mnist(config.data_dir, download=True, batch_size=config.batch_size)\n if mode == 'train':\n classifier = MNISTCapsuleClassifier(input_size=config.input_size, classes=config.classes,routings=config.routings,configuration=config)\n classifier.train(train_loader,test_loader)\n classifier.show_reconstruction(test_loader, 50)\n elif mode == 'test':\n classifier = MNISTCapsuleClassifier(input_size=config.input_size, classes=config.classes,\n routings=config.routings, configuration=config, model_path=config.save_dir + '/trained_model.pkl')\n classifier.test(test_loader)\n classifier.show_reconstruction(test_loader, 50)\n\n","sub_path":"capsule/MnistConvCapsuleNetwork.py","file_name":"MnistConvCapsuleNetwork.py","file_ext":"py","file_size_in_byte":11159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"579802766","text":"#Create a program that asks the user for a number and then prints out a list of all the divisors of that number. \n#(If you don’t know what a divisor is, it is a number that divides evenly into another number. \n#For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)\n\nnum = int(input(\"Enter a number: \"))\nnumlist = list()\n\nx = range(1, num+1)\n\nfor each in x:\n y = num % each\n if y == 0:\n numlist.append(each)\n else:\n continue\n\nprint (numlist)","sub_path":"divisors.py","file_name":"divisors.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"645165199","text":"\n\nfrom xai.brain.wordbase.nouns._viscount import _VISCOUNT\n\n#calss header\nclass _VISCOUNTS(_VISCOUNT, ):\n\tdef __init__(self,): \n\t\t_VISCOUNT.__init__(self)\n\t\tself.name = \"VISCOUNTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"viscount\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_viscounts.py","file_name":"_viscounts.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"470507811","text":"import torch\nfrom pathlib import Path\n\nfrom utils import (get_classes, get_log_csv_name, get_log_csv_train_order)\nfrom utils_model_grads import train_resnet_with_grads_no_update\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\npath_mean, path_std = ( [0.40853017568588257, 0.4573926329612732, 0.48035722970962524], \n [0.28722450137138367, 0.27334490418434143, 0.2799932360649109])\n\nexp_num = 45\n\n# Named with date and time.\ntrain_folder = Path(\"/home/brenta/scratch/jason/data/voc/voc_trainval_full\")\nlog_folder = Path(\"/home/brenta/scratch/jason/logs/voc/vanilla/exp_\" + str(exp_num))\nlog_csv = get_log_csv_name(log_folder=log_folder)\nresume_checkpoint_path = Path(\"/home/brenta/scratch/jason/checkpoints/voc/vanilla/exp_44/resnet18_e0_mb40_va0.45239.pt\") #resnet18_e2_mb120_va0.48665.pt\ngrad_csv = log_folder.joinpath(resume_checkpoint_path.name + \"_grads.csv\")\ntrain_order_csv = get_log_csv_train_order(log_folder=log_folder)\nclasses = get_classes(train_folder.joinpath(\"train\"))\nnum_classes = len(classes)\n\n# Training the ResNet.\nprint(\"\\n\\n+++++ Running 3_train.py +++++\")\ntrain_resnet_with_grads_no_update( batch_size=1,\n checkpoints_folder=Path(\"/home/brenta/scratch/jason/checkpoints/voc/vanilla/exp_\" + str(exp_num)),\n classes=classes,\n color_jitter_brightness=0,\n color_jitter_contrast=0,\n color_jitter_hue=0,\n color_jitter_saturation=0,\n device=device,\n grad_csv=grad_csv,\n learning_rate=0.0001,\n learning_rate_decay=0.5,\n log_csv=log_csv,\n train_order_csv=train_order_csv,\n num_classes=num_classes,\n num_layers=18,\n num_workers=8,\n path_mean=path_mean,\n path_std=path_std,\n pretrain=False,\n resume_checkpoint=True,\n resume_checkpoint_path=resume_checkpoint_path,\n save_interval=0,\n num_epochs=1,\n train_folder=train_folder,\n weight_decay=1e-4)\nprint(\"+++++ Finished running 3_train.py +++++\\n\\n\")","sub_path":"code/grad_cl/in_get_grads.py","file_name":"in_get_grads.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"618465059","text":"from lingpy import *\n\nwl = Wordlist('../data/Dogon-227-20-alignments.tsv')\n\netd = wl.get_etymdict(ref='lexstatid')\nfor k, v in sorted(etd.items(), key=lambda x: sum([1 for y in x[1] if y != 0]),\n reverse=False):\n concept = wl[[x for x in v if x != 0][0][0], 'concept']\n refs = sum([1 for x in v if x != 0])\n print('{0:30}\\t{1}'.format(concept, refs))\n","sub_path":"helpers/helper-coverage.py","file_name":"helper-coverage.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"487081611","text":"import uuid\nfrom blackbot.core.wss.crypto import gen_stager_psk\nfrom blackbot.core.wss.stager import Stager\nfrom blackbot.core.utils import gen_random_string_no_digits, get_path_in_package\nfrom blackbot.core.wss.utils import dotnet_deflate_and_encode\n\n\nclass ARTIC2Stager(Stager):\n def __init__(self):\n self.name = 'msbuild'\n self.description = 'Stage via MSBuild XML inline C# task'\n self.suggestions = ''\n self.extension = 'xml'\n self.options = {}\n\n def generate(self, listener):\n with open(get_path_in_package('core/wss/data/naga.exe'), 'rb') as assembly:\n with open(get_path_in_package('core/wss/stagers/templates/msbuild.xml')) as template:\n guid = uuid.uuid4()\n psk = gen_stager_psk()\n\n c2_urls = ','.join(\n filter(None, [listener['CallBackURls']])\n )\n\n template = template.read()\n template = template.replace('GUID', str(guid))\n template = template.replace('PSK', psk)\n template = template.replace('URLS', c2_urls)\n template = template.replace(\"NAME_GOES_HERE\", gen_random_string_no_digits(5))\n template = template.replace(\"BASE64_ENCODED_ASSEMBLY\", dotnet_deflate_and_encode(assembly.read()))\n return guid, psk, template\n\n #print_good(f\"Generated stager to {stager.name}\")\n #print_info(\n # f\"Launch with 'C:\\\\Windows\\\\Microsoft.NET\\\\Framework64\\\\v4.0.30319\\\\msbuild.exe {stager_filename}'\")\n","sub_path":"blackbot/core/wss/stagers/msbuild.py","file_name":"msbuild.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"570952907","text":"#\n# File : Avatar.py\n# \n# Code written by : Johann Heches\n#\n# Description : Preprocess the avatar layer by layer.\n# \n\n\nclass characteristics(object):\n \"\"\"\n characteristics\n .o rotation angle\n .xyz rotation axis\n \"\"\"\n\n\n def __init__(self, ini = 1.70): # add orientation here or keep it on origin limb ?\n \"\"\" constructor \"\"\"\n self.tag = \"\"\n self.size = ini # change to a 3D scale after ?\n self.position = [0, 0, 0]\n self.orientation = [1, 0, 0, 0]\n self.limbs = []\n self.mesh = None\n self.muscles = []\n\n\n\n\nfrom OpenGL.GL import *\nimport numpy as np\nimport math\n\nimport Definitions\nimport Events\nimport Graphics\nimport ID\nimport Limbs\nimport Muscles\n\n\n\nvirtuMan = None\n\n \nlimb = -1 # global helps through recursivity\nselectedLimbs = []\n\n\"\"\" recursive function that generates limbs by layers \"\"\"\ndef stick(entity, offset = (0,0,0)):\n global limb\n global selectedLimb\n if limb + 1 >= len(entity.limbs):\n return\n\n limb += 1\n current_limb = limb\n\n \"\"\" Check if limb is selected \"\"\"\n limbIsSelected = False\n for selectedLimb in selectedLimbs:\n if selectedLimb == entity.limbs[current_limb].tag:\n limbIsSelected = True\n break\n\n \"\"\" default orientation of limb \"\"\"\n l = Definitions.vector4D.Eul2Quat(Definitions.vector4D((0, entity.limbs[current_limb].angleRepos[0], entity.limbs[current_limb].angleRepos[1], entity.limbs[current_limb].angleRepos[2])))\n\n\n \"\"\" new rotation to implement \"\"\"\n if limbIsSelected == True:\n \"\"\" swing command with saturations \"\"\"\n sw = Definitions.vector4D.Swing(Definitions.vector4D((entity.limbs[current_limb].swing)), (entity.limbs[current_limb].saturation.saturations))\n entity.limbs[current_limb].swing = [sw.o,sw.x,sw.y,sw.z]\n\n \"\"\" twist command with saturations \"\"\"\n tw = Definitions.vector4D.Twist(Definitions.vector4D((entity.limbs[current_limb].twist)), (entity.limbs[current_limb].saturation.saturations))\n entity.limbs[current_limb].twist = [tw.o,tw.x,tw.y,tw.z]\n\n \"\"\" twist effect on vbo \"\"\"\n entity.limbs[current_limb].mesh.twistVBO(Definitions.vector4D(entity.limbs[current_limb].twist).quatAngle())\n\n\n \"\"\" current rotation of limb \"\"\"\n Qsw = Definitions.vector4D((entity.limbs[current_limb].swing))\n Qtw = Definitions.vector4D((entity.limbs[current_limb].twist))\n \n\n \"\"\" Transformations \"\"\"\n Definitions.modelMatrix.push()\n \"\"\" offset to apply \"\"\"\n Definitions.modelMatrix.translate(offset[0] + entity.size*entity.limbs[current_limb].offset[0], offset[1] + entity.size*entity.limbs[current_limb].offset[1], offset[2] + entity.size*entity.limbs[current_limb].offset[2])\n \n if limbIsSelected == True:\n Definitions.modelMatrix.push()\n \n Cy = 0.5*(entity.limbs[current_limb].saturation.saturations[2]+entity.limbs[current_limb].saturation.saturations[3])\n Cz = 0.5*(entity.limbs[current_limb].saturation.saturations[4]+entity.limbs[current_limb].saturation.saturations[5])\n Qoffset = Definitions.vector4D.Eul2Quat(Definitions.vector4D((0,0,Cy,Cz)))\n p = Definitions.vector4D.Quat2Vec(Definitions.vector4D.QuatProd(l,Qoffset))\n if math.sqrt(p.x*p.x + p.y*p.y + p.z*p.z) >= 0.0001:\n Definitions.modelMatrix.rotate(p.o, p.x, p.y, p.z)\n scale = 2*entity.size*entity.limbs[current_limb].dimensions[0]\n Definitions.modelMatrix.scale(scale,scale,scale)\n \n entity.limbs[current_limb].saturation.modelMatrix = Definitions.modelMatrix.peek()\n\n Definitions.modelMatrix.pop()\n\n \n \"\"\" total rotation to apply \"\"\"\n p = Definitions.vector4D.Quat2Vec(Definitions.vector4D.QuatProd(l,Qsw))\n if math.sqrt(p.x*p.x + p.y*p.y + p.z*p.z) >= 0.0001:\n Definitions.modelMatrix.rotate(p.o, p.x, p.y, p.z)\n \n \"\"\" preprocess limb \"\"\"\n x = entity.size*entity.limbs[current_limb].dimensions[0]\n y = entity.size*entity.limbs[current_limb].dimensions[1]\n z = entity.size*entity.limbs[current_limb].dimensions[2]\n dx = 0.5*entity.size*entity.limbs[current_limb].dimensions[0]\n dy = 0\n dz = 0\n Limbs.preprocessLimb(entity,x,y,z,dx,dy,dz,limbIsSelected, current_limb)\n\n \n \"\"\" total rotation to apply \"\"\"\n p = Definitions.vector4D.Quat2Vec(Qtw)\n if math.sqrt(p.x*p.x + p.y*p.y + p.z*p.z) >= 0.0001:\n Definitions.modelMatrix.rotate(p.o, p.x, p.y, p.z)\n\n \"\"\" recursive call for all limbs children to the current one \"\"\"\n while limb + 1 < len(entity.limbs) and entity.limbs[limb+1].layer > entity.limbs[current_limb].layer:\n stick(entity, (x, 0, 0))\n\n Definitions.modelMatrix.pop()\n\n\ndef oneMesh(entity):\n entity.mesh = Graphics.mesh()\n entity.mesh.vertices = np.array([], dtype='f')\n entity.mesh.surfIndices = np.array([], dtype=np.int32)\n entity.mesh.edgeIndices = np.array([], dtype=np.int32)\n entity.mesh.surfNbIndex = []\n entity.mesh.edgeNbIndex = []\n entity.mesh.surfIndexOffset = []\n entity.mesh.edgeIndexOffset = []\n entity.mesh.surfStyleIndex = []\n entity.mesh.edgeStyleIndex = []\n for limb in entity.limbs:\n entity.mesh.surfIndices = np.append(entity.mesh.surfIndices, limb.mesh.surfIndices + entity.mesh.vertices.size/3)\n entity.mesh.edgeIndices = np.append(entity.mesh.edgeIndices, limb.mesh.edgeIndices + entity.mesh.vertices.size/3)\n entity.mesh.vertices = np.append(entity.mesh.vertices, limb.mesh.vertices)\n if entity.mesh.surfIndexOffset != []:\n entity.mesh.surfIndexOffset = entity.mesh.surfIndexOffset + [entity.mesh.surfIndexOffset[-1] + entity.mesh.surfNbIndex[-1],]\n entity.mesh.edgeIndexOffset = entity.mesh.edgeIndexOffset + [entity.mesh.edgeIndexOffset[-1] + entity.mesh.edgeNbIndex[-1],]\n else:\n entity.mesh.surfIndexOffset = [0]\n entity.mesh.edgeIndexOffset = [0]\n entity.mesh.surfNbIndex = entity.mesh.surfNbIndex + [limb.mesh.surfNbIndex,]\n entity.mesh.edgeNbIndex = entity.mesh.edgeNbIndex + [limb.mesh.edgeNbIndex,]\n entity.mesh.surfStyleIndex = entity.mesh.surfStyleIndex + [limb.mesh.surfStyleIndex,]\n entity.mesh.edgeStyleIndex = entity.mesh.edgeStyleIndex + [limb.mesh.edgeStyleIndex,]\n Graphics.buildVBO(entity)","sub_path":"Avatar.py","file_name":"Avatar.py","file_ext":"py","file_size_in_byte":6347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"10130995","text":"import socket\r\nimport uuid\r\n#generating 4-bytes random ids\r\nimport pickle\r\n#for serializing and deserializing python object structure\r\nimport threading\r\n#creating multiple threads\r\nimport sys\r\n\r\nport=9300\r\nmax_chunk=1024\r\n\r\nclass server:\r\n def __init__(self,port,no_of_connections):\r\n self.port=port #portno of this machine\r\n self.host=socket.gethostbyname(socket.gethostname()) #ip of this machine\r\n self.no_of_connections=no_of_connections#no.of connections\r\n self.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n self.file={}#list of files registered\r\n self.peers={}#list of peers connected\r\n\r\n x=True\r\n while x:\r\n try:\r\n self.sock.bind((self.host,self.port))\r\n except OverflowError:\r\n self.port=input(\"Enter new port(>3000)\")#alternative portno\r\n else:\r\n x=False\r\n\r\n print(\"listening through [\",self.host,\":\",self.port,\"]\")\r\n\r\n\r\n\r\n\r\n def peer_threads(self,client,addr):\r\n\r\n peer_id=uuid.uuid4().int>>115\r\n #generates unique id for each peer\r\n\r\n self.peers[peer_id]=addr\r\n #appending peer spacifications to list of peers\r\n\r\n client.send(pickle.dumps((peer_id,addr[1])))\r\n #sending peerid to the recipient and also the portno for connection\r\n\r\n\r\n while True: \r\n method=pickle.loads(client.recv(max_chunk)) \r\n\r\n print(\"Method opted by peer_id-\",peer_id,\" is \",method)\r\n\r\n if(method==\"search\"):\r\n #searching a file in the centralized directory\r\n client.send(pickle.dumps(\"ok\"))\r\n file_name=pickle.loads(client.recv(max_chunk))\r\n #loading up the name of the file needed for searching\r\n\r\n if(file_name in self.file):\r\n client.send(pickle.dumps('found'))\r\n reply=pickle.loads(client.recv(max_chunk))\r\n #getting reply from the peer whether to send or not\r\n\r\n if(reply=='send'):#peer asks to send\r\n content=pickle.dumps(self.file[file_name])\r\n client.send(content)\r\n\r\n #In case of files contained by many peers\r\n #selection of file from which peer is needed\r\n peerno=pickle.loads(client.recv(max_chunk))\r\n client.send(pickle.dumps(self.peers[peerno]))\r\n else:\r\n \"only search is done..\"\r\n else:\r\n #file not found(invalid one)\r\n client.send(pickle.dumps(\"not found\"))\r\n \r\n\r\n elif(method=='register'):\r\n #registering files to the server by peers\r\n #in order to access\r\n client.send(pickle.dumps('ok'))\r\n file_name=pickle.loads(client.recv(max_chunk))\r\n print(\"For registering file by peer_id-\",peer_id)\r\n\r\n if file_name in self.file:\r\n self.file[file_name].append(peer_id)\r\n #in case of file contained only the peerids are noted for \r\n #the file\r\n else:\r\n self.file[file_name]=[]\r\n self.file[file_name].append(peer_id)\r\n #new file list created and peerids are appended\r\n client.send(pickle.dumps('success'))\r\n\r\n elif(method=='bye'):\r\n client.send(pickle.dumps('ok'))\r\n\r\n list1=[]\r\n\r\n #peerids present in the files are deleted in file list\r\n #if file[file_name] is empty\r\n #then file_name should be deleted in register\r\n\r\n for i in self.file:\r\n try:\r\n self.file[i].remove(peer_id)\r\n if(self.file[i]==[]):\r\n list1.append(i)\r\n except ValueError:\r\n continue\r\n \r\n\r\n #peerids are deleted in peers list\r\n del self.peers[peer_id]\r\n sys.exit(0)\r\n\r\n\r\n\r\n def connections(self):\r\n thread_id=[]\r\n self.sock.listen(self.no_of_connections)\r\n \r\n while True:\r\n client,addr=self.sock.accept() #accepting connections\r\n print(\"Connected with \",addr)\r\n\r\n\r\n #thread creation for each peer\r\n try:\r\n t=threading.Thread(target=self.peer_threads,args=(client,addr))\r\n #creating threads and passing arguments\r\n t.start()\r\n #starting the thread\r\n print(\"thread started\")\r\n\r\n\r\n except:\r\n print(\"Thread didn't start\")\r\n\r\n self.sock.close()\r\n\r\n\r\nif __name__=='__main__':\r\n s=server(port,5)\r\n s.connections()","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"348386367","text":"# Standard library\nimport pdb\n\n# Numpy imports\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n# Custom imports\nimport core_causal_features\n\nclass Ai_Human(core_causal_features.Agent):\n def __init__(self, pos_class_digit=7):\n self.pos_class_digit = pos_class_digit\n\n def behave(self, I):\n \"\"\" \n An \"ai\" module that queries a human about the class\n of the current image of an MNIST digit, or a manipulated\n image of a digit.\n\n The ai queries whether or not given image represents \n a digit of class 'pos_class_digit'.\n \"\"\"\n fig = plt.figure(figsize=(2,2))\n ax = fig.add_subplot(111)\n plt.axis('off')\n ax.set_title(\"Press 'y' if {}\".format(self.pos_class_digit))\n ax.imshow(I, cmap='Greys', interpolation='nearest',\n vmin=0, vmax=1)\n press_list = [0]\n\n def onkeypress(event, press_list=press_list):\n press_list[0] = event.key\n plt.close()\n \n fig.canvas.mpl_connect('key_press_event', onkeypress)\n plt.show()\n\n if press_list[0] == 'y':\n return 1\n else:\n return 0\n","sub_path":"Experiments/ai_mnist.py","file_name":"ai_mnist.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"269867755","text":"import re\n\n\ndef do_it(filename):\n with open(filename) as f:\n lines = list(map(str.strip, f.readlines()))\n\n memory = {}\n regex = re.compile(r'mem\\[(\\d+)] = (\\d+)')\n for line in lines:\n if line.startswith('mask'):\n mask_str = line.split('=')[1].strip()\n mask0 = int(mask_str.replace('X', '1'), 2)\n mask1 = int(mask_str.replace('X', '0'), 2)\n else:\n m = regex.fullmatch(line)\n memory[int(m[1])] = (int(m[2]) & mask0) | mask1\n return sum(memory.values())\n\n\nif __name__ == '__main__':\n output = do_it('input1.txt')\n print(f'Result: {output}')\n\n# Result: 4297467072083\n","sub_path":"2020/14/141.py","file_name":"141.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"383015210","text":"import PyNN as pn\n\n# Create variables\nA = pn.Variable([[1, 0], [0, -1]])\nb = pn.Variable([1, 1])\n\n# Create placeholder\nx = pn.placeholder()\n\n# Create hidden node y\ny = pn.matmul(A, x)\n\n# Create output node z\nz = pn.add(y, b)\n\nsession = pn.Session()\noutput = session.run(z, {\n x: [1, 2]\n})\nprint(output)","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"376947276","text":"class TicTacToe:\n def __init__(self):\n self.board = [\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]\n self.current_turn = \"O\"\n\n def set(self, row, col):\n if self.get(row, col) == \".\":\n self.board[row*3+col] = self.current_turn\n self.current_turn = \"X\" if self.current_turn == \"O\" else \"O\"#O면 X를 넣고 아니면 O를 넣어라\n\n def get(self, row, col) :\n return board[row*3+col]\n\n def check_winner(self):\n check = self.current_turn\n for i in range(3):\n if self.get(i,0) == self.get(i,1) == self.get(i,2) == check:\n return check\n if self.get(0,i) == self.get(1,i) == self.get(2,i) == check:\n return check\n\n def __str__(self):\n s = \"\"\n for i, ch in enumerate(self.board):\n s += ch\n if i% 3 ==2:\n s+=\"\\n\"\n return s\n \nif __name__ == '__main__':\n ttt = TicTacToe()\n ttt.set(1,1)\n print(ttt)\n ","sub_path":"2-4/2학기/amasvin/TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"251123485","text":"from django.shortcuts import render\n#from django.shortcuts import get_object_or_404\n#from django.shortcuts import redirect\n#from django.urls import reverse \nfrom .models import Weapon, Ammo\nfrom django.views.generic import View\nfrom .utils import ObjectDetailMixin, ObjectCreateMixin, ObjectUpdateMixin, ObjectDelMixin\nfrom .forms import AmmoForm, WeaponForm\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.core.paginator import Paginator\nfrom django.db.models import Q\n\n\n\ndef main_page(request):\n return render(request, 'inf/Главная.html')\n\ndef weapon_list(request):\n weapons = Weapon.objects.all()\n search_name = request.GET.get('search_name')\n search_caliber = request.GET.get('search_caliber')\n search_description = request.GET.get('search_description')\n\n if search_name != '' and search_name is not None:\n weapons = weapons.filter(name__icontains=search_name)\n elif search_caliber != '' and search_caliber is not None:\n weapons = weapons.filter(caliber__icontains=search_caliber)\n elif search_description != '' and search_description is not None:\n weapons = weapons.filter(description__icontains=search_description)\n# search_query = request.GET.get('search_name', '')\n\n# if search_query:\n# weapons = Weapon.objects.filter(Q(name__icontains=search_query) | Q(description__icontains=search_query) | Q(caliber__icontains=search_query))\n# else:\n# weapons = Weapon.objects.all()\n\n paginator = Paginator(weapons, 5)#обратная замена qs на weapons\n\n page_number = request.GET.get('page', 1)\n page = paginator.get_page(page_number)\n is_paginated = page.has_other_pages()\n\n if page.has_previous():\n prev_url = '?page={}'.format(page.previous_page_number())\n else:\n prev_url = ''\n\n if page.has_next():\n next_url = '?page={}'.format(page.next_page_number())\n else:\n next_url = ''\n\n context ={\n 'page_object': page,\n 'is_paginated': is_paginated,\n 'next_url': next_url,\n 'prev_url': prev_url,\n 'queryset': weapons\n }\n return render(request, 'inf/weaponls.html', context=context)\n\nclass WeaponDetail(ObjectDetailMixin, View):\n model = Weapon\n template = 'inf/weapondl.html'\n\nclass WeaponCreate(LoginRequiredMixin, ObjectCreateMixin, View):\n model_form = WeaponForm\n template = 'inf/weaponcrt.html'\n raise_exception = True\n\nclass WeaponUpdate(LoginRequiredMixin, ObjectUpdateMixin, View):\n model = Weapon\n model_form = WeaponForm\n template = 'inf/weapon_update_form.html'\n raise_exception = True\n\n\nclass WeaponDel(LoginRequiredMixin, ObjectDelMixin, View):\n model = Weapon\n template = 'inf/weapondel.html'\n redirect_url = 'weapon_list_url'\n raise_exception = True\n\ndef ammo_list(request):\n ammos = Ammo.objects.all()\n return render(request, 'inf/ammols.html', context={'ammos': ammos})\n\nclass AmmoDetail(ObjectDetailMixin, View):\n model = Ammo\n template = 'inf/ammodl.html'\n\nclass AmmoCreate(LoginRequiredMixin, ObjectCreateMixin, View):\n model_form = AmmoForm\n template = 'inf/ammocrt.html'\n raise_exception = True\n\nclass AmmoUpdate(LoginRequiredMixin, ObjectUpdateMixin, View):\n model = Ammo\n model_form = AmmoForm\n template = 'inf/ammo_update_form.html'\n raise_exception = True\n\nclass AmmoDel(LoginRequiredMixin, ObjectDelMixin, View):\n model = Ammo\n template = 'inf/ammodel.html'\n redirect_url = 'ammo_list_url'\n raise_exception = True","sub_path":"infsys/inf/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"222461477","text":"import os\nimport sys\nimport DoriC\nimport Assembly\n\ndef main():\n if len(sys.argv) != 4:\n print(\"Usage: \")\n sys.exit()\n\n doric = DoriC.get_entries(sys.argv[2])\n assemblies = Assembly.get_entries(sys.argv[3])\n with open(sys.argv[1]) as f:\n data = [l.strip().split('\\t') for l in f]\n doric_idx = {d.id:d for d in doric}\n asm_idx = {a.assembly:a for a in assemblies}\n\n new_data = list()\n for elem in data:\n ori_pos = doric_idx[elem[0]].position\n asm_filename = asm_idx[elem[1]].filename\n genome_length = -1\n if elem[3] == 'ASM':\n genome_length = asm_idx[elem[1]].contigs[0][1]\n if elem[3] == 'REFSEQ':\n for refseq, length in asm_idx[elem[1]].contigs:\n if refseq == elem[2]:\n genome_length = length\n break\n if genome_length == -1:\n print('ERROR')\n sys.exit()\n if genome_length == -1:\n print('ERROR')\n sys.exit()\n new_data.append(elem + [str(ori_pos), asm_filename, str(genome_length)])\n print('\\t'.join(['ori_id','asm_id','refseq','hit','gn:kegg','ori_pos','fname','genome_len']))\n print('\\n'.join(['\\t'.join(e) for e in new_data]))\n\nif __name__ == '__main__':\n main()\n","sub_path":"enrichment_analysis/kegg_analysis/add_info.py","file_name":"add_info.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"335445357","text":"# import the necessary packages\nfrom keras.models import load_model\nfrom collections import deque\nimport numpy as np\nimport argparse\nimport pickle\nimport cv2\nimport os\nfrom random import randrange\n\n\nimg_dir = 'output_images/'\nmodel = 'model/activity.model'\nlabel_bin = 'model/lb.pickle'\ninput_dir = 'example_clips/accident.mp4'\noutput_dir = 'output/lifting_128avg.avi'\nsize = 128\n\n# load the trained model and label binarizer from disk\nprint(\"[INFO] loading model and label binarizer...\")\nmodel = load_model(model)\nlb = pickle.loads(open(label_bin, \"rb\").read())\n\n# initialize the image mean for mean subtraction along with the\n# predictions queue\nmean = np.array([123.68, 116.779, 103.939][::1], dtype=\"float32\")\nQ = deque(maxlen=size)\n\n# initialize the video stream, pointer to output video file, and\n# frame dimensions\nvs = cv2.VideoCapture(input_dir)\nwriter = None\n(W, H) = (None, None)\n\n# loop over frames from the video file stream\nwhile True:\n # read the next frame from the file\n (grabbed, frame) = vs.read()\n\n # if the frame was not grabbed, then we have reached the end\n # of the stream\n if not grabbed:\n break\n\n # if the frame dimensions are empty, grab them\n if W is None or H is None:\n (H, W) = frame.shape[:2]\n\n # clone the output frame, then convert it from BGR to RGB\n # ordering, resize the frame to a fixed 224x224, and then\n # perform mean subtraction\n output = frame.copy()\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n frame = cv2.resize(frame, (224, 224)).astype(\"float32\")\n frame -= mean\n\n # make predictions on the frame and then update the predictions\n # queue\n preds = model.predict(np.expand_dims(frame, axis=0))[0]\n Q.append(preds)\n\n # perform prediction averaging over the current history of\n # previous predictions\n results = np.array(Q).mean(axis=0)\n i = np.argmax(results)\n label = lb.classes_[i]\n\n\n# capture all the frame of accident and save it in output_images folder\n if (label == \"accident\"):\n alert = \"warning:{}\".format(label)\n cv2.putText(output, alert, (35, 50), cv2.FONT_HERSHEY_SIMPLEX,\n 1.25, (0, 255, 0), 5)\n irand = randrange(0, 1000)\n # write the output image to disk\n filename = \"{}.png\".format(irand)\n p = os.path.sep.join([img_dir, filename])\n cv2.imwrite(p, output)\n\n # draw the activity on the output frame\n text = \"activity: {}\".format(label)\n cv2.putText(output, text, (35, 50), cv2.FONT_HERSHEY_SIMPLEX,\n 1.25, (255, 0, 0), 5)\n\n# saving the predicted video into output folder\n # check if the video writer is None\n if writer is None:\n # initialize our video writer\n fourcc = cv2.VideoWriter_fourcc(*\"MJPG\")\n writer = cv2.VideoWriter(output_dir, fourcc, 30,\n (W, H), True)\n\n # write the output frame to disk\n writer.write(output)\n\n # show the output image\n cv2.imshow(\"Output\", output)\n key = cv2.waitKey(1) & 0xFF\n\n # if the `q` key was pressed, break from the loop\n if key == ord(\"q\"):\n break\n\n# release the file pointers\n\nprint(\"[INFO] cleaning up...\")\nwriter.release()\nvs.release()\n","sub_path":"predict_video.py","file_name":"predict_video.py","file_ext":"py","file_size_in_byte":3207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"46239518","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSimple example of subclassing GraphItem.\n\"\"\"\nimport os\n\nimport pyqtgraph as pg\nfrom pyqtgraph import ViewBox\nfrom pyqtgraph.Qt import QtCore, QtGui\nimport numpy as np\n\npg.mkQApp()\n# Enable antialiasing for prettier plots\npg.setConfigOptions(antialias=True)\n\npath = os.path.dirname(os.path.abspath(__file__))\nuiFile = os.path.join(path, 'untitled.ui')\nWindowTemplate, TemplateBaseClass = pg.Qt.loadUiType(uiFile)\n\n\n# w = pg.GraphicsLayoutWidget(show=True)\n# w.setWindowTitle('pyqtgraph example: CustomGraphItem')\n\nclass MainWindow(TemplateBaseClass):\n def __init__(self):\n TemplateBaseClass.__init__(self)\n self.ui = WindowTemplate()\n self.ui.setupUi(self)\n self.show()\n self.ui.spinBox.valueChanged.connect(self.changeTableSize)\n self.ui.pushButton.clicked.connect(self.buildGraph)\n\n def changeTableSize(self):\n s = self.ui.spinBox.value()\n self.ui.tableWidget.setRowCount(s)\n self.ui.tableWidget.setColumnCount(s)\n\n def buildGraph(self):\n adj = []\n for i in range(self.ui.tableWidget.rowCount()):\n for j in range(self.ui.tableWidget.columnCount()):\n print(type(self.ui.tableWidget.item(i, j)))\n if int(self.ui.tableWidget.item(i, j).text()):\n adj.append([i, j])\n\n print(adj)\n\n\nprint(11111111111111)\n\n\n# v= w.addViewBox()\n# v.setAspectLocked()\n\n\n# print(type(v))\n\n\nclass Graph(pg.GraphItem):\n\n def __init__(self, ui):\n self.ui = ui\n self.dragPoint = None\n self.dragOffset = None\n self.textItems = []\n self.selectedPoint = None\n pg.GraphItem.__init__(self)\n self.scatter.sigClicked.connect(self.clicked)\n\n def addPoint(self, pos):\n self.data[\"pos\"] = np.append(self.data[\"pos\"], [pos], axis=0)\n self.text.append(\"ssss\")\n self.setTexts(self.text)\n self.setData(text=self.text, adj=self.data[\"adj\"], pxMode=False, size=1, pos=self.data[\"pos\"])\n\n def setData(self, **kwds):\n self.text = kwds.pop('text', [])\n self.data = kwds\n if 'pos' in self.data:\n npts = self.data['pos'].shape[0]\n self.data['data'] = np.empty(npts, dtype=[('index', int)])\n self.data['data']['index'] = np.arange(npts)\n self.setTexts(self.text)\n self.updateGraph()\n\n def setTexts(self, text):\n for i in self.textItems:\n i.scene().removeItem(i)\n self.textItems = []\n for t in text:\n item = pg.TextItem(t)\n self.textItems.append(item)\n item.setParentItem(self)\n\n def updateGraph(self):\n\n pg.GraphItem.setData(self, **self.data)\n for i, item in enumerate(self.textItems):\n item.setPos(*self.data['pos'][i])\n\n def mouseDragEvent(self, ev):\n if ev.button() != QtCore.Qt.LeftButton:\n return\n if ev.isStart():\n # We are already one step into the drag.\n # Find the point(s) at the mouse cursor when the button was first\n # pressed:\n pos = ev.buttonDownPos()\n pts = self.scatter.pointsAt(pos)\n if len(pts) == 0:\n ev.ignore()\n return\n self.dragPoint = pts[0]\n ind = pts[0].data()[0]\n self.dragOffset = self.data['pos'][ind] - pos\n elif ev.isFinish():\n self.dragPoint = None\n return\n else:\n if self.dragPoint is None:\n ev.ignore()\n return\n\n ind = self.dragPoint.data()[0]\n self.data['pos'][ind] = ev.pos() + self.dragOffset\n self.updateGraph()\n ev.accept()\n\n def mouseClickEvent(self, ev):\n if ev.button() == QtCore.Qt.RightButton:\n self.addPoint(ev.pos())\n\n def paintAll(self):\n data = self.scatter.getData()\n newPos = np.vstack([data[0], data[1]]).transpose()\n symbolBrushs = [None] * len(data[0])\n g.setData(pos=newPos, adj=adj, size=1, pxMode=False, text=texts,\n symbolBrush=symbolBrushs)\n self.updateGraph()\n\n def paintPoint(self, mypoint_index):\n data_list = self.scatter.data.tolist()\n print(data_list)\n data = self.scatter.getData()\n newPos = np.vstack([data[0], data[1]]).transpose()\n symbolBrushs = [None] * len(data[0])\n symbolBrushs[mypoint_index] = pg.mkBrush(color=(255, 0, 0))\n g.setPen(symbolBrushs)\n self.updateGraph()\n\n def clicked(self, scatter, pts):\n if self.ui.radioButton.isChecked():\n if self.selectedPoint == None:\n self.selectedPoint = pts[0].index()\n # self.paintPoint(self.selectedPoint)\n print(type(self.data[\"adj\"][0]))\n print(self.data)\n else:\n self.data[\"adj\"] = np.append(self.data[\"adj\"], np.array([[self.selectedPoint, pts[0].index()]]), axis=0)\n self.updateGraph()\n self.selectedPoint = None\n pass\n if self.selectedPoint == None:\n # self.paintAll()\n pass\n if self.ui.radioButton_2.isChecked():\n # поиск путей\n\n pass\n if self.ui.radioButton_3.isChecked():\n # удаление\n selPoint = pts[0].index()\n self.data['pos'] = np.delete(self.data['pos'], selPoint, axis=0)\n adjToDelete = []\n print(self.data['adj'])\n for j, i in enumerate(self.data['adj']):\n if i[0] == selPoint or i[1] == selPoint:\n adjToDelete.append(j)\n self.data['adj'] = np.delete(self.data['adj'], adjToDelete, axis=0)\n for j, i in enumerate(self.data['adj']):\n for k, kk in enumerate(i):\n print(k, selPoint)\n if kk > selPoint:\n self.data['adj'][j][k] -= 1\n\n self.text.pop(selPoint)\n self.setTexts(self.text)\n print(self.data['pos'])\n print(self.data['adj'])\n print(self.text)\n print(adjToDelete)\n self.setData(text=self.text, adj=self.data[\"adj\"], pxMode=False, size=1, pos=self.data[\"pos\"])\n\n pass\n\n\nwin = MainWindow()\n\ng = Graph(win.ui)\n## Define positions of nodes\npos = np.array([\n [0, 0],\n [15, 0],\n [0, 10],\n [10, 10],\n [5, 5],\n [15, 5],\n [15, 15]\n], dtype=float)\n\n## Define the set of connections in the graph\nadj = np.array([\n [0, 1],\n [1, 3],\n [3, 2],\n [2, 0],\n [1, 5],\n [3, 5],\n [6, 1]\n])\n\n## Define text to show next to each symbol\ntexts = [\"Point %d\" % i for i in range(7)]\n\n## Update the graph\ng.setData(pos=pos, adj=adj, size=1, pxMode=False, text=texts)\n\nwin.ui.plot.setAspectLocked()\nwin.ui.plot.addItem(g)\nwin.ui.plot.setMenuEnabled(enableMenu=False, enableViewBoxMenu='same')\nwin.ui.plot.setBackground('w')\n\n## Start Qt event loop unless running in interactive mode or using pyside.\nif __name__ == '__main__':\n import sys\n\n if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):\n QtGui.QApplication.instance().exec_()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"279644141","text":"from turtle import Turtle\n\nPOSITION = {\n \"left\": -360,\n \"right\": 350,\n \"offset\": 20\n}\nSCREEN_LIMITS = {\n \"top\": 250,\n \"bottom\": -250\n}\nPADDLE_STRETCH = {\n \"width\": 5,\n \"len\": 1\n}\nSPEED = 25\n\n\nclass Paddle(Turtle):\n\n def __init__(self, position):\n super().__init__()\n # self.paddle = Turtle()\n self.penup()\n self.shape(\"square\")\n self.shapesize(stretch_wid=PADDLE_STRETCH[\"width\"], stretch_len=PADDLE_STRETCH[\"len\"])\n self.color(\"white\")\n self.goto(POSITION[position], 0)\n self.y_direction = 20\n\n def move_up(self):\n if self.ycor() < SCREEN_LIMITS[\"top\"]:\n y_cor = self.ycor() + SPEED\n x_cor = self.xcor()\n self.goto(x_cor, y_cor)\n\n def move_down(self):\n if self.ycor() > SCREEN_LIMITS[\"bottom\"]:\n y_cor = self.ycor() - SPEED\n x_cor = self.xcor()\n self.goto(x_cor, y_cor)\n\n def auto_move(self):\n x_cor = self.xcor()\n y_cor = self.ycor() + self.y_direction\n self.goto(x_cor, y_cor)\n\n def reverse(self):\n self.y_direction *= -1\n","sub_path":"day22/pong-game/paddle.py","file_name":"paddle.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"528008865","text":"# Copyright 2018- The Pixie Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# SPDX-License-Identifier: Apache-2.0\n\nimport uuid\n\nfrom src.api.proto.uuidpb import uuid_pb2 as uuidpb\n\n\ndef uuid_pb_from_string(id_str: str) -> uuidpb.UUID:\n u = uuid.UUID(id_str)\n return uuidpb.UUID(\n high_bits=(u.int >> 64),\n low_bits=(u.int & 2**64 - 1),\n )\n\n\ndef uuid_pb_to_string(pb: uuidpb.UUID) -> str:\n i = (pb.high_bits << 64) + pb.low_bits\n u = uuid.UUID(int=i)\n return str(u)\n","sub_path":"src/api/python/pxapi/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"487036444","text":"#!/usr/bin/env python\nimport random\n\n# FIXME can we avoid having globals?\nINPUT_VALUES = []\nOUTPUT_VALUES = []\n\nrelative_base = 0\n\nmove = {1: (0, 1), 4: (1, 0), 2: (0, -1), 3: (-1, 0)} # North # East # South # West\n\nreverse_move = {1: 2, 2: 1, 3: 4, 4: 3}\n\n\ndef next_move(map, position, previous_moves=None):\n moves = list(range(1, 5))\n random.shuffle(moves)\n for move in moves:\n new_pos = new_position(position, move)\n if new_pos not in map:\n # Try to move somewhere we haven't gone before\n return move\n else:\n if previous_moves:\n # backtrack\n return reverse_move[previous_moves.pop()]\n\n\ndef new_position(position, direction):\n x, y = position\n dx, dy = move[direction]\n return (x + dx, y + dy)\n\n\ndef main():\n values = read_input()\n robot_position = (0, 0)\n previous_moves = []\n map = {}\n map[robot_position] = 1\n move = next_move(map, robot_position)\n INPUT_VALUES.append(move)\n position = 0\n while position != -1:\n position = do_turn(values, position)\n if OUTPUT_VALUES:\n output = OUTPUT_VALUES.pop()\n new = new_position(robot_position, move)\n if output in (1, 2):\n robot_position = new\n if new not in map:\n previous_moves.append(move)\n if output == 2:\n # How many moves did it take to get here\n # Note that if there were multiple branches that get here,\n # then this might not be the shortest path\n print(\"Length: %s\" % len(previous_moves))\n map[new] = output\n move = next_move(map, robot_position, previous_moves)\n INPUT_VALUES.append(move)\n\n print_map(map)\n\n\nchar = {0: \"█\", 1: \" \", 2: \"X\", None: \"?\"}\n\n\ndef print_map(map):\n max_x = max(x for x, y in map.keys())\n min_x = min(x for x, y in map.keys())\n max_y = max(y for x, y in map.keys())\n min_y = min(y for x, y in map.keys())\n for y in range(max_y, min_y - 1, -1):\n line = \"\".join(char[map.get((x, y))] for x in range(min_x, max_x + 1))\n print(line)\n\n\ndef extend_if_required(values, pos):\n if pos + 1 > len(values):\n values.extend([0] * (pos + 1 - len(values)))\n\n\ndef get_pos(values, mode, position):\n if mode == 1:\n pos = position\n elif mode == 0:\n pos = values[position]\n elif mode == 2:\n pos = relative_base + values[position]\n\n extend_if_required(values, pos)\n return pos\n\n\ndef do_add(values, modes, start_position):\n pos_a = get_pos(values, modes[0], start_position + 1)\n pos_b = get_pos(values, modes[1], start_position + 2)\n pos_destination = get_pos(values, modes[2], start_position + 3)\n\n values[pos_destination] = values[pos_a] + values[pos_b]\n return start_position + 4\n\n\ndef do_multiply(values, modes, start_position):\n pos_a = get_pos(values, modes[0], start_position + 1)\n pos_b = get_pos(values, modes[1], start_position + 2)\n pos_destination = get_pos(values, modes[2], start_position + 3)\n\n values[pos_destination] = values[pos_a] * values[pos_b]\n return start_position + 4\n\n\ndef do_input(values, modes, start_position):\n # should always be in position mode\n assert modes[0] != 1\n pos_destination = get_pos(values, modes[0], start_position + 1)\n\n values[pos_destination] = INPUT_VALUES.pop(0)\n return start_position + 2\n\n\ndef do_output(values, modes, start_position):\n pos_a = get_pos(values, modes[0], start_position + 1)\n\n output = values[pos_a]\n OUTPUT_VALUES.append(output)\n return start_position + 2\n\n\ndef do_jump_if_true(values, modes, start_position):\n pos_a = get_pos(values, modes[0], start_position + 1)\n pos_b = get_pos(values, modes[1], start_position + 2)\n\n if values[pos_a]:\n return values[pos_b]\n else:\n return start_position + 3\n\n\ndef do_jump_if_false(values, modes, start_position):\n pos_a = get_pos(values, modes[0], start_position + 1)\n pos_b = get_pos(values, modes[1], start_position + 2)\n\n if not values[pos_a]:\n return values[pos_b]\n else:\n return start_position + 3\n\n\ndef do_less_than(values, modes, start_position):\n pos_a = get_pos(values, modes[0], start_position + 1)\n pos_b = get_pos(values, modes[1], start_position + 2)\n pos_destination = get_pos(values, modes[2], start_position + 3)\n\n new_value = 1 if values[pos_a] < values[pos_b] else 0\n values[pos_destination] = new_value\n return start_position + 4\n\n\ndef do_equals(values, modes, start_position):\n pos_a = get_pos(values, modes[0], start_position + 1)\n pos_b = get_pos(values, modes[1], start_position + 2)\n pos_destination = get_pos(values, modes[2], start_position + 3)\n\n new_value = 1 if values[pos_a] == values[pos_b] else 0\n values[pos_destination] = new_value\n return start_position + 4\n\n\ndef do_relative_base(values, modes, start_position):\n global relative_base\n pos_a = get_pos(values, modes[0], start_position + 1)\n relative_base += values[pos_a]\n return start_position + 2\n\n\ndef get_modes(instruction):\n zero_padded = \"%05d\" % instruction\n return [int(x) for x in zero_padded[-3::-1]]\n\n\ndef do_turn(values, start_position):\n instruction = values[start_position]\n opcode = instruction % 100\n modes = get_modes(instruction)\n if opcode == 99:\n return -1\n\n if opcode == 1:\n position = do_add(values, modes, start_position)\n elif opcode == 2:\n position = do_multiply(values, modes, start_position)\n elif opcode == 3:\n position = do_input(values, modes, start_position)\n elif opcode == 4:\n position = do_output(values, modes, start_position)\n elif opcode == 5:\n position = do_jump_if_true(values, modes, start_position)\n elif opcode == 6:\n position = do_jump_if_false(values, modes, start_position)\n elif opcode == 7:\n position = do_less_than(values, modes, start_position)\n elif opcode == 8:\n position = do_equals(values, modes, start_position)\n elif opcode == 9:\n position = do_relative_base(values, modes, start_position)\n else:\n raise ValueError(\"Unexpected opcode: %s\", opcode)\n\n return position\n\n\ndef read_input():\n with open(\"day15.txt\") as f:\n return [int(x) for x in f.read().split(\",\")]\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"day15.py","file_name":"day15.py","file_ext":"py","file_size_in_byte":6418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"467921046","text":"# -*- coding: utf-8 -*-\n'''\n :codeauthor: Mike Place \n'''\n\n# Import python libraries\nfrom __future__ import absolute_import\nimport os\nimport shutil\n\n# Import Salt testing libraries\nfrom tests.support.unit import TestCase, skipIf\nfrom tests.support.mock import NO_MOCK, NO_MOCK_REASON\nfrom salt.utils.cache import context_cache\n\n# Import Salt libraries\nimport salt.payload\nimport salt.utils\n\n__context__ = {'a': 'b'}\n__opts__ = {'cachedir': '/tmp'}\n\n\n@skipIf(NO_MOCK, NO_MOCK_REASON)\nclass ContextCacheTest(TestCase):\n '''\n Test case for salt.utils.cache.ContextCache\n '''\n def setUp(self):\n '''\n Clear the cache before every test\n '''\n context_dir = os.path.join(__opts__['cachedir'], 'context')\n if os.path.isdir(context_dir):\n shutil.rmtree(context_dir)\n\n def test_set_cache(self):\n '''\n Tests to ensure the cache is written correctly\n '''\n @context_cache\n def _test_set_cache():\n '''\n This will inherit globals from the test module itself.\n Normally these are injected by the salt loader [salt.loader]\n '''\n pass\n\n _test_set_cache()\n\n target_cache_file = os.path.join(__opts__['cachedir'], 'context', '{0}.p'.format(__name__))\n self.assertTrue(os.path.isfile(target_cache_file), 'Context cache did not write cache file')\n\n # Test manual de-serialize\n with salt.utils.fopen(target_cache_file, 'rb') as fp_:\n target_cache_data = salt.payload.Serial(__opts__).load(fp_)\n self.assertDictEqual(__context__, target_cache_data)\n\n # Test cache de-serialize\n cc = salt.utils.cache.ContextCache(__opts__, __name__)\n retrieved_cache = cc.get_cache_context()\n self.assertDictEqual(retrieved_cache, __context__)\n\n def test_refill_cache(self):\n '''\n Tests to ensure that the context cache can rehydrate a wrapped function\n '''\n # First populate the cache\n @context_cache\n def _test_set_cache():\n pass\n _test_set_cache()\n\n # Then try to rehydate a func\n @context_cache\n def _test_refill_cache(comparison_context):\n self.assertEqual(__context__, comparison_context)\n\n global __context__\n __context__ = {}\n _test_refill_cache({'a': 'b'}) # Compare to the context before it was emptied\n","sub_path":"tests/unit/utils/test_context.py","file_name":"test_context.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"213778123","text":"import socket\nimport os\nfrom _thread import *\nimport traceback\n\n\nclass ConnectedClient:\n def __init__(self, clientSocket, clientIP, clientPort):\n self.clientSocket = clientSocket\n self.clientIP = clientIP\n self.clientPort = clientPort\n\n def setPublicKey(self, publicKey):\n self.publicKey = publicKey\n\n\nregisteredClientsList = []\n\n\ndef multi_threaded_client(client):\n try:\n connection = client.clientSocket\n while True:\n data = connection.recv(2048)\n recievedClientMessage = data.decode('utf-8')\n response = processMessage(client, recievedClientMessage)\n if not data:\n break\n connection.sendall(str.encode(response))\n connection.close()\n except Exception:\n print(traceback.format_exc())\n\n\ndef processMessage(client, message):\n if message.find(\"REGISTER\") != -1:\n method, clientid, clientpubkey = str(message).split(\"#\", 3)\n print(\"[REQUEST]REGISTER - from Client with ID=\" +\n str(clientid))\n\n isInList = False\n for i in registeredClientsList:\n if i.clientPort == clientid:\n isInList = True\n client.setPublicKey(clientpubkey)\n break\n\n if isInList == False:\n client.clientPort = clientid\n client.setPublicKey(clientpubkey)\n registeredClientsList.append(client)\n\n for i in registeredClientsList:\n print(str(i.clientPort) + \" \" + str(i.publicKey)+\"\\n\")\n return \"Succesfully registered to KeyServer\"\n\n elif message.find(\"GETPUBKEY\") != -1:\n method, clientid = str(message).split(\"#\", 2)\n print(\"[REQUEST]Get public key - from Client with ID=\" +\n str(client.clientPort))\n\n isInList = False\n for i in registeredClientsList:\n if str(i.clientPort) == clientid:\n isInList = True\n return \"POSTPUBKEY#\"+str(i.publicKey)+\"#\"+str(i.clientPort)\n\n if isInList == False:\n return \"POSTPUBKEY#\"+\"NOTFOUND#\"+\"NOTEXISTS\"\n\n\ndef main():\n ServerSideSocket = socket.socket()\n host = '127.0.0.1'\n port = 2004\n ThreadCount = 0\n try:\n ServerSideSocket.bind((host, port))\n except socket.error as e:\n print(str(e))\n print('Socket is listening..')\n ServerSideSocket.listen(5)\n\n while True:\n Client, address = ServerSideSocket.accept()\n joinedClient = ConnectedClient(Client, address[0], address[1])\n print('Connected to: ' + str(joinedClient.clientIP) +\n ':' + str(joinedClient.clientPort))\n print('Becsatlakozott', str(Client.getsockname()[\n 1]) + \" clientport= \"+str(joinedClient.clientPort) + \" adress= \"+str(address))\n\n start_new_thread(multi_threaded_client, (joinedClient, ))\n ThreadCount += 1\n print('Thread Number: ' + str(ThreadCount))\n ServerSideSocket.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"lab2/keyserver.py","file_name":"keyserver.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"461604274","text":"#!/usr/bin/python\n\nimport subprocess\nimport globalVars\n\ndef ecoforestSalon():\n try:\n command = \"/home/nfs/telegram/tgScripts/ecoforest.sh\"\n subprocess.Popen(command, shell=True)\n globalVars.toFile(globalVars.sendFile, \"Mensaje enceder ecoforest salón enviado\")\n except Exception as e:\n toLogFile('Error ecoforest salón: ' + str(e))\n return False\n\n\ndef getEnchufeWatios():\n try:\n return 0\n except Exception as e:\n toLogFile('Error getEnchufeWatios: ' + str(e))\n return -1\n\nif __name__ == \"__main__\":\n ecoforestSalon()\n","sub_path":"raspiWeb/backoffice/tgScripts/ecoforest.py","file_name":"ecoforest.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"483663733","text":"from models.inoutdata import register,inout,orders\nimport matplotlib.pyplot as plt \nx=[]\ny=[]\nfor item in orders:\n #print(item.date,item.count)\n x.append(item.date)\n y.append(item.count)\nprint(x,y)\n# plt.plot(x, y)\n# plt.title(\"用户注册趋势图\")\n# plt.xlabel('点数')\n# plt.ylabel('概率')\n# plt.rcParams['font.sans-serif']=['SimHei']\n# plt.rcParams['axes.unicode_minus'] =False\n\n# plt.show()","sub_path":"zhenghaoban.py","file_name":"zhenghaoban.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"329707598","text":"from __future__ import division\n\n# Style index functions\n\ndef norm_diff(data, band1, band2, product_cfg=None):\n # Calculate a normalised difference index.\n\n if product_cfg:\n b1=product_cfg.band_idx.band(band1)\n b2=product_cfg.band_idx.band(band2)\n else:\n b1 = band1\n b2 = band2\n return (data[b1] - data[b2]) / (data[b1] + data[b2])\n\n\ndef constant(data, band, const, product_cfg=None):\n # Covert an xarray for a flat constant.\n # Useful for displaying mask extents as a flat colour and debugging.\n # params is assumed to be a tuple containing a constant value and a band name/alias.\n\n if product_cfg:\n b = product_cfg.band_idx.band(band)\n else:\n b = band\n return data[b] * 0.0 + const\n\n\ndef single_band(data, band, product_cfg=None):\n # Use the raw value of a band directly as the index function.\n\n if product_cfg:\n b = product_cfg.band_idx.band(band)\n else:\n b = band\n return data[b]\n\n\ndef band_quotient(data, band1, band2, product_cfg=None):\n if product_cfg:\n b1=product_cfg.band_idx.band(band1)\n b2=product_cfg.band_idx.band(band2)\n else:\n b1 = band1\n b2 = band2\n return data[b1] / data[b2]\n\n\ndef band_quotient_sum(data, band1a, band1b, band2a, band2b, product_cfg=None):\n return band_quotient(data, band1a, band1b, product_cfg) + band_quotient(data, band2a, band2b, product_cfg)\n\n","sub_path":"datacube_wms/band_utils.py","file_name":"band_utils.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"522699175","text":"from django.test import SimpleTestCase\nfrom django.urls import reverse, resolve\n\nfrom authors.views import (\n AuthorDetailView,\n AuthorDeleteView,\n AuthorListView,\n AuthorCreateView,\n AuthorUpdateView\n)\n\n\nclass AuthorsUrlsSimpleTestCase(SimpleTestCase):\n\n def test_author_list_resolves(self):\n url = reverse('author_list')\n self.assertEqual(resolve(url).func.view_class, AuthorListView)\n\n def test_author_resolves(self):\n url = reverse('author', kwargs={'pk': 1})\n self.assertEqual(resolve(url).func.view_class, AuthorDetailView)\n\n def test_author_create_resolves(self):\n url = reverse('author_create')\n self.assertEqual(resolve(url).func.view_class, AuthorCreateView)\n\n def test_author_update_resolves(self):\n url = reverse('author_update', kwargs={'pk': 1})\n self.assertEqual(resolve(url).func.view_class, AuthorUpdateView)\n\n def test_author_delete_resolves(self):\n url = reverse('author_delete', kwargs={'pk': 1})\n self.assertEqual(resolve(url).func.view_class, AuthorDeleteView)\n","sub_path":"homework_09/book_lib/authors/tests/test_urls.py","file_name":"test_urls.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"390311167","text":"from __future__ import print_function\nimport numpy as np\nimport sys\nimport tensorflow as tf\n#try:\n# import special_grads\n#except KeyError as e:\n# print('WARN: Cannot define MaxPoolGrad, likely already defined for this version of tensorflow: %s' % e, file=sys.stderr)\n\nfrom tensorflow.python.platform import flags\nfrom utils import conv_block, fc, max_pool, lrn, dropout\nfrom utils import xent, kd\n\nFLAGS = flags.FLAGS\n\nclass MASF:\n def __init__(self, num_classes, batch_size=128):\n \"\"\" Call construct_model_*() after initializing MASF\"\"\"\n self.forward = self.forward_fc\n self.construct_weights = self.construct_fc_weights\n self.loss_func = self.softmax\n #self.loss_func = self.additive_angular_margin_softmax\n self.num_classes = num_classes\n self.KEEP_PROB = 1.0\n self.batch_size = batch_size\n\n\n def construct_model_train(self, prefix='metatrain_'):\n # a: meta-train for inner update, b: meta-test for meta loss\n self.input = tf.placeholder(tf.float32)\n self.label = tf.placeholder(tf.float32)\n\n meta_sample_num = (FLAGS.meta_batch_size /2) * 2\n\n self.inner_lr = FLAGS.inner_lr\n self.outer_lr = FLAGS.outer_lr\n self.clip_value = FLAGS.gradients_clip_value\n self.KEEP_PROB = tf.placeholder(tf.float32)\n\n with tf.variable_scope('model', reuse=None) as training_scope:\n if 'weights' in dir(self):\n print('weights already defined')\n training_scope.reuse_variables()\n weights = self.weights\n else:\n self.weights = weights = self.construct_weights()\n\n def task_metalearn(inp, reuse=True):\n # Function to perform meta learning update \"\"\"\n #inputa0, labela0, inputa1, labela1, inputb, labelb = inp\n input, label = inp\n\n # Obtaining the conventional task loss on meta-train\n _, output = self.forward(input, weights, reuse=reuse, is_training=True)\n output, loss = self.loss_func(output, label, is_training=True, reuse_variables=tf.AUTO_REUSE)\n accuracy = tf.contrib.metrics.accuracy(tf.argmax(tf.nn.softmax(output), 1), tf.argmax(label, 1)) #this accuracy already gathers batch size\n\n task_output = [loss, accuracy]\n return task_output\n\n self.global_step = tf.Variable(0, trainable=False)\n\n input_tensors = (self.input, self.label)\n result = task_metalearn(inp=input_tensors)\n self.raw_loss, accuracy = result\n\n ## Performance & Optimization\n if 'train' in prefix:\n self.loss = avg_loss = tf.reduce_mean(self.raw_loss)\n self.task_train_op = tf.train.AdamOptimizer(learning_rate=self.outer_lr).minimize(self.loss, global_step=self.global_step)\n\n self.accuracy = accuracy * 100.\n\n ## Summaries\n tf.summary.scalar(prefix+'loss', self.loss)\n tf.summary.scalar(prefix+'accuracy', self.accuracy)\n\n\n def construct_model_predict(self, prefix='predict'):\n\n self.test_input = tf.placeholder(tf.float32)\n\n with tf.variable_scope('model') as testing_scope:\n self.weights = weights = self.construct_fc_weights()\n testing_scope.reuse_variables()\n\n embeddings, _= self.forward(self.test_input, weights)\n \n self.embeddings = embeddings\n\n\n def construct_fc_weights(self):\n\n weights = {}\n fc_initializer = tf.contrib.layers.xavier_initializer(dtype=tf.float32)\n\n with tf.variable_scope('dense1') as scope:\n weights['dense1_weights'] = tf.get_variable('weights', shape=[512, 512], \n initializer=fc_initializer)\n weights['dense1_biases'] = tf.get_variable('biases', [512],\n initializer=fc_initializer)\n\n with tf.variable_scope('dense2') as scope:\n weights['dense2_weights'] = tf.get_variable('weights', shape=[512, 512],\n initializer=fc_initializer)\n weights['dense2_biases'] = tf.get_variable('biases', [512],\n initializer=fc_initializer)\n\n with tf.variable_scope('dense3') as scope:\n weights['dense3_weights'] = tf.get_variable('weights', shape=[512, 512],\n initializer=fc_initializer)\n weights['dense3_biases'] = tf.get_variable('biases', [512], \n initializer=fc_initializer)\n\n return weights\n\n\n def forward_fc(self, inp, weights, reuse=False, is_training=False):\n # reuse is for the normalization parameters.\n x = tf.reshape(inp, [-1,512])\n dense1 = fc(x, weights['dense1_weights'], weights['dense1_biases'], activation=None)\n bn1 = tf.layers.batch_normalization(dense1, momentum=0.99, training=is_training, \n name='bn1', reuse=tf.AUTO_REUSE)\n relu1 = tf.nn.relu(bn1)\n dropout1 = dropout(relu1, self.KEEP_PROB)\n\n dense2 = fc(dropout1, weights['dense2_weights'], weights['dense2_biases'], activation=None)\n bn2 = tf.layers.batch_normalization(dense2, momentum=0.99, training=is_training, \n name='bn2', reuse=tf.AUTO_REUSE)\n relu2 = tf.nn.relu(bn2)\n dropout2 = dropout(relu2, self.KEEP_PROB)\n\n dense3 = fc(dropout2, weights['dense3_weights'], weights['dense3_biases'], activation=None)\n bn3 = tf.layers.batch_normalization(dense3, momentum=0.99, training=is_training, \n name='bn3', reuse=tf.AUTO_REUSE)\n relu3 = tf.nn.relu(bn3)\n if self.loss_func == self.additive_angular_margin_softmax:\n return dense2, bn3 # last_layer_linear for angular softmax\n elif self.loss_func == self.softmax:\n return dense2, relu3\n\n\n def additive_angular_margin_softmax(self, features, labels, is_training=None, reuse_variables=None, name=\"softmax\"):\n \"\"\"Additive angular margin softmax (ArcFace)\n link: https://arxiv.org/abs/1801.07698\n Annealing scheme is also added.\n \n Args:\n features: A tensor with shape [batch, dim].\n labels: A tensor with shape [batch].\n num_outputs: The number of classes.\n params: params.weight_l2_regularizer: the L2 regularization.\n arcsoftmax_m: the angular margin (0.4-0.55)\n params.arcsoftmax_norm, params.arcsoftmax_s: If arcsoftmax_norm is True, arcsoftmax_s must be specified.\n This means we normalize the length of the features, and do the\n scaling on the cosine similarity.\n is_training: Not used in this case.\n reuse_variables: Reuse variables.\n name:\n \"\"\"\n #assert len(self.shape_list(features)) == len(self.shape_list(labels)) + 1\n num_outputs = self.num_classes\n # Convert the parameters to float\n arcsoftmax_lambda_min = float(0)\n arcsoftmax_lambda_base = float(1000)\n arcsoftmax_lambda_gamma = float(0.00001)\n arcsoftmax_lambda_power = float(5)\n arcsoftmax_m = float(0.00)\n \n tf.logging.info(\"Additive angular margin softmax is used.\")\n tf.logging.info(\"The margin in the additive angular margin softmax is %f\" % arcsoftmax_m)\n \n weight_l2_regularizer = 1e-2\n with tf.variable_scope(name, reuse=reuse_variables):\n w = tf.get_variable(\"output/kernel\", [512, num_outputs], dtype=tf.float32,\n initializer=tf.contrib.layers.xavier_initializer(),\n regularizer=tf.contrib.layers.l2_regularizer(weight_l2_regularizer))\n \n w_norm = tf.nn.l2_normalize(w, dim=0)\n logits = tf.matmul(features, w_norm)\n \n ordinal = tf.to_int32(tf.range(self.batch_size))\n labels = tf.to_int32(tf.argmax(labels,1))\n ordinal_labels = tf.stack([ordinal, labels], axis=1)\n sel_logits = tf.gather_nd(logits, ordinal_labels)\n \n # The angle between x and the target w_i.\n eps = 1e-12\n features_norm = tf.maximum(tf.norm(features, axis=1), eps)\n cos_theta_i = tf.div(sel_logits, features_norm)\n cos_theta_i = tf.clip_by_value(cos_theta_i, -1+eps, 1-eps) # for numerical steady\n \n # Since 0 < theta < pi, sin(theta) > 0. sin(theta) = sqrt(1 - cos(theta)^2)\n # cos(theta + m) = cos(theta)cos(m) - sin(theta)sin(m)\n sin_theta_i_sq = 1 - tf.square(cos_theta_i)\n sin_theta_i = tf.sqrt(tf.maximum(sin_theta_i_sq, 1e-12))\n cos_theta_plus_m_i = cos_theta_i * tf.cos(arcsoftmax_m) - sin_theta_i * tf.sin(arcsoftmax_m)\n \n # Since theta \\in [0, pi], theta + m > pi means cos(theta) < cos(pi - m)\n # If theta + m < pi, Phi(theta) = cos(theta + m).\n # If theta + m > pi, Phi(theta) = -cos(theta + m) - 2\n phi_i = tf.where(tf.greater(cos_theta_i, tf.cos(np.pi - arcsoftmax_m)),\n cos_theta_plus_m_i,\n -cos_theta_plus_m_i - 2)\n \n # logits = ||x||(cos(theta + m))\n scaled_logits = tf.multiply(phi_i, features_norm)\n \n logits_arcsoftmax = tf.add(logits,\n tf.scatter_nd(ordinal_labels,\n tf.subtract(scaled_logits, sel_logits),\n tf.shape(logits, out_type=tf.int32)))\n \n arcsoftmax_lambda = tf.maximum(arcsoftmax_lambda_min,\n arcsoftmax_lambda_base * (1.0 + arcsoftmax_lambda_gamma * tf.to_float(\n self.global_step)) ** (-arcsoftmax_lambda_power))\n fa = 1.0 / (1.0 + arcsoftmax_lambda)\n fs = 1.0 - fa\n updated_logits = fs * logits + fa * logits_arcsoftmax\n \n tf.summary.scalar(\"arcsoftmax_m\", arcsoftmax_m)\n tf.summary.scalar(\"arcsoftmax_lambda\", arcsoftmax_lambda)\n loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=updated_logits)\n tf.summary.scalar(\"arcsoftmax_loss\", loss)\n \n return logits, loss\n\n def softmax(self, features, labels, is_training=None, reuse_variables=None, name=\"softmax\"):\n \"\"\"Vanilla softmax loss.\n\n Args:\n features: A tensor with shape [batch, dim].\n labels: A tensor with shape [batch].\n num_outputs: The number of classes.\n params: params.weight_l2_regularizer used for L2 regularization.\n is_training: Not used in this case\n reuse_variables: Share the created variables or not.\n name:\n :return: A scalar tensor which is the loss value.\n \"\"\"\n #assert len(shape_list(features)) == len(shape_list(labels)) + 1\n num_outputs = self.num_classes\n\n weight_l2_regularizer = 1e-2\n labels = tf.to_int32(tf.argmax(labels,1))\n with tf.variable_scope(name, reuse=reuse_variables):\n logits = tf.layers.dense(features,\n num_outputs,\n activation=None,\n kernel_regularizer=tf.contrib.layers.l2_regularizer(weight_l2_regularizer),\n name=\"output\")\n loss = tf.losses.sparse_softmax_cross_entropy(labels, logits)\n\n return logits, loss\n\n","sub_path":"mct/inner/maml_mct.py","file_name":"maml_mct.py","file_ext":"py","file_size_in_byte":11804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"356700140","text":"import logging\nfrom os import getenv\nfrom flask import Flask\nfrom flask_session import Session\nfrom bucket.handler import bucket_handler\nfrom session.handler import session_handler\nfrom werkzeug.middleware.proxy_fix import ProxyFix\n\n\ndef config_logging(debug=False):\n print(f\"Debug is on?: {debug}\")\n if debug:\n logging.basicConfig(level=logging.DEBUG)\n else:\n logging.basicConfig(level=logging.INFO)\n\n\ndef create_app(debug=False):\n app = Flask(__name__)\n # Get settings\n app.config.from_pyfile('settings.py')\n # Register bucket handler\n app.register_blueprint(bucket_handler)\n # configure session\n sess = Session()\n sess.init_app(app)\n app.register_blueprint(session_handler)\n # limit max payload to 50MB\n app.config['MAX_CONTENT_LENGTH']\n config_logging(debug)\n return app\n\n\ndef behind_proxy(app):\n # App is behind one proxy that sets the -For and -Host headers.\n app = ProxyFix(app, x_for=1, x_host=1)\n\n\nif __name__ == '__main__':\n debug = True if getenv('DEBUG', '').lower() == \"true\" else False\n app = create_app(debug)\n if getenv(\"PROXIED\", \"true\").lower() == \"true\":\n behind_proxy(app)\n\n app.run(debug=debug, host='0.0.0.0')\n","sub_path":"src/app/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"387174894","text":"'''\nrequests.session 来保持状态,自动管理过程中产生的cookie\n下次请求时自动带上上一次的cookie\n'''\nimport requests\n\n# requests.get()\ns = requests.session()\n# 通过dict_from_cookiejar 将cookies转成字典\nprint(\"登录前的cookies:\",requests.utils.dict_from_cookiejar(s.cookies))\n# 登录接口\nurl = \"https://www.bagevent.com/user/login\"\ncs = {\n\"access_type\": \"1\",\n\"loginType\": \"1\",\n\"emailLoginWay\": \"0\",\n\"account\": \"2780487875@qq.com\",\n\"password\": \"qq2780487875\",\n\"remindmeBox\": \"on\",\n\"remindme\": \"1\"\n}\nr = s.post(url,data=cs)\n# print(r.text)\nprint(\"登录后的cookies:\",requests.utils.dict_from_cookiejar(s.cookies))\n\n\n# dashboard接口\ns.get(\"https://www.bagevent.com/account/dashboard\")\n# print(r.text)\nassert \"百格活动 - 账户总览\" in r.text\n\n\n# 退出登录的接口\nurl = \"https://www.bagevent.com/user/login_out\"\nr = s.get(url)\n# print(r.text)\n\nprint(\"退出登陆后的cookies:\",requests.utils.dict_from_cookiejar(s.cookies))\n","sub_path":"day01/05.自动管理Cookie.py","file_name":"05.自动管理Cookie.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"482784997","text":"# -*- coding: utf-8 -*-\nimport sys, os, importlib, random, json\nimport PARAMETERS\nfrom helpers_cntk import *\nfrom copy import deepcopy\n\nlocals().update(importlib.import_module(\"PARAMETERS\").__dict__)\n\n####################################\n# Parameters\n####################################\n\n\n\n#################################### Funcoes ####################################\n\n# passar o num da imagem. No diretorio as imagens devem estar numeradas em sequencia\ndef recursiveCallImage(strImageIndex):\n\n imgPath = recognizeDir+strImageIndex+\".jpg\"\n # Directory to save recognized images\n outDir = recognizeDir\n\n #choose which classifier to use\n classifier = 'svm'\n svm_experimentName = 'exp1'\n\n # no need to change these parameters\n boAddSelectiveSearchROIs = True\n boAddGridROIs = True\n boFilterROIs = True\n boUseNonMaximaSurpression = True\n\n\n ####################################\n # Main\n ####################################\n random.seed(0)\n\n # load cntk model\n print(\"Loading DNN..\")\n tstart = datetime.datetime.now()\n model_path = os.path.join(modelDir, \"frcn_\" + classifier + \".model\")\n model = load_model(model_path)\n print(\"Time loading DNN [ms]: \" + str((datetime.datetime.now() - tstart).total_seconds() * 1000))\n\n # load trained svm\n if classifier == \"svm\":\n print(\"Loading svm weights..\")\n tstart = datetime.datetime.now()\n svmWeights, svmBias, svmFeatScale = loadSvm(trainedSvmDir, svm_experimentName)\n print(\"Time loading svm [ms]: \" + str((datetime.datetime.now() - tstart).total_seconds() * 1000))\n else:\n svmWeights, svmBias, svmFeatScale = (None, None, None)\n\n # compute ROIs\n tstart = datetime.datetime.now()\n imgOrig = imread(imgPath)\n currRois = computeRois(imgOrig, boAddSelectiveSearchROIs, boAddGridROIs, boFilterROIs, ss_kvals, ss_minSize,\n ss_max_merging_iterations, ss_nmsThreshold,\n roi_minDimRel, roi_maxDimRel, roi_maxImgDim, roi_maxAspectRatio, roi_minNrPixelsRel,\n roi_maxNrPixelsRel, grid_nrScales, grid_aspectRatios, grid_downscaleRatioPerIteration)\n currRois = currRois[:cntk_nrRois] # only keep first cntk_nrRois rois\n print(\"Time roi computation [ms]: \" + str((datetime.datetime.now() - tstart).total_seconds() * 1000))\n\n # prepare DNN inputs\n tstart = datetime.datetime.now()\n imgPadded = imresizeAndPad(imgOrig, cntk_padWidth, cntk_padHeight)\n _, _, roisCntk = getCntkInputs(imgPath, currRois, None, train_posOverlapThres, nrClasses, cntk_nrRois, cntk_padWidth, cntk_padHeight)\n arguments = {\n model.arguments[0]: [np.ascontiguousarray(np.array(imgPadded, dtype=np.float32).transpose(2, 0, 1))], # convert to CNTK's HWC format\n model.arguments[1]: [np.array(roisCntk, np.float32)]\n }\n print(\"Time cnkt input generation [ms]: \" + str((datetime.datetime.now() - tstart).total_seconds() * 1000))\n\n # run DNN model\n print(\"Running model..\")\n tstart = datetime.datetime.now()\n dnnOutputs = model.eval(arguments)[0][0]\n dnnOutputs = dnnOutputs[:len(currRois)] # remove the zero-padded rois\n print(\"Time running model [ms]: \" + str((datetime.datetime.now() - tstart).total_seconds() * 1000))\n\n # score all ROIs\n tstart = datetime.datetime.now()\n labels, scores = scoreRois(classifier, dnnOutputs, svmWeights, svmBias, svmFeatScale, len(classes),\n decisionThreshold = vis_decisionThresholds[classifier])\n print(\"Time making prediction [ms]: \" + str((datetime.datetime.now() - tstart).total_seconds() * 1000))\n\n # perform non-maxima surpression\n tstart = datetime.datetime.now()\n nmsKeepIndices = []\n if boUseNonMaximaSurpression:\n nmsKeepIndices = applyNonMaximaSuppression(nmsThreshold, labels, scores, currRois)\n print(\"Non-maxima surpression kept {:4} of {:4} rois (nmsThreshold={})\".format(\n len(nmsKeepIndices), len(labels), nmsThreshold))\n print(\"Time non-maxima surpression [ms]: \" + str((datetime.datetime.now() - tstart).total_seconds() * 1000))\n\n # visualize results\n boPrintLabel = True;\n boPrintScore = True;\n decisionThreshold = 0.0;\n imgDebug = visualizeResults(imgPath, labels, scores, currRois, classes, boPrintLabel, boPrintScore, nmsKeepIndices,\n boDrawNegativeRois=False, boDrawNmsRejectedRois=False)\n\n \n imshow(imgDebug, waitDuration=1, maxDim=800)\n imwrite(imgDebug, outDir +imageNameRecognizedPrefix +os.path.basename(imgPath))\n\n### Out Of the Functio\n\nfor x in range(1,7):\n recursiveCallImage(str(x))\n\nprint(\"FIM DO PROCESSAMENTO\")\n","sub_path":"cntk_api/pj_Recursively_6_scoreImage.py","file_name":"pj_Recursively_6_scoreImage.py","file_ext":"py","file_size_in_byte":4689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"645103468","text":"import argparse\n\nfrom loader import MoleculeDataset_aug\nfrom torch_geometric.data import DataLoader\nfrom torch_geometric.nn.inits import uniform\nfrom torch_geometric.nn import global_mean_pool\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom tqdm import tqdm\nimport numpy as np\n\nfrom model import GNN\nfrom sklearn.metrics import roc_auc_score\n\nfrom splitters import scaffold_split, random_split, random_scaffold_split\nimport pandas as pd\n\nfrom tensorboardX import SummaryWriter\n\nfrom copy import deepcopy\n\n\ndef cycle_index(num, shift):\n arr = torch.arange(num) + shift\n arr[-shift:] = torch.arange(shift)\n return arr\n\nclass Discriminator(nn.Module):\n def __init__(self, hidden_dim):\n super(Discriminator, self).__init__()\n self.weight = nn.Parameter(torch.Tensor(hidden_dim, hidden_dim))\n self.reset_parameters()\n\n def reset_parameters(self):\n size = self.weight.size(0)\n uniform(size, self.weight)\n\n def forward(self, x, summary):\n h = torch.matmul(summary, self.weight)\n return torch.sum(x*h, dim = 1)\n\n\nclass graphcl(nn.Module):\n\n def __init__(self, gnn):\n super(graphcl, self).__init__()\n self.gnn = gnn\n self.pool = global_mean_pool\n self.projection_head = nn.Sequential(nn.Linear(300, 300), nn.ReLU(inplace=True), nn.Linear(300, 300))\n\n def forward_cl(self, x, edge_index, edge_attr, batch):\n x = self.gnn(x, edge_index, edge_attr)\n x = self.pool(x, batch)\n x = self.projection_head(x)\n return x\n\n def loss_cl(self, x1, x2):\n T = 0.1\n batch_size, _ = x1.size()\n x1_abs = x1.norm(dim=1)\n x2_abs = x2.norm(dim=1)\n\n sim_matrix = torch.einsum('ik,jk->ij', x1, x2) / torch.einsum('i,j->ij', x1_abs, x2_abs)\n sim_matrix = torch.exp(sim_matrix / T)\n pos_sim = sim_matrix[range(batch_size), range(batch_size)]\n loss = pos_sim / (sim_matrix.sum(dim=1) - pos_sim)\n loss = - torch.log(loss).mean()\n return loss\n\n\ndef train(args, model, device, dataset, optimizer):\n\n dataset.aug = \"none\"\n dataset1 = dataset.shuffle()\n dataset2 = deepcopy(dataset1)\n dataset1.aug, dataset1.aug_ratio = args.aug1, args.aug_ratio1\n dataset2.aug, dataset2.aug_ratio = args.aug2, args.aug_ratio2\n\n loader1 = DataLoader(dataset1, batch_size=args.batch_size, num_workers = args.num_workers, shuffle=False)\n loader2 = DataLoader(dataset2, batch_size=args.batch_size, num_workers = args.num_workers, shuffle=False)\n\n model.train()\n\n train_acc_accum = 0\n train_loss_accum = 0\n\n for step, batch in enumerate(tqdm(zip(loader1, loader2), desc=\"Iteration\")):\n batch1, batch2 = batch\n batch1 = batch1.to(device)\n batch2 = batch2.to(device)\n\n optimizer.zero_grad()\n\n x1 = model.forward_cl(batch1.x, batch1.edge_index, batch1.edge_attr, batch1.batch)\n x2 = model.forward_cl(batch2.x, batch2.edge_index, batch2.edge_attr, batch2.batch)\n loss = model.loss_cl(x1, x2)\n\n loss.backward()\n optimizer.step()\n\n train_loss_accum += float(loss.detach().cpu().item())\n # acc = (torch.sum(positive_score > 0) + torch.sum(negative_score < 0)).to(torch.float32)/float(2*len(positive_score))\n acc = torch.tensor(0)\n train_acc_accum += float(acc.detach().cpu().item())\n\n return train_acc_accum/(step+1), train_loss_accum/(step+1)\n\n\ndef main():\n # Training settings\n parser = argparse.ArgumentParser(description='PyTorch implementation of pre-training of graph neural networks')\n parser.add_argument('--device', type=int, default=0,\n help='which gpu to use if any (default: 0)')\n parser.add_argument('--batch_size', type=int, default=256,\n help='input batch size for training (default: 256)')\n parser.add_argument('--epochs', type=int, default=100,\n help='number of epochs to train (default: 100)')\n parser.add_argument('--lr', type=float, default=0.001,\n help='learning rate (default: 0.001)')\n parser.add_argument('--decay', type=float, default=0,\n help='weight decay (default: 0)')\n parser.add_argument('--num_layer', type=int, default=5,\n help='number of GNN message passing layers (default: 5).')\n parser.add_argument('--emb_dim', type=int, default=300,\n help='embedding dimensions (default: 300)')\n parser.add_argument('--dropout_ratio', type=float, default=0,\n help='dropout ratio (default: 0)')\n parser.add_argument('--JK', type=str, default=\"last\",\n help='how the node features across layers are combined. last, sum, max or concat')\n parser.add_argument('--dataset', type=str, default = 'zinc_standard_agent', help='root directory of dataset. For now, only classification.')\n parser.add_argument('--output_model_file', type = str, default = '', help='filename to output the pre-trained model')\n parser.add_argument('--gnn_type', type=str, default=\"gin\")\n parser.add_argument('--seed', type=int, default=0, help = \"Seed for splitting dataset.\")\n parser.add_argument('--num_workers', type=int, default = 8, help='number of workers for dataset loading')\n parser.add_argument('--aug1', type=str, default = 'none')\n parser.add_argument('--aug_ratio1', type=float, default = 0.2)\n parser.add_argument('--aug2', type=str, default = 'none')\n parser.add_argument('--aug_ratio2', type=float, default = 0.2)\n args = parser.parse_args()\n\n\n torch.manual_seed(0)\n np.random.seed(0)\n device = torch.device(\"cuda:\" + str(args.device)) if torch.cuda.is_available() else torch.device(\"cpu\")\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(0)\n\n\n #set up dataset\n dataset = MoleculeDataset_aug(\"dataset/\" + args.dataset, dataset=args.dataset)\n print(dataset)\n\n #set up model\n gnn = GNN(args.num_layer, args.emb_dim, JK = args.JK, drop_ratio = args.dropout_ratio, gnn_type = args.gnn_type)\n\n model = graphcl(gnn)\n \n model.to(device)\n\n #set up optimizer\n optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.decay)\n print(optimizer)\n\n for epoch in range(1, args.epochs):\n print(\"====epoch \" + str(epoch))\n \n train_acc, train_loss = train(args, model, device, dataset, optimizer)\n\n print(train_acc)\n print(train_loss)\n\n if epoch % 20 == 0:\n torch.save(gnn.state_dict(), \"./models_graphcl/graphcl_\" + str(epoch) + \".pth\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"transferLearning_MoleculeNet_PPI/chem/pretrain_graphcl.py","file_name":"pretrain_graphcl.py","file_ext":"py","file_size_in_byte":6678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"187128573","text":"from django.shortcuts import reverse, render\nfrom django.views.generic import View\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\nfrom .utils import (\n ObjectListMixin,\n ObjectDetailMixin,\n ObjectCreateMixin,\n ObjectUpdateMixin,\n ObjectDeleteMixin,\n BasicLoginRequiredMixin,\n)\nfrom .models import Group, Student\nfrom .forms import (\n GroupForm,\n StudentForm,\n GroupUpdateForm,\n StudentUpdateForm,\n)\n\n\nclass GroupCreateView(BasicLoginRequiredMixin, ObjectCreateMixin, View):\n form_model = GroupForm\n template = 'students/group_create.html'\n\n\nclass GroupListView(ObjectListMixin, View):\n model = Group\n objects_per_page = 4\n template = 'students/group_list.html'\n\n\nclass GroupDetailView(ObjectDetailMixin, View):\n model = Group\n template = 'students/group_detail.html'\n\n\nclass GroupUpdateView(BasicLoginRequiredMixin, ObjectUpdateMixin, View):\n model = Group\n form_model = GroupUpdateForm\n template = 'students/group_update.html'\n\n\nclass GroupDeleteView(BasicLoginRequiredMixin, ObjectDeleteMixin, View):\n model = Group\n template = 'students/group_delete.html'\n\n\nclass StudentDetailView(BasicLoginRequiredMixin, ObjectDetailMixin, View):\n model = Student\n template = 'students/student_detail.html'\n\n\nclass StudentCreateView(BasicLoginRequiredMixin, ObjectCreateMixin, View):\n form_model = StudentForm\n template = 'students/student_create.html'\n\n def get(self, request):\n '''\n changes behavior in order to\n take \"from\" get parameter which represents refer gorup\n for pretty form render\n '''\n init_group_id = request.GET.get('from', None)\n init_group = None\n\n if init_group_id:\n queryset = Group.objects.filter(id=init_group_id)\n if queryset.exists():\n init_group = queryset[0]\n\n form = self.form_model()\n form.fields['group_id'].initial = init_group # set 'selected' to refer group\n context = {\n 'form': form,\n }\n return render(request, self.template, context=context)\n\n\nclass StudentUpdateView(BasicLoginRequiredMixin, ObjectUpdateMixin, View):\n model = Student\n form_model = StudentUpdateForm\n template = 'students/student_update.html'\n\n\nclass StudentDeleteView(BasicLoginRequiredMixin, ObjectDeleteMixin, View):\n model = Student\n template = 'students/student_delete.html'\n","sub_path":"students/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"583133863","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nimport os\r\n\r\nroot = Tk()\r\n\r\n\r\ndef run():\r\n os.system('py _blackbosomsr.py')\r\n\r\n\r\ndef run1():\r\n os.system('py shatteredheart.py')\r\n\r\n\r\ndef run2():\r\n os.system('py _tarnishedhelllight.py')\r\n\r\n\r\ndef run3():\r\n os.system('py gigasgreatsword.py')\r\n\r\n\r\ndef run4():\r\n os.system('py ColossusGuillotine.py')\r\n\r\n\r\nicon = PhotoImage(file='_blackbosomsr-icon.png')\r\nlbl_image = Label(root, image=icon)\r\nlbl_image.grid(column=0, row=1)\r\n\r\nbutton = ttk.Button(text='Blackbosom Grim Reaper', command=run)\r\nbutton.grid(column=1, row=1)\r\n\r\nicon1 = PhotoImage(file='ShatteredHeart-icon.png')\r\nlbl_image1 = Label(root, image=icon1)\r\nlbl_image1.grid(column=0, row=2)\r\n\r\nbutton = ttk.Button(text='Shattered Heart', command=run1)\r\nbutton.grid(column=1, row=2)\r\n\r\nicon2 = PhotoImage(file='TarnishedHellLight-icon.png')\r\nlbl_image2 = Label(root, image=icon2)\r\nlbl_image2.grid(column=0, row=3)\r\n\r\nbutton = ttk.Button(text='Tarnished Hell Light', command=run2)\r\nbutton.grid(column=1, row=3)\r\n\r\nicon3 = PhotoImage(file='Gigagreatsword-icon.png')\r\nlbl_image3 = Label(root, image=icon3)\r\nlbl_image3.grid(column=0, row=4)\r\n\r\nbutton = ttk.Button(text='Gigas Greatsword', command=run3)\r\nbutton.grid(column=1, row=4)\r\n\r\nicon4 = PhotoImage(file='ColossusGuillotine-icon.png')\r\nlbl_image4 = Label(root, image=icon4)\r\nlbl_image4.grid(column=0, row=5)\r\n\r\nbutton = ttk.Button(text='Colossus Guillotine', command=run4)\r\nbutton.grid(column=1, row=5)\r\n\r\n\r\nroot.mainloop()\r\n","sub_path":"FF14AlphaProject/level1DRKweapons.py","file_name":"level1DRKweapons.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"29885334","text":"import time\nfrom threading import Thread\nimport scramble\nfrom util.input import getch\nfrom history.history import History\nfrom cube import playcube\n\n\nclass Timer(Thread):\n\n def run(self):\n while True:\n now = (time.time() - self.begin)\n if not self.isrunning:\n break\n print('{:.2f}'.format(now), end='\\r')\n time.sleep(0.01)\n\n def go(self, mode):\n self.isrunning = True\n self.begin = time.time()\n self.start()\n\n def stop(self):\n self.end = time.time()\n self.isrunning = False\n print('\\r{:.2f}'.format(self.gettime()))\n\n def gettime(self):\n return self.end - self.begin\n\n\nclass Timermode():\n\n def __init__(self):\n self.timer = None\n self.mode = '3x3'\n self.history = History()\n\n def nextsolve(self):\n print(self.history)\n self.scramble = scramble.scramble()\n playcube.Cubemode(self.scramble, printall=True)\n print(\"\\n\" + \"Scramble: \" + ' '.join(self.scramble) + \"\\n\")\n if self.timer:\n print('{:.2f}'.format(self.timer.gettime()), end='\\r')\n else:\n print('0.00', end='\\r')\n self.lasttimer = self.timer\n self.timer = Timer()\n time.sleep(0.5)\n\n def run(self):\n while True:\n self.nextsolve()\n if self.configmode() == -1:\n self.history.close()\n break\n self.playmode()\n self.history.save(self.timer, ' '.join(self.scramble), self.mode)\n\n def playmode(self):\n self.timer.go(self.mode)\n while True:\n c = getch()\n if c == ' ':\n self.timer.stop()\n self.history.solvecount += 1\n print('\\n')\n return\n\n def configmode(self):\n while True:\n c = getch()\n if c == ' ':\n break # space = start next solve\n if c == 'q': # q = exit timer mode\n print(\"Quit Timer\\n\")\n return -1\n if c == 'p':\n # p = print last 2 solves\n print(self.history.getlast(self.mode, 2))\n if c == 'f':\n self.history.deletelast() # f = delete last solve\n if c == 'd': # d = set last solve as dnf\n self.history.set_dnf()\n print(\"DNF nub\\n0.00\", end=\"\\r\")\n if c == '2': # 2 = set last solve as plustwo\n self.history.set_plustwo()\n print(\"+2 nub\\n0.00\", end=\"\\r\") # m = switch modes(3x3,oh, etc.)\n if c == 'm':\n self.changemode()\n\n def changemode(self):\n self.mode = input(\"let's play \")\n","sub_path":"src/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"75832558","text":"import os\n### START FAST IO ###\nos_input = os.read(0, int(1e7)).split()\nos_input_pos = -1\ndef cin():\n global os_input_pos\n os_input_pos += 1\n return os_input[os_input_pos]\n# cout: os.write(1, \"\\n\".join(res).encode())\n#### END FAST IO ####\n\nfrom bisect import bisect\n\nT = int(cin())\nres = []\nwhile T:\n T -= 1\n n, m = int(cin()), int(cin())\n ans = (2**m - 1) // 2\n a = sorted([int(cin(), 2) for i in range(n)])\n leq = bisect(a, ans)\n small = ans + 1 - leq\n big = 2**m - 1 - ans - (n - leq)\n\n have = set(a)\n while small > big:\n if ans not in have:\n small -= 1\n big += 1\n ans -= 1\n while small < big:\n ans += 1\n if ans not in have:\n small += 1\n big -= 1\n while ans in have:\n ans -= 1\n res.append(bin(ans)[2:].zfill(m))\nos.write(1, \"\\n\".join(res).encode())\n","sub_path":"codeforces/1360/h.py","file_name":"h.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"449367820","text":"import random\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nimport pytest\nfrom elsim.strategies import approval_optimal\n\n\ndef collect_random_results(method, election):\n \"\"\"\n Run multiple elections with tiebreaker='random' and collect the set of all\n winners.\n \"\"\"\n random.seed(47) # Deterministic test\n winners = set()\n for trial in range(10):\n winner = method(election, tiebreaker='random')\n assert isinstance(winner, int)\n winners.add(winner)\n return winners\n\n\n@pytest.mark.parametrize(\"tiebreaker\", [None, 'random', 'order'])\ndef test_approval_optimal(tiebreaker):\n utilities = np.array([[0.0, 0.4, 1.0],\n [1.0, 0.5, 1.0],\n [0.0, 0.2, 0.0],\n [0.0, 1.0, 0.7],\n [0.3, 0.4, 0.6],\n ])\n assert_array_equal(approval_optimal(utilities), [[0, 0, 1],\n [1, 0, 1],\n [0, 1, 0],\n [0, 1, 1],\n [0, 0, 1],\n ])\n\n\nif __name__ == \"__main__\":\n # Run unit tests, in separate process to avoid warnings about cached\n # modules, printing output line by line in realtime\n from subprocess import Popen, PIPE\n with Popen(['pytest',\n '--tb=short', # shorter traceback format\n '--hypothesis-show-statistics',\n str(__file__)], stdout=PIPE, bufsize=1,\n universal_newlines=True) as p:\n for line in p.stdout:\n print(line, end='')\n","sub_path":"tests/test_strategies.py","file_name":"test_strategies.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"375688380","text":"# commandline argument is fs, dssp, 3A, 4A, or 5A\nimport numpy as np\nimport pickle as pkl\nfrom pprint import pprint\nimport pandas as pd\nfrom sys import argv\n\nscript, ifg = argv\n\nifg_sasa_pkl = 'noskip_sasa_pkl/noskip_%s_sasa.pkl'%ifg # in wd \nifg_sasa=pkl.load(open(ifg_sasa_pkl,'rb'))\n\nsasa_dict = {}\nAAs = ['ALA', 'ARG', 'VAL', 'MET', 'GLU', 'GLN', 'GLY', \\\n 'ASP', 'ASN', 'ILE', 'LEU', 'LYS', 'HIS', 'TRP', 'TYR', 'PHE', 'PRO', 'THR', 'SER', 'CYS']\nfor aa in AAs:\n sasa_dict[aa] = []\n\n# fill sasa_dict with df values\nfor ix, row in ifg_sasa.iterrows():\n if row['resname_vdm'] in sasa_dict.keys():\n resname = row['resname_vdm']\n sasa_dict[resname].append(row['vdM_sasa_CB_3A_probe'])\n\n# col = aa, row = sasa cutoffs\nindex = [x*10 for x in range(20)][1:]\n\nall_sasa = [] # for every aa\nfor aa, x in sasa_dict.items():\n x = [float(z) for z in x ]\n for i in x:\n all_sasa.append(i)\n\nlookup = pkl.load(open('../Lookups/AAi_freq/AAi_database_lookups.pkl','rb')) # lookup table for freq(AAi) in db!\n\ndf = pd.DataFrame(index = index, columns = AAs)\nfor _bin in index:\n bin_sasa = [z<_bin and z>(_bin-20) for z in all_sasa]\n total_aa_bin = sum(bin_sasa) # counts of all aa's in this bin\n for aa, x in sasa_dict.items():\n x = [float(z) for z in x ]\n x = [z<_bin and z>(_bin-20) for z in x]\n aai_counts = sum(x) # at whatever cutoff bin\n frac_aai_bin = aai_counts / total_aa_bin # f(AAi in binj / all aa in binj)\n freq_aai_db = lookup[1][aa]\n score = frac_aai_bin / freq_aai_db\n df.ix[_bin, aa] = round(score,2)\n\npkl.dump(df, open('../Lookups/sasa_scores/scores_largeprobe_sasa_%s_lookup.pkl' % ifg,'wb'))\n","sub_path":"st_wd/burial/old/gen_sasa_scores.py","file_name":"gen_sasa_scores.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"572201560","text":"#! /usr/bin/env python\n# -*- coding: utf8 -*-\n\nimport datetime\nimport sys\nimport cgi\nimport os\nfrom jinja2 import Environment, FileSystemLoader\n\nPATH = os.path.dirname(os.path.abspath(__file__))\nTEMPLATE_ENVIRONMENT = Environment(\n autoescape=False,\n loader=FileSystemLoader(os.path.join(PATH, 'templates')),\n trim_blocks=False)\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nclass SinhoPresent:\n \n def render_template(self, template_filename, context):\n return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)\n\n def presentation(self, data, who):\n total_list = 0\n list_code = []\n dict_code = {}\n dict_name = {}\n dict_pricePer = {}\n dict_startPricePer = {}\n dict_curPrice = {}\n dict_accSign = {}\n dict_tradeAmount = {}\n dict_accSignPer = {}\n dict_weekBong = {}\n dict_priceMeans = {}\n dict_topVSper = {}\n dict_accVSmax = {}\n\n #s_curTime = data[0:6]\n t_data = data\n YY = t_data[0:4]\n MM = t_data[4:6]\n DD = t_data[6:8]\n s_curDate = '%s-%s-%s' % (YY, MM, DD)\n\n hh = t_data[8:10]\n mm = t_data[10:12]\n ss = t_data[12:14]\n s_curTime = '%s:%s:%s' % (hh, mm, ss)\n\n r = data[15:]\n r_list = r.split(\"|\")\n for items in r_list:\n fields = items.split(\"^\")\n if len(fields) != 13:\n continue\n\n total_list += 1\n\n #print '[%d] ###%s' % (total_list, str(fields))\n\n s_code = str(fields[1])\n list_code.append(s_code)\n dict_code[s_code] = s_code\n dict_name[s_code] = str(unicode(fields[0])).strip()\n #print '%s' % dict_name[s_code]\n dict_pricePer[s_code] = str(fields[2]).strip()\n dict_startPricePer[s_code] = str(fields[3]).strip()\n dict_curPrice[s_code] = str(fields[4]).strip()\n dict_accSign[s_code] = str(fields[5]).strip()\n dict_tradeAmount[s_code] = str(fields[6]).strip()\n dict_accSignPer[s_code] = str(fields[7]).strip()\n dict_weekBong[s_code] = str(fields[8]).strip()\n dict_priceMeans[s_code] = str(fields[9]).strip()\n dict_accVSmax[s_code] = str(fields[10]).strip()\n dict_topVSper[s_code] = str(fields[11]).strip()\n\n\n context = {\n 'who': who,\n 'curTime': s_curTime,\n 'curDate': s_curDate,\n 'list_code': list_code,\n 'dict_code': dict_code,\n 'dict_name': dict_name,\n 'dict_pricePer': dict_pricePer,\n 'dict_startPricePer': dict_startPricePer,\n 'dict_curPrice': dict_curPrice,\n 'dict_accSign': dict_accSign,\n 'dict_tradeAmount': dict_tradeAmount,\n 'dict_accSignPer': dict_accSignPer,\n 'dict_weekBong': dict_weekBong,\n 'dict_priceMeans': dict_priceMeans,\n 'dict_accVSmax': dict_accVSmax,\n 'dict_topVSper': dict_topVSper\n }\n\n html = self.render_template('present_jinja_working.html', context)\n\n return html\n\n","sub_path":"present_jinja_oj2.py","file_name":"present_jinja_oj2.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"314487282","text":"#!/usr/bin/env python \r\n# -*- coding: utf-8 -*- \r\n# __author__: xinlan 2018/1/8\r\nimport os\r\nimport sys\r\nimport re\r\nimport json\r\nimport time\r\nimport subprocess\r\nimport random\r\nfrom PIL import Image\r\nimport math\r\nimport debug\r\n# 截图参数\r\nSCREENSHOT_WAY = 2\r\n# 是否循环游戏\r\nLOOP = False\r\n# 调试\r\nDEBUG = True\r\n\r\n\r\ndef _get_screen_size():\r\n \"\"\"\r\n 获取手机屏幕分辨率\r\n :return:\r\n \"\"\"\r\n size_str = os.popen('adb shell wm size').read()\r\n print(size_str)\r\n if not size_str:\r\n print('请安装 ADB 及驱动并配置环境变量')\r\n sys.exit()\r\n m = re.search(r'(\\d+)x(\\d+)', size_str)\r\n if m:\r\n return \"{height}x{width}\".format(height=m.group(2), width=m.group(1))\r\n\r\n\r\ndef init():\r\n \"\"\"\r\n 初始化\r\n :return:\r\n \"\"\"\r\n # 获取屏幕分辨率\r\n screen_size = _get_screen_size()\r\n config_file_path = 'config/{0}/config.json'.format(screen_size)\r\n print(config_file_path)\r\n if os.path.exists(config_file_path):\r\n with open(config_file_path, 'r') as f:\r\n print(\"Load config file from {}\".format(config_file_path))\r\n return json.load(f)\r\n else:\r\n with open('config/default.json', 'r') as f:\r\n print(\"Load default config\")\r\n return json.load(f)\r\n\r\n\r\ndef get_screenshot():\r\n global SCREENSHOT_WAY\r\n if SCREENSHOT_WAY == 2 or SCREENSHOT_WAY == 1:\r\n process = subprocess.Popen('adb shell screencap -p', shell=True, stdout=subprocess.PIPE)\r\n screenshot = process.stdout.read()\r\n if SCREENSHOT_WAY == 2:\r\n binary_screenshot = screenshot.replace(b'\\r\\n', b'\\n')\r\n else:\r\n binary_screenshot = screenshot.replace(b'\\r\\r\\n', b'\\n')\r\n with open('autojump.png', 'wb') as f:\r\n f.write(binary_screenshot)\r\n\r\n elif SCREENSHOT_WAY == 0:\r\n os.system('adb shell s creencap -p /sdcard/autojump.png')\r\n os.system('adb pull /sdcard/autojump.png .')\r\n\r\n\r\ndef check_screenshot():\r\n global SCREENSHOT_WAY\r\n if os.path.isfile('autojump.png'):\r\n os.remove('autojump.png')\r\n\r\n if SCREENSHOT_WAY < 0:\r\n print('暂不支持当前设备')\r\n sys.exit()\r\n get_screenshot()\r\n try:\r\n Image.open('autojump.png').load()\r\n except Exception as e:\r\n print(e)\r\n SCREENSHOT_WAY -= 1\r\n check_screenshot()\r\n\r\n\r\ndef find_piece_and_board(img, con):\r\n w, h = img.size\r\n # 棋子的底边界\r\n piece_y_max = 0\r\n scan_x_side = int(w / 8) # 扫描棋子的左右边界减少开销\r\n scan_start_y = 0 # 扫描起始y坐标\r\n # 图片像素矩阵\r\n img_pixel = img.load()\r\n if not LOOP: # 是否循环游戏\r\n if sum(img_pixel[5, 5][:-1]) < 150: # 根据屏幕黑色\r\n exit('游戏结束!')\r\n # 以50px 步长,尝试探测 scan_start_y\r\n for i in range(int(h / 3), int(h * 2 / 3), 50):\r\n first_pixel = img_pixel[0, i]\r\n for j in range(1, w):\r\n # 如果不是纯色,说明碰到了新的棋盘,跳出\r\n pixel = img_pixel[j, i]\r\n if pixel[0] != first_pixel[0] or pixel[1] != first_pixel[1] or pixel[2] != first_pixel[2]:\r\n scan_start_y = i - 50\r\n break\r\n if scan_start_y:\r\n break\r\n\r\n # 从上往下开始扫描棋子,棋子位于屏幕上半部分\r\n left = 0\r\n right = 0\r\n for i in range(scan_start_y, int(h * 2 / 3)):\r\n flag = True\r\n\r\n for j in range(scan_x_side, w - scan_x_side):\r\n pixel = img_pixel[j, i]\r\n # 根据棋子的最低行的颜色判断,找最后一行那些点的平均值\r\n if (50 < pixel[0] < 60) and (53 < pixel[1] < 63) and (95 < pixel[2] < 110):\r\n if flag:\r\n left = j\r\n flag = False\r\n right = j\r\n piece_y_max = max(i, piece_y_max)\r\n if not all((left, right)):\r\n return 0, 0, 0, 0\r\n piece_x = (left + right) // 2\r\n piece_y = piece_y_max - con['piece_base_height_1_2'] # 上调高度,根据分辨率自行 调节\r\n\r\n # 限制棋盘扫描横坐标\r\n if piece_x < w / 2: # 棋子在左边\r\n board_x_start = piece_x + con[\"piece_body_width\"]//2\r\n board_x_end = w\r\n else:\r\n board_x_start = 0\r\n board_x_end = piece_x - con[\"piece_body_width\"]//2\r\n\r\n # 从上往下扫描找到棋盘的顶点\r\n left = 0\r\n right = 0\r\n num = 0\r\n for i in range(int(h / 3), int(h * 2 / 3)):\r\n flag = True\r\n first_pixel = img_pixel[0, i]\r\n for j in range(board_x_start, board_x_end):\r\n pixel = img_pixel[j, i]\r\n # 20是色差阈值可以调节\r\n if abs(pixel[0] - first_pixel[0]) + abs(pixel[1] - first_pixel[1]) + abs(pixel[2] - first_pixel[2]) > 10:\r\n if flag:\r\n left = j\r\n right = j\r\n flag = False\r\n else:\r\n right = j\r\n num += 1\r\n # print(left, right)\r\n if not flag:\r\n break\r\n\r\n board_x = (left + right) // 2\r\n top_point = img_pixel[board_x, i+1] # i+1去掉上面一条白线的bug\r\n # 从上顶点往下 + con['hight'] 的位置开始向上找颜色与上顶点一样的点,为下顶点\r\n # if num < 5:\r\n # # 说明是方形\r\n # if abs(top_point[0] - 255) + abs(top_point[1] - 228) + abs(top_point[2] - 226) < 5:\r\n # print('唱片图案')\r\n # top = 0\r\n # bottom = 0\r\n # for k in range(i, i + con[\"hight\"]):\r\n # pixel = img_pixel[board_x, k]\r\n # # 根据唱片中的红色部分判断\r\n # # if (155 < pixel[0] < 180) and (141 < pixel[1] < 165) and (113 < pixel[2] < 116):\r\n # # print(pixel[0], pixel[1], pixel[2])\r\n # if (abs(pixel[0] - 239) < 3) and (abs(pixel[1] - 118) < 3) and (abs(pixel[2] - 119) < 3):\r\n #\r\n # if not top:\r\n # top = k\r\n # else:\r\n # bottom = k\r\n # # print(top, bottom)\r\n # board_y = (top + bottom) // 2\r\n # return piece_x, piece_y, board_x, board_y\r\n\r\n # 该方法对所有纯色平面和部分非纯色平面有效\r\n # print(top_point)\r\n for k in range(i + con[\"hight\"], i, -1):\r\n pixel = img_pixel[board_x, k]\r\n # print(pixel)\r\n if abs(pixel[0] - top_point[0]) + abs(pixel[1] - top_point[1]) + abs(pixel[2] - top_point[2]) < 10:\r\n break\r\n board_y = (i + k) // 2\r\n\r\n if num < 5:\r\n # 去除有些颜色比较多的误差\r\n\r\n if k - i < 30:\r\n print('酱红色433----》》》')\r\n board_y += (k - i)\r\n\r\n # 去掉药瓶\r\n\r\n if top_point[:-1] == (255, 255, 255):\r\n print('药瓶图案')\r\n board_y = (i + board_y) // 2\r\n\r\n # 去掉唱片\r\n if num == 3:\r\n if top_point[:-1] == (219, 221, 229):\r\n print('唱片')\r\n top = 0\r\n bottom = 0\r\n for k in range(i, i + con[\"hight\"]):\r\n pixel = img_pixel[board_x, k]\r\n # 根据唱片中的红色部分判断\r\n # if (155 < pixel[0] < 180) and (141 < pixel[1] < 165) and (113 < pixel[2] < 116):\r\n # print(pixel[0], pixel[1], pixel[2])\r\n if pixel[:-1] == (118, 118, 118):\r\n\r\n if not top:\r\n top = k\r\n else:\r\n bottom = k\r\n # print(top, bottom)\r\n board_y = (top + bottom) // 2\r\n return piece_x, piece_y, board_x, board_y\r\n\r\n if not all((board_x, board_y)):\r\n return 0, 0, 0, 0\r\n\r\n return piece_x, piece_y, board_x, board_y\r\n\r\n\r\ndef jump(distance, point, ratio):\r\n press_time = distance * ratio\r\n press_time = max(press_time, 200) # 最小按压时间\r\n press_time = int(press_time)\r\n cmd = 'adb shell input swipe {x1} {y1} {x2} {y2} {duration}'.format(\r\n x1=point[0],\r\n y1=point[1],\r\n x2=point[0] + random.randint(0, 3),\r\n y2=point[1] + random.randint(0, 3),\r\n duration=press_time\r\n )\r\n print(cmd)\r\n os.system(cmd)\r\n return press_time\r\n\r\n\r\ndef run():\r\n oper = input('请确保手机打开了 ADB 并连接了电脑,然后打开跳一跳并【开始游戏】后再用本程序,确定开始?y/n>>:')\r\n if oper != 'y':\r\n exit('退出')\r\n # 初始化,获取配置\r\n config = init()\r\n # 检测截图方式\r\n check_screenshot()\r\n while True:\r\n # 获取截图\r\n get_screenshot()\r\n # 获取棋子,棋盘位置\r\n img = Image.open('autojump.png')\r\n piece_x, piece_y, board_x, board_y = find_piece_and_board(img, config)\r\n ntime = time.time()\r\n print(piece_x, piece_y, board_x, board_y, '------->')\r\n distance = math.sqrt((board_x - piece_x) ** 2 + (board_y - piece_y) ** 2)\r\n # 生成一个随机按压点,防止被ban\r\n\r\n press_point = (random.randint(*config['swipe']['x']),\r\n random.randint(*config['swipe']['y']))\r\n jump(distance, press_point, config['press_ratio'])\r\n if DEBUG:\r\n debug.save_debug_screenshot(ntime, img, piece_x, piece_y, board_x, board_y)\r\n debug.backup_screenshot(ntime)\r\n time.sleep(random.randrange(1, 2))\r\n\r\n\r\ndef test_scrennshot():\r\n\r\n img = Image.open('autojump.png')\r\n con = init()\r\n res = find_piece_and_board(img, con)\r\n print(res)\r\n\r\n# def test_time_ratio():\r\n# config = init()\r\n#\r\n#\r\n# get_screenshot()\r\n# img = Image.open('autojump.png')\r\n# piece_x, piece_y, board_x, board_y = find_piece_and_board(img)\r\n# print(piece_x, piece_y)\r\n# point = (random.randint(*config['swipe']['x']),\r\n# random.randint(*config['swipe']['y']))\r\n# t = 600\r\n#\r\n# cmd = 'adb shell input swipe {x1} {y1} {x2} {y2} {duration}'.format(\r\n# x1=point[0],\r\n# y1=point[1],\r\n# x2=point[0] + random.randint(0, 3),\r\n# y2=point[1] + random.randint(0, 3),\r\n# duration=t\r\n# )\r\n# print(cmd)\r\n# os.system(cmd)\r\n# time.sleep(2)\r\n# get_screenshot()\r\n# img = Image.open('autojump.png')\r\n# piece_2x, piece_2y, board_2x, board_2y = find_piece_and_board(img)\r\n#\r\n# print(piece_2x, piece_2y)\r\n# print(t/math.sqrt((piece_x-piece_2x)**2+(piece_y-piece_2y)**2))\r\n\r\nif __name__ == '__main__':\r\n run()\r\n # test_time_ratio()\r\n # test_scrennshot()\r\n # get_screenshot()\r\n # check_screenshot()","sub_path":"auto.py","file_name":"auto.py","file_ext":"py","file_size_in_byte":10686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"317337922","text":"from Node import Node\r\n\r\nclass QueueAsLinkedList:\r\n def __init__(self):\r\n self.head = None\r\n self.tail = None\r\n\r\n def isEmpty(self):\r\n return self.head == None\r\n\r\n def size(self):\r\n count = 0\r\n tmp = self.head\r\n while tmp != None:\r\n count += 1\r\n tmp = tmp.next\r\n\r\n return count\r\n\r\n def print(self):\r\n result = \"\"\r\n tmp = self.head\r\n while tmp != None:\r\n result += str(tmp.payload)\r\n tmp = tmp.next\r\n print(result)\r\n\r\n def enqueue(self, payload):\r\n if self.isEmpty():\r\n self.head = Node(payload, self.head)\r\n self.tail = self.head\r\n else: \r\n self.head = Node(payload, self.head)\r\n\r\n def dequeue(self):\r\n if self.isEmpty():\r\n return None\r\n else:\r\n nodeToRemove = self.tail\r\n if self.head == self.tail:\r\n self.head = self.tail = None\r\n else:\r\n tmp = self.head\r\n while tmp.next != self.tail:\r\n tmp = tmp.next\r\n tmp.next = None\r\n self.tail = tmp\r\n return nodeToRemove.payload\r\n\r\n\r\n\r\nq = QueueAsLinkedlList()\r\nq.enqueue(\"string\")\r\nq.enqueue(12)\r\nq.enqueue(100)\r\n\r\nq.print()\r\nwhile not q.isEmpty():\r\n print(q.dequeue())","sub_path":"Ch03. Basic Data Structures/QueueAsLinkedList.py","file_name":"QueueAsLinkedList.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"604945706","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# payment_account module for OpenERP, Allows to create account payment from payment transaction\n# Copyright (C) 2016 SYLEAM Info Services ()\n# Sebastien LANGE \n#\n# This file is a part of payment_account\n#\n# payment_account is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# payment_account 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 models, fields, api\n\n\nclass AccountPayment(models.Model):\n _inherit = 'account.payment'\n\n transaction_id = fields.Many2one(comodel_name='payment.transaction', string='Payment Transaction')\n\n @api.onchange('transaction_id')\n def _onchange_transaction_id(self):\n if self.transaction_id:\n transaction = self.transaction_id\n self.partner_id = transaction.partner_id\n self.amount = transaction.amount\n self.currency_id = transaction.currency_id\n self.journal_id = transaction.acquirer_id.journal_id\n self.communication = transaction.acquirer_reference or transaction.reference\n\n @api.multi\n def validate_payment(self):\n self.transaction_id.state = 'done'\n self.post()\n return True\n\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"models/account_payment.py","file_name":"account_payment.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"147177118","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport os\nimport sys\nimport numpy as np\nimport pandas as pd\nimport cv2\n\n\n# In[2]:\n\n\nimage_size = 100\npath_name = './expression/original'\n\n\n# In[3]:\n\n\nimages = []\nlabels = []\npath = []\nimageID = []\nID = []\n\n\n# In[4]:\n\n\ndef resize_image(image, height = image_size, width = image_size):\n top, bottom, left, right = (0, 0, 0, 0)\n \n #獲取影象尺寸\n h, w, _ = image.shape\n \n #對於長寬不相等的圖片,找到最長的一邊\n longest_edge = max(h, w) \n \n #計算短邊需要增加多上畫素寬度使其與長邊等長\n if h < longest_edge:\n dh = longest_edge - h\n top = dh // 2\n bottom = dh - top\n elif w < longest_edge:\n dw = longest_edge - w\n left = dw // 2\n right = dw - left\n else:\n pass \n \n #RGB顏色\n BLACK = [0, 0, 0]\n \n #給影象增加邊界,是圖片長、寬等長,cv2.BORDER_CONSTANT指定邊界顏色由value指定\n constant = cv2.copyMakeBorder(image, top , bottom, left, right, cv2.BORDER_CONSTANT, value = BLACK)\n \n #調整影象大小並返回\n return cv2.resize(constant, (height, width))\n\n\n# In[5]:\n\n\ndef read_path(path_name):\n for dir_item in os.listdir(path_name):\n #從初始路徑開始疊加,合併成可識別的操作路徑\n full_path = os.path.abspath(os.path.join(path_name, dir_item))\n\n if os.path.isdir(full_path): #如果是資料夾,繼續遞迴呼叫\n read_path(full_path)\n else: #檔案\n if dir_item.endswith('.jpg'):\n image = cv2.imread(full_path)\n image = resize_image(image, image_size, image_size)\n \n #放開這個程式碼,可以看到resize_image()函式的實際呼叫效果\n #cv2.imwrite('1.jpg', image)\n \n images.append(image) \n path.append(full_path) \n \n return images, path\n\n\n# In[6]:\n\n\nimages, path = read_path(path_name)\n\n\n# In[7]:\n\n\nfor i in range(len(path)):\n ID.append(path[i].split('\\\\')[-1])\n\n\n# In[8]:\n\n\nprint(ID)\n\n\n# In[9]:\n\n\nwith open('expression/list_patition_label1.txt', 'r') as f:\n label = f.read().splitlines()\n\nfor i in range(len(label)):\n imageID.append(label[i].split(' ')[0])\n labels.append(label[i].split(' ')[1])\n\n\n# In[10]:\n\n\nnewlabels = []\nfor i in ID:\n index = imageID.index(i)\n newlabels.append(labels[index])\n\n\n# In[11]:\n\n\nprint(newlabels)\n\n\n# In[12]:\n\n\n#將輸入的所有圖片轉成四維陣列,尺寸為(圖片數量*IMAGE_SIZE*IMAGE_SIZE*3)\n#我和閨女兩個人共1200張圖片,IMAGE_SIZE為64,故對我來說尺寸為1200 * 64 * 64 * 3\n#圖片為64 * 64畫素,一個畫素3個顏色值(RGB)\nimages = np.array(images)\nprint(images.shape) \n\n\n# In[13]:\n\n\nnewlabels = np.array(newlabels)\nprint(newlabels.shape)\n\n\n# In[ ]:\n\n\n\n\n\n# In[14]:\n\n\nimport random\n\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Convolution2D, MaxPooling2D\nfrom keras.optimizers import SGD\nfrom keras.utils import np_utils\nfrom keras.models import load_model\nfrom keras import backend as K\n\n#from load_face_dataset import load_dataset, resize_image, IMAGE_SIZE\n\n\n# In[15]:\n\n\ntemp_images, test_images, temp_labels, test_labels = train_test_split(images, newlabels, test_size=0.1,random_state = random.randint(0, 100))\n\n\n# In[16]:\n\n\ntrain_images, valid_images, train_labels, valid_labels = train_test_split(temp_images, temp_labels, test_size=0.2, random_state = random.randint(0, 100))\n\n\n# In[17]:\n\n\n#把label的1~11改成0~10,為了作one hot encoding\nfor i in range(len(train_labels)):\n train_labels[i] = np.int(train_labels[i]) - 1\n\nfor i in range(len(valid_labels)):\n valid_labels[i] = np.int(valid_labels[i]) - 1\n \nfor i in range(len(test_labels)):\n test_labels[i] = np.int(test_labels[i]) - 1\n\n\n# In[18]:\n\n\n#我們的模型使用categorical_crossentropy作為損失函式,因此需要根據類別數量nb_classes\n#類別標籤進行one-hot編碼使其向量化,在這裡我們的類別只有兩種,經過轉化後標籤資料變為二維\n\nclasses = 11\n\ntrain_labels = np_utils.to_categorical(train_labels, classes)\nvalid_labels = np_utils.to_categorical(valid_labels, classes)\ntest_labels = np_utils.to_categorical(test_labels, classes)\n\n\n# In[19]:\n\n\n#畫素資料浮點化以便歸一化\ntrain_images = train_images.astype('float32') \nvalid_images = valid_images.astype('float32')\ntest_images = test_images.astype('float32')\n\n\n# In[20]:\n\n\n#將其歸一化,影象的各畫素值歸一化到0~1區間\ntrain_images /= 255\nvalid_images /= 255\ntest_images /= 255\n\n\n# In[22]:\n\n\nmodel = Sequential()\n\nmodel.add(Convolution2D(32, 3, 3, border_mode='same', input_shape = (100,100,3) )) #卷積層\nmodel.add(Activation('relu')) #啟用函式層\nmodel.add(MaxPooling2D(2,2)) #池化層\nmodel.add(Dropout(0.25)) #dropout層\n\nmodel.add(Convolution2D(50, 3, 3))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(2,2))\nmodel.add(Dropout(0.25)) \n\nmodel.add(Flatten()) #flatten層\n\nmodel.add(Dense(512)) #全聯通層\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(classes))\nmodel.add(Activation('softmax')) #分類層\n\nmodel.summary()\n\n\n# In[23]:\n\n\n#訓練模型\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n\n# In[24]:\n\n\nmodel.fit(x=train_images,y=train_labels,validation_split=0.2, epochs=10, batch_size=300,verbose=2)\n\n\n# In[25]:\n\n\nresult = model.evaluate(train_images, train_labels)\nprint ('\\ntrain Acc:', result[1])\n\n\n# In[26]:\n\n\nresult = model.evaluate(test_images, test_labels)\nprint ('\\nTest Acc:', result[1])\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Expression Recognition.py","file_name":"Expression Recognition.py","file_ext":"py","file_size_in_byte":5907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"530307252","text":"symbolsAlpha = [chr(x) for x in range(65,91)]\nsymbolsCrypt = ['!','@','#','$','%','^','&','*','(',')','-','=',\n'+','?',':',';','<','>','/','[',']','{','}','|','.',',','~']\n\ncryptMode = input(\"[E]ncrypt|[D]ecrypt: \").upper()\nif cryptMode not in ['E','D']:\n\tprint(\"Error: mode is not Found!\"); raise SystemExit\nstartMessage = input(\"Write the message: \").upper()\nkeys = dict(zip(symbolsAlpha,symbolsCrypt))\n\ndef encryptDecrypt(mode, message, final = \"\"):\n\tif mode == 'E':\n\t\tfor symbol in message:\n\t\t\tif symbol in keys: final += keys[symbol]\n\telse:\n\t\tfor symbol in message:\n\t\t\tfor key in keys:\n\t\t\t\tif symbol == keys[key]: final += key\n\treturn final\nprint(\"Final message:\",encryptDecrypt(cryptMode, startMessage))\n\nclass write():\n try:\n namefile = input(\"File name: \")\n with open(namefile, 'ab') as file:\n text = (encryptDecrypt(cryptMode, startMessage))\n file.write(text.encode(\"utf-8\"))\n except FileNotFoundError:\n print(\"[x] File: '\" + str(namefile) + \"' is not defined!\")\n raise SystemExit\n else:\n print(\"[+] File: \" + str(namefile) + \" successfully overwritten!\")","sub_path":"криптография/crypt1.py","file_name":"crypt1.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"644555900","text":"# Copyright (c) 2019-2020, NVIDIA CORPORATION.\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 cupy as cp\nfrom ..convolution.convolve import convolve\n\n_qmf_kernel = cp.ElementwiseKernel(\n \"\",\n \"int64 output\",\n \"\"\"\n const int sign { ( i & 1 ) ? -1 : 1 };\n output = ( _ind.size() - ( i + 1 ) ) * sign;\n \"\"\",\n \"_qmf_kernel\",\n options=(\"-std=c++11\",),\n)\n\n\ndef qmf(hk):\n \"\"\"\n Return high-pass qmf filter from low-pass\n\n Parameters\n ----------\n hk : array_like\n Coefficients of high-pass filter.\n\n \"\"\"\n return _qmf_kernel(size=len(hk))\n\n\n_morlet_kernel = cp.ElementwiseKernel(\n \"float64 w, float64 s, bool complete\",\n \"complex128 output\",\n \"\"\"\n const double x { start + delta * i };\n\n thrust::complex temp { exp(\n thrust::complex( 0, w * x ) ) };\n\n if ( complete ) {\n temp -= exp( -0.5 * ( w * w ) );\n }\n\n output = temp * exp( -0.5 * ( x * x ) ) * pow( M_PI, -0.25 )\n \"\"\",\n \"_morlet_kernel\",\n options=(\"-std=c++11\",),\n loop_prep=\"const double end { s * 2.0 * M_PI }; \\\n const double start { -s * 2.0 * M_PI }; \\\n const double delta { ( end - start ) / ( _ind.size() - 1 ) };\",\n)\n\n\ndef morlet(M, w=5.0, s=1.0, complete=True):\n \"\"\"\n Complex Morlet wavelet.\n\n Parameters\n ----------\n M : int\n Length of the wavelet.\n w : float, optional\n Omega0. Default is 5\n s : float, optional\n Scaling factor, windowed from ``-s*2*pi`` to ``+s*2*pi``. Default is 1.\n complete : bool, optional\n Whether to use the complete or the standard version.\n\n Returns\n -------\n morlet : (M,) ndarray\n\n See Also\n --------\n cusignal.gausspulse\n\n Notes\n -----\n The standard version::\n\n pi**-0.25 * exp(1j*w*x) * exp(-0.5*(x**2))\n\n This commonly used wavelet is often referred to simply as the\n Morlet wavelet. Note that this simplified version can cause\n admissibility problems at low values of `w`.\n\n The complete version::\n\n pi**-0.25 * (exp(1j*w*x) - exp(-0.5*(w**2))) * exp(-0.5*(x**2))\n\n This version has a correction\n term to improve admissibility. For `w` greater than 5, the\n correction term is negligible.\n\n Note that the energy of the return wavelet is not normalised\n according to `s`.\n\n The fundamental frequency of this wavelet in Hz is given\n by ``f = 2*s*w*r / M`` where `r` is the sampling rate.\n\n Note: This function was created before `cwt` and is not compatible\n with it.\n\n \"\"\"\n return _morlet_kernel(w, s, complete, size=M)\n\n\n_ricker_kernel = cp.ElementwiseKernel(\n \"float64 a\",\n \"float64 total\",\n \"\"\"\n const double vec { i - ( _ind.size() - 1.0 ) * 0.5 };\n const double xsq { vec * vec };\n const double mod { 1 - xsq / wsq };\n const double gauss { exp( -xsq / ( 2.0 * wsq ) ) };\n\n total = A * mod * gauss;\n \"\"\",\n \"_ricker_kernel\",\n options=(\"-std=c++11\",),\n loop_prep=\"const double A { 2.0 / ( sqrt( 3 * a ) * pow( M_PI, 0.25 ) ) }; \\\n const double wsq { a * a };\",\n)\n\n\ndef ricker(points, a):\n \"\"\"\n Return a Ricker wavelet, also known as the \"Mexican hat wavelet\".\n\n It models the function:\n\n ``A (1 - x^2/a^2) exp(-x^2/2 a^2)``,\n\n where ``A = 2/sqrt(3a)pi^1/4``.\n\n Parameters\n ----------\n points : int\n Number of points in `vector`.\n Will be centered around 0.\n a : scalar\n Width parameter of the wavelet.\n\n Returns\n -------\n vector : (N,) ndarray\n Array of length `points` in shape of ricker curve.\n\n Examples\n --------\n >>> import cusignal\n >>> import cupy as cp\n >>> import matplotlib.pyplot as plt\n\n >>> points = 100\n >>> a = 4.0\n >>> vec2 = cusignal.ricker(points, a)\n >>> print(len(vec2))\n 100\n >>> plt.plot(cp.asnumpy(vec2))\n >>> plt.show()\n\n \"\"\"\n return _ricker_kernel(a, size=points)\n\n\n_morlet2_kernel = cp.ElementwiseKernel(\n \"float64 w, float64 s\",\n \"complex128 output\",\n \"\"\"\n const double x { ( i - ( _ind.size() - 1.0 ) * 0.5 ) / s };\n\n thrust::complex temp { exp(\n thrust::complex( 0, w * x ) ) };\n\n output = sqrt( 1 / s ) * temp * exp( -0.5 * ( x * x ) ) *\n pow( M_PI, -0.25 )\n \"\"\",\n \"_morlet_kernel\",\n options=(\"-std=c++11\",),\n loop_prep=\"\",\n)\n\n\ndef morlet2(M, s, w=5):\n \"\"\"\n Complex Morlet wavelet, designed to work with `cwt`.\n Returns the complete version of morlet wavelet, normalised\n according to `s`::\n exp(1j*w*x/s) * exp(-0.5*(x/s)**2) * pi**(-0.25) * sqrt(1/s)\n Parameters\n ----------\n M : int\n Length of the wavelet.\n s : float\n Width parameter of the wavelet.\n w : float, optional\n Omega0. Default is 5\n Returns\n -------\n morlet : (M,) ndarray\n See Also\n --------\n morlet : Implementation of Morlet wavelet, incompatible with `cwt`\n Notes\n -----\n .. versionadded:: 1.4.0\n This function was designed to work with `cwt`. Because `morlet2`\n returns an array of complex numbers, the `dtype` argument of `cwt`\n should be set to `complex128` for best results.\n Note the difference in implementation with `morlet`.\n The fundamental frequency of this wavelet in Hz is given by::\n f = w*fs / (2*s*np.pi)\n where ``fs`` is the sampling rate and `s` is the wavelet width parameter.\n Similarly we can get the wavelet width parameter at ``f``::\n s = w*fs / (2*f*np.pi)\n Examples\n --------\n >>> from scipy import signal\n >>> import matplotlib.pyplot as plt\n >>> M = 100\n >>> s = 4.0\n >>> w = 2.0\n >>> wavelet = signal.morlet2(M, s, w)\n >>> plt.plot(abs(wavelet))\n >>> plt.show()\n This example shows basic use of `morlet2` with `cwt` in time-frequency\n analysis:\n >>> from scipy import signal\n >>> import matplotlib.pyplot as plt\n >>> t, dt = np.linspace(0, 1, 200, retstep=True)\n >>> fs = 1/dt\n >>> w = 6.\n >>> sig = np.cos(2*np.pi*(50 + 10*t)*t) + np.sin(40*np.pi*t)\n >>> freq = np.linspace(1, fs/2, 100)\n >>> widths = w*fs / (2*freq*np.pi)\n >>> cwtm = signal.cwt(sig, signal.morlet2, widths, w=w)\n >>> plt.pcolormesh(t, freq, np.abs(cwtm),\n cmap='viridis', shading='gouraud')\n >>> plt.show()\n \"\"\"\n\n return _morlet2_kernel(w, s, size=M)\n\n\ndef cwt(data, wavelet, widths):\n \"\"\"\n Continuous wavelet transform.\n\n Performs a continuous wavelet transform on `data`,\n using the `wavelet` function. A CWT performs a convolution\n with `data` using the `wavelet` function, which is characterized\n by a width parameter and length parameter.\n\n Parameters\n ----------\n data : (N,) ndarray\n data on which to perform the transform.\n wavelet : function\n Wavelet function, which should take 2 arguments.\n The first argument is the number of points that the returned vector\n will have (len(wavelet(length,width)) == length).\n The second is a width parameter, defining the size of the wavelet\n (e.g. standard deviation of a gaussian). See `ricker`, which\n satisfies these requirements.\n widths : (M,) sequence\n Widths to use for transform.\n\n Returns\n -------\n cwt: (M, N) ndarray\n Will have shape of (len(widths), len(data)).\n\n Notes\n -----\n ::\n\n length = min(10 * width[ii], len(data))\n cwt[ii,:] = cusignal.convolve(data, wavelet(length,\n width[ii]), mode='same')\n\n Examples\n --------\n >>> import cusignal\n >>> import cupy as cp\n >>> import matplotlib.pyplot as plt\n >>> t = cp.linspace(-1, 1, 200, endpoint=False)\n >>> sig = cp.cos(2 * cp.pi * 7 * t) + cusignal.gausspulse(t - 0.4, fc=2)\n >>> widths = cp.arange(1, 31)\n >>> cwtmatr = cusignal.cwt(sig, cusignal.ricker, widths)\n >>> plt.imshow(cp.asnumpy(cwtmatr), extent=[-1, 1, 31, 1], cmap='PRGn',\n aspect='auto', vmax=abs(cwtmatr).max(),\n vmin=-abs(cwtmatr).max())\n >>> plt.show()\n\n \"\"\"\n output = cp.empty([len(widths), len(data)])\n for ind, width in enumerate(widths):\n wavelet_data = wavelet(min(10 * width, len(data)), width)\n output[ind, :] = convolve(data, wavelet_data, mode=\"same\")\n return output\n","sub_path":"python/cusignal/wavelets/wavelets.py","file_name":"wavelets.py","file_ext":"py","file_size_in_byte":8808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"618672123","text":"from itertools import cycle\n\n\ndef encode(xs, height):\n xs = xs.replace(' ', '')\n positions = pattern(height, len(xs))\n return ''.join(xs[i] for _, i in positions)\n\n\ndef decode(xs, height):\n positions = pattern(height, len(xs))\n rectified = sorted(enumerate(positions), key=lambda t: t[1][1])\n return ''.join(xs[i] for i, _ in rectified)\n\n\ndef pattern(height, width):\n n = 2 * (height - 1)\n positions = (min(x, n - x) for x in cycle(range(n)))\n return sorted(zip(positions, range(width)))\n\n\nif __name__ == '__main__':\n text = open('data.txt', 'r', encoding='utf8').read()\n\n layers = int(input('Enter number of layers: '))\n crypted_text = encode(text, layers)\n print('Crypted text: ', crypted_text)\n print('Encrypted text: ', decode(crypted_text, layers))\n","sub_path":"Lab_4/lab_4.py","file_name":"lab_4.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"427419052","text":"from sys import argv\n\nscript, user_name, eheheh = argv\nprompt = '>>>> '\n\nprint(\"%s %s, I'm the %s script. \"%(eheheh, user_name, script))\nprint(\"I'd like to ask you a few questions.\")\nprint(\"Do you like me %s?. \" %(user_name))\nlk = input(prompt)\nprint(\"Where do you live %s?\" %(user_name))\nlv = input(prompt)\nprint(\"What kind of computer do you have??\" )\nc = input(prompt)\n\nprint(\"\"\"\nYea you said %r about liking me.\nYou live in %r, not sure where the fxxk there is.\nAnd you have a %r computer. Great Job.\n\"\"\"%(lk, lv, c))","sub_path":"learnPythonTheHardWay/ex14.py","file_name":"ex14.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"343673620","text":"from __future__ import absolute_import\nimport logging\nimport tornado\nfrom tornado.websocket import WebSocketHandler\nfrom dxlclient import EventCallback, ResponseCallback\n\nlogger = logging.getLogger(__name__)\n\n\nclass _WebSocketEventCallback(EventCallback):\n \"\"\"\n A DXL event callback to handle all events by adding them to delivery queues\n and notifying the browser through WebSockets.\n \"\"\"\n\n def __init__(self, web_socket, module):\n super(_WebSocketEventCallback, self).__init__()\n self._socket = web_socket\n self._module = module\n\n def on_event(self, event):\n \"\"\"\n Adds the event to a pending messages queue and notifies the associated\n WebSocket that an event is waiting\n\n :param event: the incoming event\n \"\"\"\n logger.debug(\"Received event on topic: %s\", event.destination_topic)\n self._module.queue_message(event, self._socket._client_id)\n self._module.io_loop.add_callback(self._socket.write_message,\n u\"messagesPending\")\n\n\nclass _WebSocketResponseCallback(ResponseCallback):\n \"\"\"\n A DXL Response callback to handle all responses by adding them to delivery\n queues and notifying the browser through WebSockets.\n \"\"\"\n\n def __init__(self, web_socket, module):\n super(_WebSocketResponseCallback, self).__init__()\n self._socket = web_socket\n self._module = module\n\n def on_response(self, response):\n \"\"\"\n Adds the response to a pending messages queue and notifies the\n associated WebSocket that a response is waiting\n\n :param response: the incoming response\n \"\"\"\n logger.debug(\n \"Received response to message: %s\", response.request_message_id)\n self._module.queue_message(response, self._socket._client_id)\n self._module.io_loop.add_callback(self._socket.write_message,\n u\"messagesPending\")\n\n\nclass ConsoleWebSocketHandler(WebSocketHandler):\n \"\"\"\n Handles the WebSocket connection used to notify the client of updates in real time\n \"\"\"\n\n def __init__(self, application, request, module):\n super(ConsoleWebSocketHandler, self).__init__(application, request)\n self._event_callback = None\n self._response_callback = None\n self._client = None\n self._client_id = None\n self._module = module\n\n def get_current_user(self):\n return self.get_secure_cookie(self.application.bootstrap_app.user_cookie_name)\n\n def data_received(self, chunk):\n pass\n\n @tornado.web.authenticated\n def open(self, *args, **kwargs):\n client_id = self.get_query_argument(\"id\", \"null\")\n if client_id == \"null\":\n logger.error(\"No client ID sent with web socket connection.\")\n return\n\n logger.debug(\"Creating web socket for client: %s\", client_id)\n self._client_id = client_id\n self._event_callback = _WebSocketEventCallback(self, self._module)\n self._response_callback = _WebSocketResponseCallback(self, self._module)\n self._client = self._module.get_dxl_client(str(client_id))\n self._module.add_web_socket(client_id, self)\n\n self._client.add_event_callback(None, self._event_callback)\n self._client.add_response_callback(None, self._response_callback)\n\n def on_message(self, message):\n self._module.client_keep_alive(self._client_id)\n\n def on_close(self):\n logger.debug(\"Web socket closed for client: %s\", self._client_id)\n if self._client:\n self._client.remove_event_callback(None, self._event_callback)\n self._client.remove_response_callback(None, self._response_callback)\n\n self._module.remove_web_socket(self._client_id)\n","sub_path":"dxlconsole/modules/monitor/websocket_handler.py","file_name":"websocket_handler.py","file_ext":"py","file_size_in_byte":3801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"570739799","text":"# -*- coding: utf-8 -*- \n# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:\n# $Id$\n#Copyright (c) 2005 Ali Afshar aafshar@gmail.com\n\n#Permission is hereby granted, free of charge, to any person obtaining a copy\n#of this software and associated documentation files (the \"Software\"), to deal\n#in the Software without restriction, including without limitation the rights\n#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n#copies of the Software, and to permit persons to whom the Software is\n#furnished to do so, subject to the following conditions:\n\n#The above copyright notice and this permission notice shall be included in\n#all copies or substantial portions of the Software.\n\n#THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n#SOFTWARE.\n\n\nimport gtk\nimport pida.plugin as plugin\n#import tree\nimport os\nimport gobject\nimport pida.gtkextra as gtkextra\nimport pida.configuration.registry as registry\n\ntry:\n import bike\n from bike.parsing import fastparser\nexcept ImportError:\n bike = fastparser = None\n print ('Python refactring functionality is not available. '\n 'If you wish to use these features please install '\n 'bicycle repair man (eg \"apt-get install bicyclerepair\").')\n\nbrmctx = None\n\ndef brm():\n global brmctx\n if not brmctx:\n brmctx = bike.init().brmctx\n return brmctx\n\nclass DefTree(gtkextra.Tree):\n COLUMNS = [('name', gobject.TYPE_STRING, None, False, None),\n ('display', gobject.TYPE_STRING, gtk.CellRendererText, True,\n 'markup'),\n ('line', gobject.TYPE_INT, None, False, None),\n ('column', gobject.TYPE_INT, None, False, None)]\n\n def populate(self, rootnodes, parent=None):\n for node in rootnodes:\n b = self.beautify(node)\n col = node.getLine(0).index(node.name)\n prnt = self.add_item([node.name, b, node.linenum, col], parent)\n self.populate(node.getChildNodes(), prnt)\n\n def beautify(self, el):\n mu = ('%s '\n '%s\\n'\n ' %s')\n name = el.name\n typl = el.type[0].lower()\n col = ''\n if self.prop_main_registry.python_browser.use_colors.value():\n if typl == 'f':\n col = ' foreground=\"#0000c0\"'\n else:\n col = ' foreground=\"#c00000\"'\n fl = el.getLine(0).strip().split(' ', 1)[-1].replace(name, '', 1)\n return mu % (col, typl, name, fl)\n\nclass RefTree(gtkextra.Tree):\n COLUMNS = [('name', gobject.TYPE_STRING, None, False, None),\n ('display', gobject.TYPE_STRING, gtk.CellRendererText, True,\n 'markup'),\n ('line', gobject.TYPE_INT, None, False, None),\n ('column', gobject.TYPE_INT, None, False, None)]\n\n def populate(self, nodes):\n self.clear()\n for node in nodes:\n b = self.beautify(node)\n self.add_item([node.filename, b, node.lineno, node.colno])\n self.update()\n\n def beautify(self, element):\n rel = ('%s'\n ' (L%s,'\n ' C%s)\\n'\n '%s')\n dir, name = os.path.split(element.filename)\n disp = rel % (name, element.lineno, element.colno, dir)\n s = '%s:%s' % (element.lineno, element.colno)\n return disp\n\nclass RefWin(gtkextra.Transient):\n\n def populate_widgets(self):\n self.tree = RefTree()\n self.frame.pack_start(self.tree.win)\n\nclass Plugin(plugin.Plugin):\n ICON = 'python'\n DICON = 'run', 'Execute Python script'\n NAME = \"python_browser\"\n\n def configure(self, reg):\n self.registry = reg.add_group('python_browser',\n 'The Python sopurce code browser.')\n self.registry.add('use_colors',\n registry.Boolean,\n 1,\n 'Whether colors will be used in the definition list')\n \n\n def populate_widgets(self):\n\n vp = gtk.VPaned()\n self.add(vp)\n\n self.defs = DefTree()\n vp.pack1(self.defs.win, resize=True, shrink=True)\n\n self.refwin = RefWin()\n vp.pack2(self.refwin.win, resize=True, shrink=True)\n\n self.refs = self.refwin.tree\n \n self.add_button('warning', self.cb_but_pydoc , 'Look up in Pydoc')\n #self.add_button('profile', self.cb_but_profile, 'Run in the Python profiler')\n #self.add_button('debug', self.cb_but_debug, 'Run in the Python debugger')\n self.add_separator()\n self.add_button('undo', self.cb_but_undo, 'Undo last refactoring')\n self.add_button('rename', self.cb_but_rename, 'Rename class or method')\n self.add_button('find', self.cb_but_references, 'List references.')\n\n #self.menu = gtkextra.PositionPopup('position')\n\n def connect_widgets(self):\n self.defs.connect_select(self.cb_defs_select)\n self.refs.connect_select(self.cb_refs_select)\n #self.defs.connect_rightclick(self.cb_defs_rclick)\n #self.refs.connect_rightclick(self.cb_refs_rclick)\n\n def get_references(self, label='References'):\n row, col = self.defs.selected(2), self.defs.selected(3)\n brmc = brm()\n if row and col:\n d = brmc.findReferencesByCoordinates(self.fn, int(row), int(col))\n self.refresh_refs(d, label)\n else:\n self.message('Please select a definition')\n\n def refresh_defs(self, fn):\n self.fn = fn\n f = open(fn)\n root = fastparser.fastparser(f.read())\n f.close()\n self.defs.clear()\n self.defs.populate(root.getChildNodes())\n \n def refresh_refs(self, refs, label=\"References\"):\n refs = [i for i in refs]\n self.refs.populate(refs)\n s = '%s: %s' % (label, len(refs))\n self.refwin.show(s)\n\n def execute(self):\n py = self.prop_main_registry.commands.python.value()\n dirn = os.path.split(self.fn)[0]\n self.do_action('newterminal', '%s %s' % (py, self.fn), directory=dirn)\n\n def cb_alternative(self):\n self.execute()\n \n def cb_but_pydoc(self, *args):\n def ans(text):\n self.evt_doc(text)\n self.question('Search Pydoc for:', ans)\n\n def cb_defs_select(self, tv):\n self.do_edit('gotoline', self.defs.selected(2))\n\n def cb_refs_select(self, tv):\n fn, line, col = [self.refs.selected(i) for i in [0, 2, 3]]\n if fn != self.fn:\n self.do_edit('openfile', fn)\n self.do_edit('gotoline', line)\n\n def cb_defs_rclick(self, ite, time):\n line = self.defs.get(ite, 2)\n self.menu.popup(self.fn, line, time)\n\n def cb_refs_rclick(self, ite, time):\n line = self.refs.get(ite, 2)\n self.menu.popup(self.fn, line, time)\n\n def cb_but_rename(self, *a):\n self.get_references(label='Renames')\n brmc = brm()\n def rename(name):\n row, col = self.tree.get_selected_id()\n brmc.renameByCoordinates(self.fn, int(row), int(col), name)\n brmc.save()\n self.refresh(self.fn)\n self.question('Name to rename to?', rename)\n\n def cb_but_references(self, *a):\n self.get_references()\n\n def cb_but_undo(self, *args):\n brmc = brm()\n brmc.undo()\n brmc.save()\n self.refresh(self.fn)\n\n def evt_bufferchange(self, nr, name):\n self.fn = name\n if name.endswith('py') and os.path.exists(name):\n self.refresh_defs(name)\n else:\n self.defs.model.clear()\n\n def evt_bufferexecute(self, *args):\n self.execute()\n\n def evt_started(self, *args):\n brm()\n self.refwin.hide()\n\n def evt_doc(self, text):\n pydoc = self.prop_main_registry.commands.pydoc.value()\n self.do_action('newterminal', '%s %s' % (pydoc, text))\n\n\n\n\n","sub_path":"tags/release-0.2.2/src/plugins/python_browser/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":8401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"225647557","text":"import components.seeforward as camera\nimport components.localiser as localiser\nimport components.obstacleDetector as obstacleDetector\nimport components.actOnMux as actOn\nimport components.followGradient as followLine\nimport components.getContours as getContours\nimport components.clean_contours as cc\nimport components.videowrite as videowriter\nimport components.fpsCounter as fps\nimport components.reverse as reverse\nimport components.steer as steer\nimport components.calculateAngle as calculateAngle\nimport components.checkgreen as green\nimport traceback, cv2, time, math, time\nimport numpy as np\nfrom threading import Thread\n\nmemory = {}\nmemory['reverse'] = 0\nmemory['seen_green'] = False\nmemory['green_timer'] = 0\nmemory['start_time'] = None\n\n\n# FPS stuff\nmemory['time']=time.time()\nmemory['minfps']=100\nmemory['totfps']=0\nmemory['itercount']=0\n\n# Debug stuff\nmemory['debug'] =False\nmemory['record'] = False\n\n# For arduino thread\nmemory['angle'] = 90\nmemory['speed'] = 1500\nmemory['running'] = True\n\n# This is used to actually stop execution of the script. Shouldn't need to be used tbh.\nmemory['true_stop'] = False\n\n\nbase=1560\nboost=60\n\ndef reciever(helper):\n # General setup\n global memory\n if memory['start_time'] == None:\n memory['start_time'] = time.time()\n \n helper['speed'] = 1560\n helper['angle'] = 90\n helper['debug'] = memory['debug']\n helper['target_point'] = None\n image = helper['image']\n helper['draw_image'] = image.copy()\n localiser.getOurLocation(helper)\n fps.show(memory)\n\n # Draws a black box over the top of our 'hood'\n height = helper['ourLocation'][1].astype(int)\n width = helper['ourLocation'][0].astype(int)*2\n\n image[int(height/10*7.5):, int(width/4):int(width/7*6)] = 0\n \n\n # Get Contours\n getContours.get_c(helper)\n cc.clean(helper)\n \n # Reverse if necessary\n if reverse.r(helper,memory):\n print(\"reversing...\")\n elif helper['main_y_contour'] is None and helper['main_b_contour'] is None:\n reverse.beware(helper,memory)\n print('bewareing')\n else:\n print ('not reversing...')\n if obstacleDetector.amendPath(helper):\n pass\n else:\n steer.s(helper)\n \n if helper['target_point'] is not None:\n calculateAngle.c(helper)\n # Sending stuff to arduino thread\n memory['angle'] = helper['angle']\n memory['speed'] = (1-math.fabs(memory['angle']-90)/45.0)*boost+base\n \n green.check(helper, memory)\n\n # Drawing and recording\n if memory['debug']:\n cv2.imshow(\"uneditted\", image)\n cv2.imshow(\"drawn\", helper['draw_image'])\n cv2.waitKey(1)\n\n if memory['record']:\n videowriter.writeToFile(helper)\n\ndef run():\n global memory\n camera.sendImageTo(reciever)\n\n actOnProcess = Thread(target = actOn.move, args=(memory,))\n actOnProcess.start()\n\n try:\n camera.start(memory)\n except Exception as e:\n print(e)\n traceback.print_exc()\n print('Program stopped')\n stop_thread(actOnProcess)\n memory['speed']=1500\n memory['angle']=90\n memory['running']=True\n actOn.move(memory)\n memory['running']=False\n\ndef stop_thread(actOnProcess):\n global memory\n memory['running']=False\n actOnProcess.join()\n\n\nif __name__ == '__main__':\n try:\n while not memory['true_stop']:\n input('Press enter when ready: ')\n run()\n memory['speed']=1500\n memory['angle']=90\n memory['running']=True\n actOn.move(memory)\n finally:\n stop_thread(actOnProcess)\n","sub_path":"see_plus_safe.py","file_name":"see_plus_safe.py","file_ext":"py","file_size_in_byte":3612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"76083472","text":"\"\"\"\nProjet d'année 2014-2014 (Partie 4)\nNom : Raphaël Slagmolen\nEtudes : BA1-INFO\nMatricule : 000377852\nFichier : InfosFrame.py (version final)\n\"\"\"\n\n# On importe les outils de tkinter strictement nécessaire\nfrom tkinter import LabelFrame, Label, Frame\n\n# De quoi gérer les utilisateurs et les liens d'amitié\nfrom Person import *\nfrom Link import *\n\nclass InfosFrame(LabelFrame):\n \"\"\"\n Gère la création et la mise en page de la fenêtre d'infos\n Cette objet est une Frame qui est basé sur tkinter.Frame\n \"\"\"\n \n def __init__(self, GUI, parent, **options):\n \n # On surclasse la création d'une Frame\n LabelFrame.__init__(self, parent, **options)\n \n # On récupère aussi l'objet parent\n self.GUI = GUI\n \n # On initialise le panneau des infos d'utilisateur et de cycle\n self.infos = Label(self, text=\"Pas d'utilisateurs sélectionnée\", height=5)\n self.etapes = Label(self, text=\"Nombre de cycle : 0\", height=5)\n self.stats = Label(self, text=\"Pas d'informations\", height=5)\n self.refresh()\n \n # On pack et on rafraichie\n self.infos.pack()\n Label(self, text=\"--- Statistiques sur la simulation ---\", height=5).pack()\n self.etapes.pack()\n self.stats.pack()\n \n def refresh(self, select=None):\n \"\"\"\n Appel les fonctions pour rafraichire les infos à montrer\n \"\"\"\n self.showInfos(select)\n self.showEtape()\n self.showStat()\n \n def showStat(self):\n \"\"\"\n Permet de calculer certaine statistiques sur la simulation\n \"\"\"\n \n # On récupère de quoi calculer les statistiques\n usersList = self.GUI.getNetworkFrame().getUserList()\n friendsList = self.GUI.getNetworkFrame().getFriendList()\n \n # On calcul le ratio des utilisateurs qui connaissent la rumeur\n knows = 0\n for user in usersList:\n if user.isKnowIt(self.GUI.getNetworkFrame().getCurrentRumeur()):\n knows += 1\n \n # On construit le message à afficher\n if len(usersList) > 0:\n toPrint = \"Nombre d'utilisateurs : \"+str(len(usersList))+\"\\n\"\n toPrint += \"Ratio de connaisseurs : \"+str(knows)+'/'+str(len(usersList))+\"\\n\"\n toPrint += \"Nombres d'amis moyen : \"+str(round(len(friendsList)/len(usersList), 2))+\"\\n\"\n toPrint += \"Nombres de rumeur total : \"+str(self.GUI.getNetworkFrame().getTotRumeur())+\"\\n\"\n toPrint += \"Rumeur affichée : \"+str(self.GUI.getNetworkFrame().getCurrentRumeur()+1)\n else:\n toPrint = \"Nombres de rumeur total : \"+str(self.GUI.getNetworkFrame().getTotRumeur())+\"\\n\"\n toPrint += \"Rumeur affichée : \"+str(self.GUI.getNetworkFrame().getCurrentRumeur()+1)\n \n self.stats['text'] = toPrint\n \n def showEtape(self):\n \"\"\"\n Affiche le numéro de l'étape en cours\n \"\"\"\n self.etapes['text'] = \"Nombre de cycle :\\n\"+str(self.GUI.getControlFrame().getEtape())\n \n def showInfos(self, select):\n \"\"\"\n Affiche le nom de l'utilisateur ainsi que la rumeur qu'il connait\n \"\"\"\n toPrint = \"\"\n if select == None:\n toPrint += \"Pas d'utilisateurs sélectionnée\"\n elif isinstance(select, Person): # On sélectionne un utilisateur\n toPrint += \"Nom de l'utilisateur :\\n\"+select.getName()+\"\\n\\n\"\n if select.isKnowIt(self.GUI.getNetworkFrame().getCurrentRumeur()):\n toPrint += \"Rumeur qu'il connait :\\n\"+select.getRumeur(\n self.GUI.getNetworkFrame().getCurrentRumeur()).upper()\n else:\n toPrint += \"! Il ne connait pas la rumeur actuel !\"\n else: # On sélectionne un liens\n users = select.getUser()\n toPrint += users[0].getName() + \"\\net\\n\" + users[1].getName() + \"\\nsont ami(e)s\"\n self.infos['text'] = toPrint # On affiche\n","sub_path":"INFO-BA-1/Projet d'année/InfoFrame.py","file_name":"InfoFrame.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"75400016","text":"#Edited on May 10, 2017\r\n#Finished May 10, 2017\r\n\r\n#Get letter to be used for variant\r\n\r\ndef getLetter(prevLetter=\"\"):\r\n\r\n while True:\r\n\r\n letter = input(\"Letter: \").lower()\r\n\r\n if letter.isalpha():\r\n\r\n if len(letter) == 1:\r\n\r\n if letter != prevLetter:\r\n\r\n print(\"Letter chosen and it is {}\".format(letter.upper()))\r\n return letter\r\n\r\n else:\r\n\r\n print(\"\\n{} is already used for the first trait\".format(prevLetter.upper()))\r\n\r\n else:\r\n\r\n print(\"Letter is too long\")\r\n\r\n else:\r\n\r\n print(\"That\\'s not a letter\")\r\n \r\n\r\n#Define a function that gets the mode for the two parts of the variant\r\n\r\ndef getTrait(letter):\r\n \r\n HomoDominant = letter.upper() + letter.upper()\r\n HomoRecessive = letter.lower() + letter.lower()\r\n Heterozygous = letter.upper() + letter.lower()\r\n\r\n choices = {1:\"Homozygous Dominant\", 2:\"Homozygous Recessive\", 3:\"Heterozygous\"}\r\n choices2 = {1:HomoDominant, 2:HomoRecessive, 3:Heterozygous}\r\n\r\n for i in choices:\r\n\r\n print(\"{} : {} -> {}\".format(i, choices[i], choices2[i]))\r\n\r\n while True:\r\n\r\n mode = input(\"Mode: \")\r\n\r\n if mode.isnumeric():\r\n\r\n if len(mode) == 1:\r\n\r\n if mode == \"1\":\r\n\r\n print(\"Homozygous dominant chosen.\")\r\n return HomoDominant\r\n\r\n elif mode == \"2\":\r\n\r\n print(\"Homozygous recessive chosen\")\r\n return HomoRecessive\r\n\r\n elif mode == \"3\":\r\n\r\n print(\"Heterozygous chosen.\")\r\n return Heterozygous\r\n\r\n else:\r\n\r\n print(\"Chosen number does not correspond to a choice.\")\r\n\r\n else:\r\n\r\n print(\"Chosen number does not correspond to a choice.\")\r\n\r\n else:\r\n\r\n print(\"Chosen mode is not a number.\")\r\n \r\ndef makeBoard(modeFirst, modeSecond):\r\n\r\n #Board list\r\n board = []\r\n #Variable Assignment for vertical\r\n v_one = modeFirst[0] + modeFirst[2]\r\n v_two = modeFirst[0] + modeFirst[3]\r\n v_three = modeFirst[1] + modeFirst[2]\r\n v_four = modeFirst[1] + modeFirst[3]\r\n #Variable Assignment for horizontal\r\n h_one = modeSecond[0] + modeSecond[2]\r\n h_two = modeSecond[0] + modeSecond[3]\r\n h_three = modeSecond[1] + modeSecond[2]\r\n h_four = modeSecond[1] + modeSecond[3]\r\n #Dictionary assignment for appending\r\n combinationsDictionary = {1:v_one + h_one, 2:v_one + h_two, 3:v_one + h_three, 4:v_one + h_four,\r\n 5:v_two + h_one, 6:v_two + h_two, 7:v_two + h_three, 8:v_two + h_four,\r\n 9:v_three + h_one, 10:v_three + h_two, 11:v_three + h_three, 12:v_three + h_four,\r\n 13:v_four + h_one, 14:v_four + h_two, 15:v_four + h_three, 16:v_four + h_four\r\n }\r\n \r\n \r\n def arrange(x):\r\n\r\n def check(x, dex):\r\n\r\n if x[dex].isupper():\r\n \r\n box = x[dex] + x[dex + 2]\r\n return box\r\n \r\n else:\r\n \r\n box = x[dex + 2] + x[dex]\r\n return box\r\n\r\n arrangedOne = check(x, 0)\r\n arrangedTwo = check(x, 1)\r\n arrangedFinal = arrangedOne + arrangedTwo\r\n return arrangedFinal\r\n\r\n for i in combinationsDictionary:\r\n board.append(arrange(combinationsDictionary[i]))\r\n\r\n print(\"\"\"\r\n {0} {1} {2} {3}\r\n *------*------*------*------*\r\n {4} | {5} | {6} | {7} | {8} |\r\n *------*------*------*------*\r\n {9} | {10} | {11} | {12} | {13} |\r\n *------*------*------*------*\r\n {14} | {15} | {16} | {17} | {18} |\r\n *------*------*------*------*\r\n {19} | {20} | {21} | {22} | {23} |\r\n *------*------*------*------*\r\n \"\"\".format(h_one, h_two, h_three, h_four,\r\n v_one, board[0], board[1], board[2], board[3],\r\n v_two, board[4], board[5], board[6], board[7],\r\n v_three, board[8], board[9], board[10], board[11],\r\n v_four, board[12], board[13], board[14], board[15]))\r\n\r\n return board\r\n\r\ndef boardData(lOne, lTwo, board):\r\n\r\n def getPercent(x):\r\n if x == 1:\r\n return \"6.25%\"\r\n elif x == 2:\r\n return \"12.5%\"\r\n elif x == 3:\r\n return \"18.75%\"\r\n elif x == 4:\r\n return \"25%\"\r\n elif x == 5:\r\n return \"31.25%\"\r\n elif x == 6:\r\n return \"37.50%\"\r\n elif x == 7:\r\n return \"43.75%\"\r\n elif x == 8:\r\n return \"50%\"\r\n elif x == 9:\r\n return \"56.25%\"\r\n elif x == 10:\r\n return \"62.50%\"\r\n elif x == 11:\r\n return \"68.75%\"\r\n elif x == 12:\r\n return \"75%\"\r\n elif x == 13:\r\n return \"81.25%\"\r\n elif x == 14:\r\n return \"87.50%\"\r\n elif x == 15:\r\n return \"93.75%\"\r\n elif x == 16:\r\n return \"100%\"\r\n else:\r\n return \"0%\"\r\n\r\n dd = (lOne + lOne + lTwo + lTwo).upper()\r\n dh = (lOne + lOne).upper() + lTwo.upper() + lTwo.lower()\r\n rr = (lOne + lOne + lTwo + lTwo).lower()\r\n rh = (lOne + lOne).lower() + lTwo.upper() + lTwo.lower()\r\n dr = (lOne + lOne).upper() + (lTwo + lTwo).lower()\r\n rd = (lOne + lOne).lower() + (lTwo + lTwo).upper()\r\n hh = lOne.upper() + lOne.lower() + lTwo.upper() + lTwo.lower()\r\n hd = lOne.upper() + lOne.lower() + (lTwo + lTwo).upper()\r\n hr = lOne.upper() + lOne.lower() + (lTwo + lTwo).lower()\r\n\r\n ddCount = board.count(dd)\r\n dhCount = board.count(dh)\r\n rrCount = board.count(rr)\r\n rhCount = board.count(rh)\r\n drCount = board.count(dr)\r\n rdCount = board.count(rd)\r\n hhCount = board.count(hh)\r\n hdCount = board.count(hd)\r\n hrCount = board.count(hr)\r\n\r\n fullDominant = ddCount + dhCount + hhCount + hdCount\r\n halfDominant = drCount + hrCount\r\n halfRecessive = rhCount + rdCount\r\n fullRecessive = rrCount\r\n\r\n phenotypicList = [fullDominant, halfDominant, halfRecessive, fullRecessive]\r\n phenotypicList.sort()\r\n\r\n genotypicList = [ddCount, dhCount, rrCount, rhCount, drCount, rdCount, hhCount, hdCount, hrCount]\r\n genotypicList.sort()\r\n\r\n ddPercent = getPercent(ddCount)\r\n dhPercent = getPercent(dhCount)\r\n rrPercent = getPercent(rrCount)\r\n rhPercent = getPercent(rhCount)\r\n drPercent = getPercent(drCount)\r\n rdPercent = getPercent(rdCount)\r\n hhPercent = getPercent(hhCount)\r\n hdPercent = getPercent(hdCount)\r\n hrPercent = getPercent(hrCount)\r\n \r\n print(\"\"\"\r\n\r\nCount & Percentage\r\n\r\nPure Homozygous Dominant: {} - {}\r\nPure Homozygous Recessive: {} - {}\r\nPure Heterozygous: {} - {}\r\n\r\nHomozygous Dominant, Homozygous Recessive: {} - {}\r\nHomozygous Dominant, Heterozygous: {} - {}\r\n\r\nHomozygous Recessive, Homozygous Dominant: {} - {}\r\nHomozygous Recessive, Heterozygous: {} - {}\r\n\r\nHeterozygous, Homozygous Dominant: {} - {}\r\nHeterozygous, Homozygous Recessive: {} - {}\r\n\r\nPhenotypic Ratio: {}:{}:{}:{}\r\n\"\"\".format(ddCount, ddPercent, rrCount, rrPercent, hhCount, hhPercent,\r\n drCount, drPercent, dhCount, dhPercent,\r\n rdCount, rdPercent, rhCount, rhPercent,\r\n hdCount, hdPercent, hrCount, hrPercent,\r\n phenotypicList[3], phenotypicList[2], phenotypicList[1], phenotypicList[0]).replace(\":0\", \"\"))\r\n\r\n print(\"\"\"Genotypic Ratio: {}:{}:{}:{}:{}:{}:{}:{}:{}\r\n\"\"\".format(genotypicList[8], genotypicList[7], genotypicList[6], genotypicList[5],\r\n genotypicList[4], genotypicList[3], genotypicList[2], genotypicList[1],\r\n genotypicList[0]).replace(\":0\", \"\"))\r\n\r\ndef main():\r\n\r\n running = True\r\n\r\n while running:\r\n \r\n print(\"\\nPlease choose letter for first trait of the variants\")\r\n letterOne = getLetter()\r\n\r\n print(\"\\nPlease choose letter for second trait of the variants\")\r\n letterTwo = getLetter(letterOne)\r\n\r\n print(\"\\nInput value for first trait of first variant\")\r\n traitOne = getTrait(letterOne)\r\n\r\n print(\"\\nInput value for second trait of second variant\")\r\n traitTwo = getTrait(letterTwo)\r\n\r\n print(\"\\nInput value for first trait of second variant\")\r\n traitThree = getTrait(letterOne)\r\n\r\n print(\"\\nInput value for second trait of second variant\")\r\n traitFour = getTrait(letterTwo)\r\n\r\n variantOne = traitOne + traitTwo\r\n variantTwo = traitThree + traitFour\r\n\r\n print(\"\\n\\'{}\\' x \\'{}\\' \".format(variantOne, variantTwo))\r\n board = makeBoard(variantOne, variantTwo)\r\n boardData(letterOne, letterTwo, board)\r\n\r\n print(\"Process has ended\\nEither input Y to terminate or N to repeat\")\r\n answer = input(\"Y/N: \").lower()\r\n\r\n if answer == \"y\":\r\n\r\n print(\"\\n\\nGoodbye, press enter to exit\")\r\n input()\r\n exit()\r\n\r\n elif answer == \"n\":\r\n\r\n print(\"\\n\\nRepeating... Press enter to continue\")\r\n input()\r\n\r\n elif answer == \"zen\":\r\n\r\n print()\r\n import this\r\n input()\r\n exit()\r\n \r\n elif answer != \"y\" and \"n\" and \"zen\" and \"spook\":\r\n\r\n print(\"Invalid keyword\")\r\n\r\n#Main\r\nmain()\r\n","sub_path":"DihybridSquareGeneratorAlpha/Alpha1.1/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":9512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"384984296","text":"import numpy as np\nfrom numpy.testing import assert_allclose\nimport pandas as pd\n\nfrom ..stats import gelman_rubin, effective_n, geweke\n\n\nclass TestDiagnostics():\n good_rhat = 1.1\n\n def fake_trace(self, n_samples):\n \"\"\"\n Creates a fake trace with 3 variables and 2 chains\n \"\"\"\n alpha = np.repeat((1, 5, 10), n_samples)\n beta = np.repeat((1, 5, 1), n_samples)\n data = np.random.beta(alpha, beta).reshape(-1, n_samples//2)\n trace = pd.DataFrame(data.T, columns=['a', 'a', 'b', 'b', 'c', 'c'])\n return trace\n\n def test_gelman_rubin(self):\n \"\"\"Confirm Gelman-Rubin statistic is close to 1 for a large number of samples.\n Also checks the correct shape\"\"\"\n trace = self.fake_trace(1000)\n rhat = gelman_rubin(trace)\n assert all(1 / self.good_rhat < r < self.good_rhat for r in rhat.values)\n assert rhat.shape == (3,)\n\n def test_gelman_rubin_bad(self):\n \"\"\"Confirm Gelman-Rubin statistic is far from 1 for a small number of samples.\"\"\"\n trace = self.fake_trace(6)\n rhat = gelman_rubin(trace)\n assert not all(1 / self.good_rhat < r < self.good_rhat for r in rhat.values)\n\n def test_effective_n(self):\n n_samples = 1000\n trace = self.fake_trace(n_samples)\n eff_n = effective_n(trace)\n assert_allclose(eff_n, n_samples, 2)\n assert eff_n.shape == (3,)\n\n def test_geweke(self):\n trace = self.fake_trace(1000)\n gw_stat = geweke(trace)\n assert max(abs(gw_stat['a'][:, 1])) < 1\n assert max(abs(gw_stat['a'][:, 0])) > -1\n","sub_path":"arviz/tests/test_diagnostics.py","file_name":"test_diagnostics.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"162786222","text":"#Maddy Chan 12/3/15\n#InterviewBit\n#Find out the maximum sub-array of non negative numbers from an array.\n#The sub-array should be continuous. Maximum sub-array is defined in\n#terms of the sum of the elements in the sub-array. Sub-array A is\n#greater than sub-array B if sum(A) > sum(B).\n#If there is a tie, then compare with segment's length and return\n#which has maximum length. If there is still a tie, then return\n#the segment with minimum starting index\n\ndef maxset(A):\n answers = []\n currentStart = 0\n #take all subarrays with positive numbers\n for i in range(len(A)):\n if A[i] < 0: \n if i > currentStart:\n answers.append(A[currentStart:i])\n currentStart = i+1\n if i == len(A)-1 and i >= currentStart:\n answers.append(A[currentStart:i+1])\n #filter for the ones with the biggest sum\n maxSum = 0\n maxLists = []\n for a in answers:\n if sum(a) > maxSum:\n maxSum = sum(a)\n maxLists = [a]\n elif sum(a) == maxSum:\n maxLists.append(a)\n #filter for the ones with the largest length\n answer = []\n for a in maxLists:\n if len(a) > len(answer):\n answer = a\n return answer\n\n\n\nprint(maxset([76546,-1,-2,-3,34524564563465]))\n","sub_path":"maxSet.py","file_name":"maxSet.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"178934755","text":"# -*- coding: utf-8 -*-\n\nfrom socket import *\nimport threading\nimport argparse\n\nlock = threading.Lock()\n\nopenNum = 0\nthreads = []\n\n\ndef portScanner(host, port):\n global openNum\n try:\n s = socket(AF_INET, SOCK_STREAM)\n s.connect_ex((host, port))\n\n # 防止输出混乱,输出之前要获取锁\n lock.acquire()\n openNum += 1\n print(\"[+] {} open\".format(port))\n\n # 输出之后释放锁\n lock.release()\n s.close()\n except:\n pass\n\n\ndef main():\n p = argparse.ArgumentParser(description='Port scanner!.')\n p.add_argument('-H', dest='hosts', type=str)\n args = p.parse_args()\n hostList = args.hosts.split(',')\n setdefaulttimeout(1)\n\n for host in hostList:\n print('Scanning the host:{}'.format(host))\n\n for p in range(1, 1024):\n # 创建线程\n t = threading.Thread(target=portScanner, args=('192.168.0.100', p))\n # 添加到线程列表\n threads.append(t)\n # 启动线程\n t.start()\n\n for t in threads:\n # join所完成的工作就是线程同步,即主线程任务结束之后,\n # 进入阻塞状态,一直等待其他的子线程执行结束之后,主线程在终止\n t.join()\n\n print('[*] The scan is completed!')\n print('[*] A total of {} open port'.format(openNum))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"learn_py/port_scan_learn/port_scan_with_thread.py","file_name":"port_scan_with_thread.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"247660779","text":"# -*- coding:utf-8 -*-\n__author__ = 'chen'\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom base.utils import DateUtil,MethodUtil as mtu\nfrom base.models import BasPurLog\nimport datetime,decimal,calendar,json\nimport xlwt3 as xlwt\nfrom django.views.decorators.cache import cache_page\n\ndef query():\n today = datetime.date.today()\n monthFirst = datetime.date.today().replace(day=1)\n\n if (str(today)[8:10] == '01'):\n monthFirst = datetime.date(datetime.date.today().year, datetime.date.today().month, 1)\n today = datetime.date(datetime.date.today().year, datetime.date.today().month, 1) - datetime.timedelta(days=1)\n todayStr = today.strftime('%y-%m-%d')\n monthFirstStr = str(monthFirst)\n\n shopTop = []\n shopTopTotal = {'shopid': '合计', 'shopname': ''}\n\n conn = mtu.getMysqlConn()\n cur = conn.cursor()\n # 月累计报损\n sqlMonthTotal = 'select shopid,shopname,sum(costvalue) costvalueSum,sum(lostvalue) lostvalueSum,(sum(lostvalue)/sum(costvalue)) lrateSum ' \\\n 'from KGshop17lost ' \\\n 'where ShopID!=\"C009\" AND sdate between \"' + monthFirstStr + '\" and \"' + todayStr + '\" ' \\\n 'group by shopid order by shopid '\n cur.execute(sqlMonthTotal)\n shopTop = cur.fetchall()\n\n # 每日报损\n sqlDaily = 'select sdate,shopid,costvalue,lostvalue,lrate ' \\\n 'from KGshop17lost ' \\\n 'where ShopID!=\"C009\" AND sdate between \"' + monthFirstStr + '\" and \"' + todayStr + '\" ' \\\n 'order by sdate '\n cur.execute(sqlDaily)\n listDaily = cur.fetchall()\n # 计算纵向合计、格式化数据、拼接月累计报损和每日报损\n for obj1 in shopTop:\n obj1['lostvalueSum'] = float(obj1['lostvalueSum']) if obj1['lostvalueSum'] else 0\n if 'lostvalueSum' in shopTopTotal:\n shopTopTotal['lostvalueSum'] += obj1['lostvalueSum']\n else:\n shopTopTotal['lostvalueSum'] = obj1['lostvalueSum']\n\n obj1['costvalueSum'] = float(obj1['costvalueSum']) if obj1['costvalueSum'] else 0\n if 'costvalueSum' in shopTopTotal:\n shopTopTotal['costvalueSum'] += obj1['costvalueSum']\n else:\n shopTopTotal['costvalueSum'] = obj1['costvalueSum']\n\n obj1['lrateSum'] = str(float('%0.2f' % (obj1['lrateSum'] * 100))) + '%' if obj1['lrateSum'] else '0.00%'\n shopTopTotal['lrateSum'] = shopTopTotal['lostvalueSum'] / shopTopTotal['costvalueSum']\n shopTopTotal['lrateSum'] = str(float('%0.2f' % (shopTopTotal['lrateSum'] * 100))) + '%'\n for obj2 in listDaily:\n date = str(obj2['sdate'])[8:10]\n if obj1['shopid'] == obj2['shopid']:\n obj1['costvalue_' + date] = float('%0.2f' % obj2['costvalue']) if obj2['costvalue'] else 0\n if 'costvalue_' + date in shopTopTotal:\n shopTopTotal['costvalue_' + date] += obj1['costvalue_' + date]\n shopTopTotal['costvalue_' + date] = float('%0.2f' % shopTopTotal['costvalue_' + date])\n else:\n shopTopTotal['costvalue_' + date] = obj1['costvalue_' + date]\n\n obj1['lostvalue_' + date] = float('%0.2f' % obj2['lostvalue']) if obj2['lostvalue'] else 0\n if 'lostvalue_' + date in shopTopTotal:\n shopTopTotal['lostvalue_' + date] += obj1['lostvalue_' + date]\n shopTopTotal['lostvalue_' + date] = float('%0.2f' % shopTopTotal['lostvalue_' + date])\n else:\n shopTopTotal['lostvalue_' + date] = obj1['lostvalue_' + date]\n\n obj1['lrate_' + date] = str(float(obj2['lrate'] * 100)) + '%' if obj2['lrate'] else '0.00%'\n shopTopTotal['lrate_' + date] = (shopTopTotal['lostvalue_' + date] / shopTopTotal['costvalue_' + date])\n shopTopTotal['lrate_' + date] = str(float('%0.2f' % (shopTopTotal['lrate_' + date] * 100))) + '%'\n\n TotalDict = {'shopTopTotal': shopTopTotal}\n return locals()\n\n@cache_page(60*60*4,key_prefix='daily_fruit_lost')\ndef inidex(request):\n yesterday = datetime.date.today() - datetime.timedelta(days=1)\n qtype = mtu.getReqVal(request,\"qtype\",\"1\")\n\n # 操作日志\n if not qtype:\n qtype = \"1\"\n key_state = mtu.getReqVal(request, \"key_state\", '')\n if qtype == '2' and (not key_state or key_state != '2'):\n qtype = '1'\n path = request.path\n today = datetime.datetime.today();\n ucode = request.session.get(\"s_ucode\")\n uname = request.session.get(\"s_uname\")\n BasPurLog.objects.create(name=\"超市水果报损率\", url=path, qtype=qtype, ucode=ucode,uname=uname, createtime=today)\n\n if qtype== \"1\":\n data = query()\n return render(request,'report/daily/fruit_lost.html',data)\n else:\n fname = yesterday.strftime(\"%m.%d\") + \"_daily_fruitLost.xls\"\n return export(fname)\n\nimport base.report.Excel as excel\ndef export(fname):\n if not excel.isExist(fname):\n data = query()\n createExcel(fname,data)\n res = {}\n res['fname'] = fname\n return HttpResponse(json.dumps(res))\ndef createExcel(fname,data):\n wb = xlwt.Workbook(encoding='utf-8',style_compression=0)\n #写入sheet1\n writeDataToSheet1(wb,data['shopTop'],data['TotalDict'])\n excel.saveToExcel(fname,wb)\n\n\ndef writeDataToSheet1(wb,shopTop,TotalDict):\n date = DateUtil.get_day_of_day(-1)\n year = date.year\n month = date.month\n lastDay = calendar.monthrange(year,month)[1]\n\n sheet = wb.add_sheet(\"(月)水果报损率日报\",cell_overwrite_ok=True)\n\n titles = [[(\"(%s月)水果报损率日报\" % month,0,1,15)],\n [(\"门店编号\",0,2,1),(\"门店名称\",1,2,1),(\"月累计报损\",2,1,3)],\n [('成本金额',2,1,1),('销售成本金额',3,1,1),('报损率',4,1,1),]\n ]\n\n keylist = ['shopid','shopname','lostvalueSum','costvalueSum','lrateSum']\n\n widthList = [600,1100,600,600,600,600]\n\n trow1 = titles[1]\n trow2 = titles[2]\n\n n = 5 #1日单元格开始位置\n for d in range(1,lastDay+1):\n trow1.append((str(d)+'日',n,1,3))\n trow2.append(('成本金额',n,1,1))\n trow2.append(('销售成本金额',n+1,1,1))\n trow2.append(('报损率',n+2,1,1))\n widthList.append(600)\n widthList.append(400)\n widthList.append(400)\n widthList.append(400)\n n += 3 #每日单元格数量\n dStr = '0'+str(d) if d<10 else str(d)\n keylist.append('lostvalue_'+dStr)\n keylist.append('costvalue_'+dStr)\n keylist.append('lrate_'+dStr)\n\n #日销售报表\n mtu.insertTitle2(sheet,titles,keylist,widthList)\n mtu.insertCell2(sheet,3,shopTop,keylist,None)\n titlesLen = len(titles)\n listTopLen = len(shopTop)\n mtu.insertSum2(sheet,keylist,titlesLen+listTopLen,TotalDict,2)\n\n\ndef formatDate(dict):\n for key in dict.keys():\n #转换数据格式\n obj = dict[key]\n if obj is None:\n dict[key] = '0'\n else:\n if isinstance(obj,decimal.Decimal):\n dict[key] = float('%0.4f'%dict[key])","sub_path":"base/report/daily/fruitLost.py","file_name":"fruitLost.py","file_ext":"py","file_size_in_byte":7303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"112043532","text":"from collections import Counter\n\n#===============================================\nclass NumDiapStat:\n def __init__(self):\n self.mMin, self.mMax = None, None\n self.mCntDef = 0\n self.mCntUndef = 0\n\n def isDefined(self):\n return self.mCntDef > 0\n\n def regValue(self, val):\n if val is None:\n self.mCntUndef += 1\n return\n self.mCntDef += 1\n if self.mCntDef == 1:\n self.mMin = self.mMax = val\n else:\n if val < self.mMin:\n self.mMin = val\n elif val > self.mMax:\n self.mMax = val\n\n def result(self):\n return [self.mMin, self.mMax, self.mCntDef, self.mCntUndef]\n\n#===============================================\nclass EnumStat:\n def __init__(self, variant_set):\n self.mVariantSet = variant_set\n self.mStat = Counter()\n\n def isDefined(self):\n for cnt in self.mStat.values():\n if cnt > 0:\n return True\n return False\n\n def regValues(self, values, count = 1):\n if not values:\n return\n for val in values:\n if not(0 <= val < len(self.mVariantSet)):\n continue\n assert 0 <= val < len(self.mVariantSet)\n self.mStat[val] += count\n\n def result(self):\n rep_list = []\n for idx, variant in enumerate(iter(self.mVariantSet)):\n rep_list.append([variant, self.mStat.get(idx, 0)])\n return [rep_list]\n","sub_path":"app/search/val_stat.py","file_name":"val_stat.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"14572931","text":"# Iterative and Bubble sorting assignment\n\n# In-place selection sort\ndef selection_sort(arr):\n # loop through n elements\n # Minus one because we don't need to sort the very last item, \n # it has already been sorted by the one before it\n for i in range(0, len(arr) -1):\n\n # Current index we are looking at, lowest index of the unsorted boundary\n boundary= i\n\n # Current value we are looking at, at the starting point of the unsorted boundary\n smallest_value = arr[boundary]\n\n # Current index of the lower end of the boundary\n smallest_index = boundary\n\n # Find the smallest element in the unsorted portion of the array\n # Unsorted array range is from the boundary line \n # (which we are moving by 1 on each iteration of the first for loop)\n # to the end of the array\n for unsorted_index in range(boundary, len(arr)):\n # Iterate through the unsorted portion of the array and find the smallest value and its index location\n # Save that as the smallest value and smallest index\n if arr[unsorted_index] < smallest_value:\n smallest_value = arr[unsorted_index]\n smallest_index = unsorted_index\n \n # After iterating through all of the unsorted numbers and finding the smallest one,\n # Swap the found smallest value with the value at the begining of the boundary\n arr[boundary], arr[smallest_index] = arr[smallest_index], arr[boundary]\n\n # Then it will loop through on the next index of the whole array\n\n # When it has gone through the entire array, return the now sorted array\n return arr\n\n\ndef bubble_sort(arr):\n '''\n Completed this thinking a bubble sort acted differently. This method compares n item \n to the item next to it. If they need to be swapped, they swap and then start over from the begining.\n Only if it doesn't need to be swapped does it move on to the next item.\n '''\n\n # # Start at index 0 and iterate through each item in array\n # # Compare element n to its next element.\n # # If the next element is less than the first element, swap them and start back at index 0\n\n # # Don't need to look at the last \n # for i in range(len(arr)-1):\n # # Compare to the next item in the array\n # # If the next value is less than the first value, swap them and start over\n # if arr[i+1] < arr[i]:\n # arr[i], arr[i +1] = arr[i+1], arr[i]\n # bubble_sort(arr)\n\n # return arr\n\n\n '''\n This method compares each item to its next, walking through the entire array before starting over.\n '''\n # Go through the array except for the last item, that will have already been sorted\n for i in range(len(arr) - 1):\n # With each index position, traverse through the array that has not been sorted yet\n # The last i items have already been sorted\n for j in range(len(arr) - i - 1):\n # Compare the values, if the next is less than the current, swap them\n if arr[j] > arr[j+1]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n # Return the array\n return arr\n\n\n'''\nSTRETCH: implement the Counting Sort function below\n\nCounting sort is a sorting algorithm that works on a set of data where\nwe specifically know the maximum value that can exist in that set of\ndata. The idea behind this algorithm then is that we can create \"buckets\"\nfrom 0 up to the max value. This is most easily done by initializing an\narray of 0s whose length is the max value + 1 (why do we need this \"+ 1\"?).\n\nEach buckets[i] then is responsible for keeping track of how many times \nwe've seen `i` in the input set of data as we iterate through it.\nOnce we know exactly how many times each piece of data in the input set\nshowed up, we can construct a sorted set of the input data from the \nbuckets. \n\nWhat is the time and space complexity of the counting sort algorithm?\n'''\ndef counting_sort(arr, maximum=None):\n # Your code here\n\n\n return arr\n","sub_path":"src/iterative_sorting/iterative_sorting.py","file_name":"iterative_sorting.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"373320334","text":"import numpy as np\nfrom mailFilter_function import *\nimport matplotlib.pyplot as plt\nfrom sklearn import svm\nfrom collections import OrderedDict # 項目が追加された順序を記憶する辞書のサブクラス\nimport re #正規表現操作\nimport string #一般的な文字列操作\nfrom nltk import stem #Natural Language Toolkit付属の語幹分析ライブラリ群\nimport glob\nimport os\n\ndataPath = os.path.join(os.path.dirname(__file__), \"vocab.txt\")\nenronDir = \"C:\\\\Users\\\\lisc2m\\\\Downloads\\\\bootcampData\\\\step6\\\\\"\n\nif os.path.isfile(dataPath) == False:\n\n print(\"hamデータをロードします\")\n ham = []\n\n for file_name in glob.glob(enronDir + 'ham\\\\*.txt'):\n with open(file_name, 'r', errors='ignore') as file:\n ham_tmp = file.readlines()\n ham.extend(stemmingEmail(preprocess(ham_tmp)))\n print(file_name + \" end\")\n\n print(\"hamの語彙の延べ数は\",end=\"\")\n print(len(ham))\n\n print(\"spamデータをロードします\")\n spam = []\n\n for file_name in glob.glob(enronDir + '\\spam\\\\*.txt'):\n with open(file_name, 'r', errors='ignore') as file:\n spam_tmp = file.readlines()\n spam.extend(stemmingEmail(preprocess(spam_tmp)))\n print(file_name + \" end\")\n\n print(\"spamの語彙の延べ数は\",end=\"\")\n print(len(spam))\n\n print(\"語彙データの生成を行います\")\n\n # ham と spam を結合し、重複を削除\n all_data = np.r_[ham, spam]\n all_word_unique = np.unique(all_data)\n\n # 各語幹をインデックス付け\n word_idx = range(all_word_unique.size)\n vocab_list = np.c_[word_idx, all_word_unique]\n print(\"vocab_list.shape: \", end=\"\")\n print(vocab_list.shape)\n\n # セーブ\n np.savetxt(dataPath, vocab_list, delimiter=\"\\t\", fmt=\"%s\")\n\ntrainDataPath = os.path.join(os.path.dirname(__file__), \"trainData.npz\")\ntestDataPath = os.path.join(os.path.dirname(__file__), \"testData.npz\")\n\nprint(\"データベースの事前処理を行います。\\n\")\nprint(\"vocabデータをロードします\")\nvocabList = getVocabList(dataPath)\nn = len(vocabList)\nprint(\"len(vocablist): \",end=\"\")\nprint(n)\n\nprint(\"hamデータをロードします\")\nham_everyFile = []\nfor file_name in glob.glob(enronDir + 'ham\\\\*.txt'):\n with open(file_name, 'r', errors='ignore') as file:\n ham_tmp = file.readlines()\n ham_everyFile.append(ham_tmp)\nprint(\"hamのファイルの数は\",end=\"\")\nm_ham = len(ham_everyFile)\nprint(m_ham)\n\nprint(\"spamデータをロードします\")\nspam_everyFile = []\nfor file_name in glob.glob(enronDir + 'spam\\\\*.txt'):\n with open(file_name, 'r', errors='ignore') as file:\n spam_tmp = file.readlines()\n spam_everyFile.append(spam_tmp)\nprint(\"spamのファイルの数は\",end=\"\")\nm_spam = len(spam_everyFile)\nprint(m_spam)\n\nprint(\"index化して存在する語の番号の要素を1にします\")\nprint(\"まずはhamデータから。\")\nX_ham = np.empty((m_ham, n), dtype=np.bool)\nfor i in range(m_ham):\n word_indices = processEmail(preprocess(ham_everyFile[i]), vocabList, showResult=0)\n features = emailFeatures(word_indices, n)\n X_ham[i,:] = features\n print(i, end=\" \")\n\nprint(\"次にspamデータ。\")\nX_spam = np.empty((m_spam, n),dtype=np.bool)\nfor i in range(m_spam):\n word_indices = processEmail(preprocess(spam_everyFile[i]), vocabList, showResult=0)\n features = emailFeatures(word_indices, n)\n X_spam[i,:] = features\n print(i, end=\" \")\n\nprint(\"spam(y=1), ham(y=0)のフラグを立てます\")\ny_ham = np.zeros(m_ham, dtype=np.bool)\ny_spam = np.ones(m_spam, dtype=np.bool)\n\nprint(\"spamデータ, hamデータを統合してシャッフルします\")\nX_all = np.r_[X_ham, X_spam]\ny_all = np.r_[y_ham, y_spam]\nshuffle_idx = np.random.permutation(m_ham + m_spam)\n\nprint(\"TrainデータとTestデータに分離、保存\")\nX = X_all[shuffle_idx[:(m_ham + m_spam) * 7//10],:]\ny = y_all[shuffle_idx[:(m_ham + m_spam) * 7//10]]\nXtest = X_all[shuffle_idx[(m_ham + m_spam) * 7//10:],:]\nytest = y_all[shuffle_idx[(m_ham + m_spam) * 7//10:]]\n\nprint(\"X.shape: \", X.shape)\nprint(\"y.shape: \", y.shape)\nprint(\"Xtest.shape: \", Xtest.shape)\nprint(\"ytest.shape: \", ytest.shape)\n\nnp.savez(trainDataPath, X=X, y=y)\nnp.savez(testDataPath,Xtest=Xtest, ytest=ytest)","sub_path":"MachineLearning/SVM/mailFilter_preprocess.py","file_name":"mailFilter_preprocess.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"183584887","text":"from django.core.exceptions import ImproperlyConfigured\nfrom django.conf import settings\n\n\nclass CoreUtils(object):\n @classmethod\n def get_default_page_size(cls, key='DEFAULT_PAGE_SIZE'):\n '''\n functions to get default page size\n '''\n try:\n return getattr(settings, key)\n except Exception as exc:\n raise ImproperlyConfigured('%s is required' % key)\n\n @classmethod\n def get_default_page_index(cls, key='DEFAULT_PAGE_INDEX'):\n '''\n functions to get default page index\n '''\n try:\n return getattr(settings, key)\n except Exception as exc:\n raise ImproperlyConfigured('%s is required' % key)\n\n @classmethod\n def get_start_end_index(cls, page, limit):\n '''\n get start and end limit based on a pageIndex and pageSize\n '''\n start = page*limit\n end = start+limit\n return start, end, page, limit\n","sub_path":"core/utils/utls.py","file_name":"utls.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"485768210","text":"import tensorflow as tf\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.training import moving_averages\n\nimport math\n\ndef _get_variable(name, shape, initializer, weight_decay=0.0,\n dtype='float', trainable=True):\n if weight_decay > 0:\n regularizer = tf.contrib.layers.l2_regularizer(weight_decay)\n else:\n regularizer = None\n collections = [tf.GraphKeys.VARIABLES, 'VGG_VARIABLE']\n return tf.get_variable(name, shape=shape, initializer=initializer, dtype=dtype,\n regularizer=regularizer, collections=collections, trainable=trainable)\n\ndef _conv(x, filter_out, ksize=3, stride=1, padding='SAME', bias=True, data_format='NHWC', scope_name='Conv2D'):\n with tf.variable_scope(scope_name):\n filter_in = x.get_shape()[-1] if data_format=='NHWC' else x.get_shape()[1]\n #kernel_init_std = math.sqrt(tf.convert_to_tensor(2.0)/(ksize*ksize*filter_in))\n kernel_init_std = tf.sqrt(2.0/(tf.convert_to_tensor(ksize*ksize,dtype=tf.float32)*tf.to_float(filter_in)))\n initializer = tf.truncated_normal_initializer(mean=0.0, stddev=kernel_init_std)\n kernel = _get_variable('Weight', shape=[ksize, ksize, filter_in, filter_out],\n initializer=initializer)\n tf.add_to_collection('Weights', kernel)\n if data_format =='NCHW':\n y = tf.nn.conv2d(x, kernel, [1, 1, stride, stride], padding=padding, data_format='NCHW')\n else:\n y = tf.nn.conv2d(x, kernel, [1, stride, stride, 1], padding=padding, data_format='NHWC')\n\n if bias:\n bias = _get_variable('Bias', shape=[filter_out],\n initializer=tf.constant_initializer(0.0))\n if data_format == 'NCHW':\n y = tf.nn.bias_add(y, bias, data_format='NCHW')\n else:\n y = tf.nn.bias_add(y, bias, data_format='NHWC')\n return y\n\ndef _relu(x):\n return tf.nn.relu(x)\n\ndef _max_pooling(x, ksize=2, stride=2, padding='SAME', data_format='NHWC', scope_name='MaxPool'):\n\n with tf.variable_scope(scope_name):\n if data_format=='NCHW':\n pool = tf.nn.max_pool(x, [1, 1, ksize, ksize], [1, 1, stride, stride], padding=padding, data_format='NCHW')\n else:\n pool = tf.nn.max_pool(x, [1, ksize, ksize, 1], [1, stride, stride, 1], padding=padding, data_format='NHWC')\n\n return pool\n\ndef _batchnorm(x, is_training=None, moving_avg_decay=0.9997, batchnorm_epsilon=0.001, bias=True, scope_name='BatchNorm'):\n\n with tf.variable_scope(scope_name):\n x_shape = x.get_shape()\n params_shape = x_shape[-1:]\n\n if bias:\n bias =_get_variable('Bias', params_shape,\n initializer=tf.zeros_initializer)\n return x + bias\n\n axis = list(range(len(x_shape) - 1))\n\n beta = _get_variable('Beta',\n params_shape,\n initializer=tf.zeros_initializer)\n gamma = _get_variable('Gamma',\n params_shape,\n initializer=tf.ones_initializer)\n\n moving_mean = _get_variable('Moving_mean',\n params_shape,\n initializer=tf.zeros_initializer,\n trainable=False)\n moving_variance = _get_variable('Moving_variance',\n params_shape,\n initializer=tf.ones_initializer,\n trainable=False)\n\n # These ops will only be preformed when training.\n mean, variance = tf.nn.moments(x, axis)\n update_moving_mean = moving_averages.assign_moving_average(moving_mean,\n mean, moving_avg_decay)\n update_moving_variance = moving_averages.assign_moving_average(\n moving_variance, variance, moving_avg_decay)\n tf.add_to_collection('BatchNorm', update_moving_mean)\n tf.add_to_collection('BatchNorm', update_moving_variance)\n\n mean, variance = control_flow_ops.cond(\n is_training, lambda: (mean, variance),\n lambda: (moving_mean, moving_variance))\n\n x = tf.nn.batch_normalization(x, mean, variance, beta, gamma, batchnorm_epsilon)\n # x.set_shape(inputs.get_shape()) ??\n\n return x\n\ndef _linear(x, filter_out, bias=True, scope_name='Linear'):\n\n with tf.variable_scope(scope_name):\n filter_in = x.get_shape()[1]\n weight_init_std = math.sqrt(1.0 / filter_out)\n weight_initializer = tf.truncated_normal_initializer(mean=0.0, stddev=weight_init_std)\n weight = _get_variable('Weight', shape=[filter_in, filter_out], initializer=weight_initializer)\n tf.add_to_collection('Weights', weight)\n y = tf.matmul(x, weight)\n if bias:\n bias = _get_variable('Bias', shape=[filter_out],\n initializer=tf.constant_initializer(0.0))\n tf.add_to_collection('Biases', bias)\n y = y + bias\n return y\n\ndef _stack(x, num_blocks, filter_internal, stack_stride, is_training=None,\n bottleneck=True, data_format='NHWC', scope_name=None):\n for n in range(num_blocks):\n with tf.variable_scope(scope_name):\n stride = stack_stride if n == 0 else 1\n ksize = 3\n\n x = _residual_block(x, filter_internal, ksize, stride,\n data_format=data_format,\n bottleneck=bottleneck,\n is_training=is_training,\n scope_name=scope_name)\n return x\n\n\ndef _residual_block(x, filter_internal,\n ksize=3, stride=1,\n data_format = 'NHWC',\n is_training = None,\n bottleneck=True, scope_name=None):\n\n m = 4 if bottleneck else 1\n filter_out = m * filter_internal\n filter_in = x.get_shape()[-1] if data_format == 'NHWC' else x.get_shape()[1]\n\n shortcut = x\n\n conv_filter_out = filter_internal\n\n if bottleneck:\n with tf.variable_scope('conv2d_1'):\n\n x = _conv(x, conv_filter_out, ksize=1, stride=stride,\n padding='SAME', data_format=data_format)\n x = _batchnorm(x, is_training=is_training)\n x = _relu(x)\n\n with tf.variable_scope('conv2d_2'):\n x = _conv(x, conv_filter_out, ksize=3, stride=1,\n padding='SAME', data_format=data_format)\n x = _batchnorm(x, is_training=is_training)\n x = _relu(x)\n\n with tf.variable_scope('conv2d_3'):\n x = _conv(x, filter_out, ksize=1, stride=1,\n padding='SAME', data_format=data_format)\n x = _batchnorm(x, is_training=is_training)\n else:\n with tf.variable_scope('conv2d_1'):\n x = _conv(x, conv_filter_out, ksize=3, stride=stride,\n padding='SAME', data_format=data_format)\n x = _batchnorm(x,is_training=is_training)\n x = _relu(x)\n with tf.variable_scope('conv2d_2'):\n x = _conv(x, conv_filter_out, ksize=3, stride=1,\n padding='SAME', data_format=data_format)\n x = _batchnorm(x, is_training=is_training)\n with tf.variable_scope('shortcut'):\n if filter_out != filter_in or stride != 1:\n shortcut = _conv(x, filter_out, ksize=1, stride=stride,\n padding='SAME',data_format=data_format)\n shortcut = _batchnorm(shortcut,is_training=is_training)\n\n return _relu(x+shortcut)\n","sub_path":"ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":7774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"242205160","text":"import os\r\n\r\nfile_dir = '/home/share2/BU101/images/'\r\nfilename = '/home/share2/BU101/train_bu101.txt'\r\nwith open(filename, 'w') as file_to_read:\r\n for root, dirs, files in os.walk(file_dir):\r\n for pic in files:\r\n # print('root_dir:', root) # 当前目录路径\r\n # print('files:', pic) # 当前路径下所有非目录子文件\r\n cls=pic.split('_')[0]\r\n line = cls + '/' + pic\r\n file_to_read.write(line)\r\n file_to_read.write(\"\\n\")\r\n\r\nprint(\"bu101train filelist established\")","sub_path":"data_tools/bu101/build_filelist.py","file_name":"build_filelist.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"496606282","text":"#!/usr/bin/env python2\n\n# Copyright (c) 2017 Public Library of Science\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n\n\"\"\"\nBase class for Rhino Ingestibles JSON related services\n\"\"\"\n\n__author__ = 'msingh@plos.org'\n\nfrom ...Base.Config import API_BASE_URL\nfrom ingestion_json import Ingestion\n\nINGESTIBLES_API = API_BASE_URL + '/ingestibles'\nDEFAULT_HEADERS = {'Accept': 'application/json'}\nHEADER = '-H'\n\nOK, CREATED, BAD_REQUEST, UNAUTHORIZED, FORBIDDEN, NOT_FOUND, NOT_ALLOWED = 200, 201, 400, 401, 403, 404, 405\n\nclass IngestiblesJson(Ingestion):\n\n def get_ingestibles(self):\n self.doGet(INGESTIBLES_API, None, headers=DEFAULT_HEADERS)\n self.parse_response_as_json()\n\n def post_ingestibles(self, parse=True, **kwargs):\n self.doPost(INGESTIBLES_API, data=kwargs, headers=DEFAULT_HEADERS)\n if parse:\n self.parse_response_as_json()\n\n def verify_get_ingestibles(self, names=None):\n ingestibles = self.parsed.get_json(printvalue=False)\n if names:\n self.assertTrue( bool(ingestibles), \"result is not a valid array: %r\"%(ingestibles,))\n for name in names:\n self.assertIn(name, ingestibles, \"%r not found in result %r\"%(name, ingestibles))\n","sub_path":"test/api/RequestObject/ingestibles_json.py","file_name":"ingestibles_json.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"426521465","text":"# -*- coding: utf-8 -*-\n\nfrom resources.lib.const import Const\nfrom resources.lib.common import log\n\nimport random\nimport socket\nimport urllib\n\nfrom http.server import HTTPServer\nfrom http.server import SimpleHTTPRequestHandler\n\n\nclass LocalProxy(HTTPServer):\n\n # 文字セット\n CHARSET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'\n # キーの長さ\n LENGTH = 8\n\n def __init__(self):\n # ポート番号\n self.activeport = Const.GET('port')\n # ポート番号が取得できたらHTTPサーバを準備する\n if self.activeport:\n # ポートが利用可能か確認する\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n result = s.connect_ex(('127.0.0.1', int(self.activeport)))\n s.close()\n if result > 0:\n # アクティブなポート番号として保存\n Const.SET('activeport', self.activeport)\n # APIキー\n self.apikey = ''.join([LocalProxy.CHARSET[random.randrange(len(LocalProxy.CHARSET))] for i in range(LocalProxy.LENGTH)])\n # APIキーを保存\n Const.SET('apikey', self.apikey)\n # ログ\n log('apikey initialized: %s' % self.apikey)\n # HTTPサーバを初期化\n super().__init__(('', int(self.activeport)), LocalProxyHandler)\n else:\n # ポート番号が利用できない場合はローカルプロキシの設定変更を促す\n self.apikey = None\n # 通知メッセージ\n self.message = 'Local proxy port %s is busy' % self.activeport\n else:\n # ポート番号が取得できないインストール直後はKodiの再起動を促す\n self.apikey = None\n # 通知メッセージ\n self.message = 'Restart Kodi to enable local proxy'\n\n @staticmethod\n def abort():\n # ポート番号\n activeport = Const.GET('activeport')\n # APIキー\n apikey = Const.GET('apikey')\n # URLを生成\n abort_url = 'http://127.0.0.1:%s/abort;%s' % (activeport, apikey)\n # リクエスト\n res = urllib.request.urlopen(abort_url)\n data = res.read()\n res.close()\n return data\n\n @staticmethod\n def proxy(url='', headers={}):\n # ポート番号\n activeport = Const.GET('activeport')\n # APIキー\n apikey = Const.GET('apikey')\n # URLを生成\n params = {'_': url}\n params.update(headers)\n proxy_url = 'http://127.0.0.1:%s/proxy;%s?%s' % (activeport, apikey, urllib.parse.urlencode(params))\n return proxy_url\n\n @staticmethod\n def parse(proxy_url):\n # APIキー\n apikey = Const.GET('apikey')\n # ソースURLとリクエストヘッダの既定値\n url = proxy_url\n headers = {}\n # プロキシURLを展開\n parsed = urllib.parse.urlparse(proxy_url)\n # URLのパスとAPIキーが一致したらソースURLとリクエストヘッダを抽出する\n if parsed.path == '/proxy' and parsed.params == apikey:\n for key, val in urllib.parse.parse_qs(parsed.query, keep_blank_values=True).items():\n if key == '_':\n url = val[0]\n else:\n headers[key] = val[0]\n return url, headers\n\n\nclass LocalProxyHandler(SimpleHTTPRequestHandler):\n\n def do_HEAD(self):\n self.do_request()\n\n def do_GET(self):\n self.do_request()\n\n def log_message(self, format, *args):\n # デフォルトのログ出力を抑制する\n # format: '\"%s\" %s %s'\n # args: ('GET /abort;pBVVfZdW HTTP/1.1', '200', '-')\n return\n\n def do_respond(self, code, message):\n # レスポンスヘッダ\n self.send_response(code)\n self.end_headers()\n # レスポンスボディ\n if self.command == 'GET':\n # HTTPステータスを返す\n data = '%d %s' % (code, message)\n self.wfile.write(data.encode())\n # ログ\n log('%s: %s' % (message, self.path))\n\n def do_request(self):\n try:\n # HTTPリクエストをパースする\n # リクエスト: GET /proxy;pBVVfZdW?x-radiko-authtoken=PYRk2tStPElKwPIQkPjJ4A&_=https%3A%2F%2Ff-radiko.smartstream.ne.jp%2FTBS%2F_definst_%2Fsimul-stream.stream%2Fplaylist.m3u HTTP/1.1\"\n # パース結果: ParseResult(scheme='', netloc='', path='/proxy', params='pBVVfZdW', query='x-radiko-authtoken=PYRk2tStPElKwPIQkPjJ4A&_=https%3A%2F%2Ff-radiko.smartstream.ne.jp%2FTBS%2F_definst_%2Fsimul-stream.stream%2Fplaylist.m3u', fragment='')\n parsed = urllib.parse.urlparse(self.path)\n # APIキーをチェック\n if parsed.params == self.server.apikey:\n # パスに応じて処理\n if parsed.path == '/proxy':\n # クエリを展開\n url, headers = LocalProxy.parse(self.path)\n # レスポンス\n if url:\n # レスポンスヘッダ(OK)\n self.send_response(200)\n self.end_headers()\n # レスポンスボディ\n if self.command == 'GET':\n req = urllib.request.Request(url, headers=headers)\n data = urllib.request.urlopen(req).read()\n self.wfile.write(data)\n # ログ\n log('forwarded to: %s' % url)\n else:\n self.do_respond(404, 'Not Found')\n elif parsed.path == '/abort':\n # レスポンス\n self.do_respond(200, 'OK')\n # APIキーを削除\n self.server.apikey = ''\n elif parsed.path == '/hello':\n # レスポンス\n self.do_respond(200, 'OK')\n else:\n self.do_respond(404, 'Not Found')\n else:\n self.do_respond(403, 'Forbidden')\n except Exception:\n self.do_respond(500, 'Internal Server Error')\n","sub_path":"resources/lib/localproxy.py","file_name":"localproxy.py","file_ext":"py","file_size_in_byte":6401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"93157802","text":"\"\"\"Netgear LTE platform for notify component.\n\nFor more details about this platform, please refer to the documentation at\nhttps://home-assistant.io/components/notify.netgear_lte/\n\"\"\"\n\nimport voluptuous as vol\nimport attr\n\nfrom homeassistant.components.notify import (\n BaseNotificationService, ATTR_TARGET, PLATFORM_SCHEMA)\nfrom homeassistant.const import CONF_HOST\nimport homeassistant.helpers.config_validation as cv\n\nfrom ..netgear_lte import DATA_KEY\n\n\nDEPENDENCIES = ['netgear_lte']\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Optional(CONF_HOST): cv.string,\n vol.Required(ATTR_TARGET): vol.All(cv.ensure_list, [cv.string]),\n})\n\n\nasync def async_get_service(hass, config, discovery_info=None):\n \"\"\"Get the notification service.\"\"\"\n modem_data = hass.data[DATA_KEY].get_modem_data(config)\n phone = config.get(ATTR_TARGET)\n return NetgearNotifyService(modem_data, phone)\n\n\n@attr.s\nclass NetgearNotifyService(BaseNotificationService):\n \"\"\"Implementation of a notification service.\"\"\"\n\n modem_data = attr.ib()\n phone = attr.ib()\n\n async def async_send_message(self, message=\"\", **kwargs):\n \"\"\"Send a message to a user.\"\"\"\n targets = kwargs.get(ATTR_TARGET, self.phone)\n if targets and message:\n for target in targets:\n await self.modem_data.modem.sms(target, message)\n","sub_path":"homeassistant/components/notify/netgear_lte.py","file_name":"netgear_lte.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"494216948","text":"from collections import Counter, defaultdict, OrderedDict, deque\nfrom bisect import bisect_left, bisect_right\nfrom functools import reduce, lru_cache\nfrom typing import List\nimport itertools\nimport math\nimport heapq\nimport string\ntrue = True\nfalse = False\nMIN, MAX, MOD = -0x3f3f3f3f, 0x3f3f3f3f, 1000000007\n#\n# @lc app=leetcode id=1508 lang=python3\n#\n# [1508] Range Sum of Sorted Subarray Sums\n#\n# https://leetcode.com/problems/range-sum-of-sorted-subarray-sums/description/\n#\n# algorithms\n# Medium (75.12%)\n# Total Accepted: 5K\n# Total Submissions: 6.7K\n# Testcase Example: '[1,2,3,4]\\n4\\n1\\n5'\n#\n# Given the array nums consisting of n positive integers. You computed the sum\n# of all non-empty continous subarrays from the array and then sort them in\n# non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.\n#\n# Return the sum of the numbers from index left to index right (indexed from\n# 1), inclusive, in the new array. Since the answer can be a huge number return\n# it modulo 10^9 + 7.\n#\n#\n# Example 1:\n#\n#\n# Input: nums = [1,2,3,4], n = 4, left = 1, right = 5\n# Output: 13\n# Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After\n# sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5,\n# 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3\n# + 3 + 4 = 13.\n#\n#\n# Example 2:\n#\n#\n# Input: nums = [1,2,3,4], n = 4, left = 3, right = 4\n# Output: 6\n# Explanation: The given array is the same as example 1. We have the new array\n# [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to\n# ri = 4 is 3 + 3 = 6.\n#\n#\n# Example 3:\n#\n#\n# Input: nums = [1,2,3,4], n = 4, left = 1, right = 10\n# Output: 50\n#\n#\n#\n# Constraints:\n#\n#\n# 1 <= nums.length <= 10^3\n# nums.length == n\n# 1 <= nums[i] <= 100\n# 1 <= left <= right <= n * (n + 1) / 2\n#\n#\n#\n\n\nclass Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:\n hp = [(n, i) for i, n in enumerate(nums)]\n heapq.heapify(hp)\n ans = 0\n for i in range(1, right + 1):\n _n, idx = heapq.heappop(hp)\n if i >= left:\n ans += _n\n if idx + 1 < n:\n heapq.heappush(hp, (_n + nums[idx + 1], idx + 1))\n return ans % MOD\n\n\nsol = Solution()\nnums = [1, 2, 3, 4]\nnums = [1, 2, 3, 4]\nnums = [1, 2, 3, 4]\nprint(sol.rangeSum(nums, 4, 1, 5))\n","sub_path":"python_solutions/1508.range-sum-of-sorted-subarray-sums.py","file_name":"1508.range-sum-of-sorted-subarray-sums.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"370397449","text":"import learn_pcfg as pcfg\nfrom nltk.corpus import treebank\n\nthree_trees = pcfg.three_trees\nsentences = pcfg.sentences\nsentence = \"Jeff pronounced that Fred snored loudly\"\ndef probA():\n print(pcfg.learn_trees(three_trees))\n\ndef ProbB():\n grammar = pcfg.learn_trees(three_trees)\n # calculates the top two parses and prints em\n parse = pcfg.prob_parse(grammar, sentence, 2)\n for i in parse:\n print(i)\n #i.draw()\nProbB()\n\ndef ProbD():\n grammar = pcfg.learn_treebank()\n # 27783 rules\n print(grammar)\n","sub_path":"classes/vassar/Linguistics_HW_4/Prob3/Problem_3.py","file_name":"Problem_3.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"304432875","text":"\"\"\"\nTools for creating arg parsers that are preconfigured for\nlettersmith scripts.\n\"\"\"\nimport argparse\nfrom pathlib import Path\nfrom .yamltools import load\n\nfrom lettersmith.util import get_deep\n\n\ndef lettersmith_argparser(description=\"Builds a site with Lettersmith\"):\n \"\"\"\n Creates a Lettersmith argparser. You supply the description. This\n makes it easy to create your own static site generator, and have a\n useful description text for it.\n \"\"\"\n parser = argparse.ArgumentParser(\n description=description,\n )\n parser.add_argument(\n 'config',\n help=\"Path to a YAML config file\",\n type=load,\n default={}\n )\n return parser\n\n\n\ndef read_config(config):\n \"\"\"\n Reads config object, providing sensible defaults for properties\n that aren't defined.\n \"\"\"\n return {\n \"input_path\": config.get(\"input_path\", \"content\"),\n \"output_path\": config.get(\"output_path\", \"public\"),\n \"theme_path\": config.get(\"theme_path\", \"theme\"),\n \"data_path\": config.get(\"data_path\", \"data\"),\n \"static_paths\": config.get(\"static_paths\", []),\n \"base_url\": config.get(\"base_url\", \"/\"),\n \"build_drafts\": config.get(\"build_drafts\", False),\n \"permalink_templates\": config.get(\"permalink_templates\", {}),\n \"taxonomies\": config.get(\"taxonomies\", []),\n \"paging\": config.get(\"paging\", {}),\n \"site\": config.get(\"site\", {})\n }","sub_path":"lettersmith/argparser.py","file_name":"argparser.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"26753014","text":"##\n## For help on setting up your machine and configuring this TestScript go to\n## http://help.testdroid.com/customer/portal/topics/631129-appium/articles\n##\n\nimport os\nimport time\nimport unittest\nfrom time import sleep\nfrom selenium import webdriver\nfrom device_finder import DeviceFinder\n\ndef log(msg):\n print (time.strftime(\"%H:%M:%S\") + \": \" + msg)\n\nclass TestdroidAndroid(unittest.TestCase):\n\n def screenshot(self, name):\n self.screenShotCount = 1\n screenshotName = str(self.screenShotCount) + \"_\" + name + \".png\" \n log (\"Taking screenshot: \" + screenshotName)\n sleep(1) # wait for animations to complete before taking screenshot\n self.driver.save_screenshot(self.screenshotDir + \"/\" + screenshotName)\n self.screenShotCount += 1\n\n \n def setUp(self):\n\n ##\n ## IMPORTANT: Set the following parameters.\n ## You can set the parameters outside the script with environment variables.\n ## If env var is not set the string after or is used.\n ##\n self.screenshotDir = os.environ.get('TESTDROID_SCREENSHOTS') or \"/absolute/path/to/desired/directory\"\n testdroid_url = os.environ.get('TESTDROID_URL') or \"https://cloud.testdroid.com\"\n testdroid_apiKey = os.environ.get('TESTDROID_APIKEY') or \"\"\n# testdroid_app = os.environ.get('TESTDROID_APP') or \"\"\n appium_url = os.environ.get('TESTDROID_APPIUM_URL') or 'http://appium.testdroid.com/wd/hub'\n\n # Options to select device\n # 1) Set environment variable TESTDROID_DEVICE\n # 2) Set device name to this python script\n # 3) Do not set #1 and #2 and let DeviceFinder to find free device for you\n\n deviceFinder = None\n testdroid_device = os.environ.get('TESTDROID_DEVICE') or \"Samsung Galaxy Tab 3 10.1 GT-P5210 4.4.2\"\n\n deviceFinder = DeviceFinder(url=testdroid_url)\n if testdroid_device == \"\":\n # Loop will not exit until free device is found\n while testdroid_device == \"\":\n testdroid_device = deviceFinder.available_free_android_device()\n\n \n desired_capabilities_cloud = {}\n desired_capabilities_cloud['testdroid_apiKey'] = testdroid_apiKey\n desired_capabilities_cloud['testdroid_target'] = 'chrome'\n desired_capabilities_cloud['testdroid_project'] = 'Appium Chrome Demo'\n desired_capabilities_cloud['testdroid_testrun'] = 'TestRun A'\n desired_capabilities_cloud['testdroid_device'] = testdroid_device\n# desired_capabilities_cloud['testdroid_app'] = testdroid_app\n desired_capabilities_cloud['platformName'] = 'Android'\n desired_capabilities_cloud['deviceName'] = 'AndroidDevice'\n desired_capabilities_cloud['browserName'] = 'chrome'\n\n desired_caps = desired_capabilities_cloud;\n\n log (\"Will save screenshots at: \" + self.screenshotDir)\n\n # set up webdriver\n log (\"WebDriver request initiated. Waiting for response, this typically takes 2-3 mins\")\n self.driver = webdriver.Remote(appium_url, desired_caps)\n\n log (\"Loading page http://testdroid.com\")\n self.driver.get(\"http://testdroid.com\")\n\n def tearDown(self):\n log (\"Quitting\")\n self.driver.quit()\n\n def testSample(self):\n log (\"Taking screenshot of home page: '1_home.png'\")\n self.driver.save_screenshot(self.screenshotDir + \"/1_home.png\")\n\n log (\"Finding 'Products'\")\n elem = self.driver.find_element_by_xpath('//*[@id=\"menu\"]/ul/li[1]/a')\n log (\"Clicking 'Products'\")\n elem.click()\n \n log (\"Taking screenshot of 'Products' page: '2_products.png'\")\n self.driver.save_screenshot(self.screenshotDir + \"/2_products.png\")\n \n log (\"Finding 'Learn More'\")\n elem = self.driver.find_element_by_xpath('//*[@id=\"products\"]/div[1]/div/div[1]/div[3]/a')\n log (\"Clicking 'Learn More'\")\n elem.click()\n\n log (\"Taking screenshot of 'Learn More' page: '3_learnmore.png'\")\n self.driver.save_screenshot(self.screenshotDir + \"/3_learnmore.png\")\n\n log (\"Finding 'Supported Frameworks'\")\n elem = self.driver.find_element_by_xpath('//*[@id=\"topBox\"]/div[1]/div/a[2]')\n log (\"Clicking 'Supported Frameworks'\")\n elem.click()\n\n log (\"Taking screenshot of 'Supported Framworks' page: '4_supportedframeworks.png'\")\n self.driver.save_screenshot(self.screenshotDir + \"/4_supportedframeworks.png\")\n\n log (\"quitting\")\n\n\nif __name__ == \"__main__\":\n suite = unittest.TestLoader().loadTestsFromTestCase(TestdroidAndroid)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"appium/sample-scripts/python/testdroid_chrome.py","file_name":"testdroid_chrome.py","file_ext":"py","file_size_in_byte":4657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"262660733","text":"from model import *\n\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker,scoped_session\n\n\nengine = create_engine('sqlite:///database.db')\nBase.metadata.create_all(engine)\nDBSession = sessionmaker(bind=engine)\nsession = scoped_session(sessionmaker(bind=engine,autoflush=False))\n\ndef add_product(name,price,Picturelink,Description):\n\tproduct_objection = Product(\n\t\tname=name,\n\t\tprice=price,\n\t\tPicturelink=Picturelink,\n\t\tDescription=Description)\n\tsession.add(product_objection)\n\tsession.commit()\n\nadd_product(\"Family Charm\",60,\"/static/charm1.jpeg\",\"Silver Charm \")\n\ndef update_price(ID,price):\n \n\tproduct_object = session.query(\n\t\tProduct).filter_by(\n\t\t\tID=ID).first()\n\tproduct_object.price = price\n\tsession.commit()\n#update_price(12,50)\ndef delete_product(their_name):\n\n\tsession.query(Product).filter_by(\n\t\tID=their_name).delete()\n\tsession.commit()\n#delete_product(11)\ndef query_all():\n\tproducts = session.query(\n\t\tProduct).all()\t\n\treturn products\n#query_all()\n#print(query_all())\ndef query_by_id(their_ID):\n\n \tproduct= session.query(\n\t\tProduct).filter_by(\n\t\tID=their_ID).first()\n\n\ndef add_to_cart(productID):\n\tproduct_object = Cart(\n\t\tproductID=productID)\n\tsession.add(product_object)\n\tsession.commit()\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"25231422","text":"from datetime import date, datetime\nfrom enum import Enum\nfrom typing import List, Optional, Union\n\nfrom api.activities.activity_models import SimplenightActivity\nfrom api.common.common_models import SimplenightModel\nfrom api.hotel.models.hotel_api_model import SimplenightHotel, HotelLocationSearch, HotelSpecificSearch\nfrom api.restaurants.restaurant_models import SimplenightRestaurant\n\n\nclass Products(Enum):\n HOTELS = \"hotels\"\n ACTIVITIES = \"activities\"\n DINING = \"dining\"\n EVENTS = \"events\"\n\n\nclass ActivitySearch(SimplenightModel):\n begin_date: date\n end_date: date\n adults: int\n children: int = 0\n provider: Optional[str] = None\n\n\nclass RestaurantSearch(SimplenightModel):\n location_id: str\n reservation_date: datetime\n party_size: int\n cuisine: Optional[str] = None\n restaurant_name: Optional[str] = None\n provider: Optional[str] = None\n\n\nclass ActivityLocationSearch(ActivitySearch):\n location_id: Union[str, int]\n\n\nclass ActivitySpecificSearch(ActivitySearch):\n activity_id: str\n\n\nclass SearchRequest(SimplenightModel):\n product_types: List[Products]\n hotel_search: Optional[Union[HotelLocationSearch, HotelSpecificSearch]]\n activity_search: Optional[Union[ActivitySpecificSearch, ActivityLocationSearch]]\n restaurant_search: Optional[RestaurantSearch]\n\n\nclass SearchResponse(SimplenightModel):\n hotel_results: Optional[Union[SimplenightHotel, List[SimplenightHotel]]]\n restaurant_results: Optional[List[SimplenightRestaurant]]\n activity_results: Optional[Union[SimplenightActivity, List[SimplenightActivity]]]\n","sub_path":"api/multi/multi_product_models.py","file_name":"multi_product_models.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"425106566","text":"# coding=utf-8\n# 合同管理\nimport time\nimport unittest\nfrom fky_pageobjects.contractManagement import ContractManagement\nfrom framework.browser_engine import BrowserEngine\nfrom fky_common.login import Login\nfrom fky_common.logout import Logout\nfrom framework import generator\nfrom framework.logger import Logger\nfrom fky_pageobjects.myApprove import MyApprove\n\n\nlogger = Logger(logger=\"Contract\").getlog()\n\n\nclass Contract(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n browser = BrowserEngine(cls)\n cls.driver = browser.open_browser(cls)\n # 登录\n login = Login()\n login.log_in(cls)\n ht = ContractManagement(cls.driver)\n ht.into_contract_management()\n\n @classmethod\n def tearDownClass(cls):\n # 登出\n logout = Logout()\n logout.log_out(cls)\n cls.driver.quit()\n\n # 合同新增---驳回---提交---同意\n def test01_add_contract(self):\n ht = ContractManagement(self.driver)\n # 调用合同新增方法,并断言\n htid = generator.randomStr(10, True, False, False, False, False, None)\n ht.click_xinZeng()\n ht.add_contract(htid)\n myapprove = MyApprove(self.driver)\n myapprove.xuanze_spr()\n ht.click_queding()\n try:\n self.assertEqual(ht.get_sp_states()[0], \"审批中\")\n logger.info(\"发起审批合同成功!\")\n except Exception as e:\n logger.error(\"发起审批合同失败!\", e)\n ht.get_windows_img()\n # 审批项目流程--驳回\n myapprove.execute_bohui()\n # pj.click_queding()\n ht.into_contract_management()\n try:\n self.assertEqual(ht.get_sp_states()[0], \"驳回\")\n logger.info(\"驳回合同成功!\")\n except Exception as e:\n logger.error(\"驳回合同失败!\", e)\n ht.get_windows_img()\n # 审批项目流程--同意\n myapprove.execute_tijiao_tongyi(0)\n ht.into_contract_management()\n try:\n self.assertEqual(ht.get_sp_states()[0], \"审批通过\")\n logger.info(\"新增合同成功!\")\n except Exception as e:\n logger.error(\"新增合同失败!\", e)\n ht.get_windows_img()\n\n # 调用禁用,启用方法,并断言\n def test02_jinyong_contract(self):\n ht = ContractManagement(self.driver)\n n = -1\n for ht_state in ht.get_ht_states():\n n = n + 1\n if ht_state == \"启用\" and ht.get_sp_states()[n] == \"审批通过\":\n ht.get_jinyongs_elements()[n].click()\n time.sleep(1)\n ht.click_queding()\n try:\n self.assertEqual(ht.get_ht_states()[n], \"禁用\")\n logger.info(\"合同:%s 禁用成功!\" % ht.gain_contractId()[n])\n except Exception as e:\n logger.error(\"合同禁用失败!\", e)\n ht.get_windows_img()\n break\n else:\n logger.info(\"%s: 该单据无法禁用\" % ht.gain_contractId()[n])\n\n # 启用\n def test03_qiyong_contract(self):\n ht = ContractManagement(self.driver)\n n = -1\n for ht_state in ht.get_ht_states():\n n = n + 1\n if ht_state == \"禁用\" and ht.get_sp_states()[n] == \"审批通过\":\n ht.get_qiyongs_elements()[n].click()\n time.sleep(1)\n ht.click_queding()\n try:\n self.assertEqual(ht.get_ht_states()[n], \"启用\")\n logger.info(\"合同:%s 启用成功!\" % ht.gain_contractId()[n])\n except Exception as e:\n logger.error(\"合同启用失败!\", e)\n ht.get_windows_img()\n break\n else:\n logger.info(\"%s: 该单据无法启用\" % ht.gain_contractId()[n])\n\n # 合同修改---反对\n def test04_modify_contract(self):\n ht = ContractManagement(self.driver)\n n = -1\n for ht_state in ht.get_ht_states():\n n = n + 1\n if ht_state == \"启用\" and ht.get_sp_states()[n] == \"审批通过\":\n ht.get_xiugais_elements()[n].click()\n time.sleep(1)\n htid = generator.randomStr(\n 10, True, False, False, False, False, None)\n ht.add_contract(htid)\n myapprove = MyApprove(self.driver)\n myapprove.xuanze_spr()\n ht.click_queding()\n try:\n self.assertEqual(ht.get_sp_states()[n], \"审批中\")\n self.assertEqual(ht.get_ht_states()[n], \"禁用\")\n logger.info(\"发起审批合同修改成功!\")\n except Exception as e:\n logger.error(\"发起审批合同修改失败!\", e)\n ht.get_windows_img()\n # 审批项目流程--反对\n myapprove.execute_fandui()\n ht.into_contract_management()\n try:\n self.assertEqual(ht.get_sp_states()[n], \"审批通过\")\n self.assertEqual(ht.get_ht_states()[n], \"启用\")\n logger.info(\"反对合同修改成功!\")\n except Exception as e:\n logger.error(\"反对合同修改失败!\", e)\n ht.get_windows_img()\n # # 审批项目流程--同意\n # myapprove.execute_tijiao_tongyi(0)\n # ht.into_contract_management()\n # try:\n # self.assertEqual(ht.get_sp_states()[0], \"审批通过\")\n # logger.info(\"修改合同成功!\")\n # except Exception as e:\n # logger.error(\"修改合同失败!\", e)\n # ht.get_windows_img()\n break\n else:\n logger.info(\"%s: 该单据无法修改\" % ht.gain_contractId()[n])\n\n # 合同修改---同意\n def test05_modify_contract(self):\n ht = ContractManagement(self.driver)\n n = -1\n for ht_state in ht.get_ht_states():\n n = n + 1\n if ht_state == \"启用\" and ht.get_sp_states()[n] == \"审批通过\":\n ht.get_xiugais_elements()[n].click()\n time.sleep(1)\n htid = generator.randomStr(\n 10, True, False, False, False, False, None)\n ht.add_contract(htid)\n myapprove = MyApprove(self.driver)\n myapprove.xuanze_spr()\n ht.click_queding()\n try:\n self.assertEqual(ht.get_sp_states()[n], \"审批中\")\n self.assertEqual(ht.get_ht_states()[n], \"禁用\")\n logger.info(\"发起审批合同修改成功!\")\n except Exception as e:\n logger.error(\"发起审批合同修改失败!\", e)\n ht.get_windows_img()\n # 审批项目流程--同意\n myapprove.execute_tongyi()\n ht.into_contract_management()\n try:\n self.assertEqual(ht.gain_contractId()[n], htid)\n self.assertEqual(ht.get_ht_states()[n], \"启用\")\n self.assertEqual(ht.get_sp_states()[n], \"审批通过\")\n logger.info(\"修改合同成功!\")\n except Exception as e:\n logger.error(\"修改合同失败!\", e)\n ht.get_windows_img()\n break\n else:\n logger.info(\"%s: 该单据无法修改\" % ht.gain_contractId()[n])\n\n # 查询---合同编号\n def test06_query_htbh(self):\n ht = ContractManagement(self.driver)\n ht.click_zhankai()\n htbh_1 = ht.gain_contractId()[0]\n ht.input_sr_htbh(htbh_1)\n ht.click_query_btn()\n htbh_list = ht.gain_contractId()\n for htbh in htbh_list:\n self.assertEqual(htbh, htbh_1, \"按合同编号查询合同失败!\")\n logger.info(\"按合同编号查询合同成功!\")\n ht.click_clear_btn()\n\n def test07_query_htmc(self):\n ht = ContractManagement(self.driver)\n ht.click_zhankai()\n htmc_1 = ht.get_htmc()[0]\n ht.input_sr_htmc(htmc_1)\n ht.click_query_btn()\n htmc_list = ht.get_htmc()\n for htmc in htmc_list:\n self.assertIn(htmc_1, htmc, \"按合同名称查询合同失败!\")\n logger.info(\"按合同名称查询合同成功!\")\n ht.click_clear_btn()\n\n # 查询---合同状态\n def test08_query_htzt(self):\n ht = ContractManagement(self.driver)\n ht.click_zhankai()\n htzt_1 = ht.gain_contractState()[0]\n ht.select_sr_htzt(htzt_1)\n ht.click_query_btn()\n htzt_list = ht.gain_contractState()\n for htzt in htzt_list:\n self.assertEqual(htzt, htzt_1, \"按合同状态查询合同失败!\")\n logger.info(\"按合同状态查询合同成功!\")\n ht.click_clear_btn()\n\n # 导入\n def test09_import_contract(self):\n ht = ContractManagement(self.driver)\n ht.click_input()\n title = ht.get_into_title()\n try:\n self.assertEqual(\"导入数据\", title, \"点击导入按钮失败!\")\n logger.info(\"点击导入按钮成功!\")\n except NameError as e:\n logger.error(\"执行错误!%s\" % e)\n ht.get_windows_img()\n ht.click_close()\n ht.wait(1)\n\n # 导出\n def test10_export_contract(self):\n ht = ContractManagement(self.driver)\n ht.click_export()\n ht.click_queding()\n name_list = ht.file_name(r\"C:\\\\Users\\Kejie\\Downloads\")\n try:\n self.assertIn(\"合同信息.xls\", name_list, \"合同信息导出失败!\")\n logger.info(\"合同信息导出成功!\")\n except NameError as e:\n logger.error(\"执行错误!%s\" % e)\n ht.get_windows_img()\n ht.remover_file(\"合同信息\")\n ht.wait(1)\n","sub_path":"fky_testsuits/test22_contract_management.py","file_name":"test22_contract_management.py","file_ext":"py","file_size_in_byte":10181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"288485157","text":"def authentication_message(app_key, session_token) -> dict:\n \"\"\"Authentication request.\"\"\"\n message = {\n \"op\": \"authentication\",\n \"appKey\": app_key,\n \"session\": session_token,\n }\n return message\n\n\ndef subscription_message(\n market_filter: dict,\n market_data_filter: dict,\n conflate_ms: int = None,\n heartbeat_ms: int = None,\n segmentation_enabled: bool = True,\n) -> dict:\n \"\"\"\n Market subscription request.\n\n :param dict market_filter: Market filter\n :param dict market_data_filter: Market data filter\n :param str initial_clk: Sequence token for reconnect\n :param str clk: Sequence token for reconnect\n :param int conflate_ms: conflation rate (bounds are 0 to 120000)\n :param int heartbeat_ms: heartbeat rate (500 to 5000)\n :param bool segmentation_enabled: allow the server to send large sets of data\n in segments, instead of a single block\n \"\"\"\n\n message = {\n \"op\": \"marketSubscription\",\n \"marketFilter\": market_filter,\n \"marketDataFilter\": market_data_filter,\n \"conflateMs\": conflate_ms,\n \"heartbeatMs\": heartbeat_ms,\n \"segmentationEnabled\": segmentation_enabled,\n }\n\n return message\n\n\ndef order_message():\n\n message = {\n 'op': 'orderSubscription',\n 'orderFilter': None,\n 'initialClk': None,\n 'clk': None,\n 'conflateMs': None,\n 'heartbeatMs': 5000,\n 'segmentationEnabled': True,\n }\n\n return message\n","sub_path":"betfairstreamer/api_messages.py","file_name":"api_messages.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"72855167","text":"import self as self\nimport tweepy\nfrom FinalTweet import TweetFinal\nAccess_token = ''\nAccess_token_secret = ''\n\nBearer_token = ''\n\nCONSUMER_KEY = ''\nCONSUMER_SECRET = ''\n\nauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\nauth.set_access_token(Access_token, Access_token_secret)\napi = tweepy.API(auth)\n\n#final_tweet return will return a poem from assocaiated JSON file\nTweetData = TweetFinal.final_tweet(self)\n\ntry:\n api.verify_credentials()\n print(\"Authentication OK\")\n \n #Tweet\n api.update_status(TweetData)\nexcept:\n print(\"Error during authentication\")\n","sub_path":"Starter.py","file_name":"Starter.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"364509376","text":"import pygame, sys, global_parameter\nimport level\nimport gameover\n\nimport role.god.baseGod\n\ndef select_god():\n pygame.init()\n size = (global_parameter.windows_width, global_parameter.windows_height)\n screen = pygame.display.set_mode(size)\n pygame.display.set_caption('人物选择')\n\n god = None\n god_choose = False\n\n level_list = level.get_level_list()\n\n god_select_background = pygame.image.load('Image/background/god_select_background.jpg')\n god_select_background_rect = god_select_background.get_rect()\n\n\n god1_choose1 = pygame.image.load('Image/font/god1_choose1.png')\n god1_choose2 = pygame.image.load('Image/font/god1_choose2.png')\n god2_choose1 = pygame.image.load('Image/font/god2_choose1.png')\n god2_choose2 = pygame.image.load('Image/font/god2_choose2.png')\n back1 = pygame.image.load('Image/font/back1.png')\n back2 = pygame.image.load('Image/font/back2.png')\n god1_choose_rect = god1_choose1.get_rect()\n god2_choose_rect = god2_choose1.get_rect()\n back_rect = back1.get_rect()\n\n god1_choose_rect = god1_choose_rect.move(150, 600)\n god2_choose_rect = god2_choose_rect.move(800, 600)\n back_rect = back_rect.move(1100, 650)\n\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n if god1_choose_rect.collidepoint(pygame.mouse.get_pos()):\n god = role.god.baseGod.God(move_speed=4, skill_type=2)\n god_choose = True\n #next_op = test_level.Level_1(role.god.baseGod.God(move_speed=4))\n elif god2_choose_rect.collidepoint(pygame.mouse.get_pos()):\n god = role.god.baseGod.God(move_speed=6, skill_type=1)\n god_choose = True\n #next_op = test_level.Level_1(role.god.baseGod.God(move_speed=6))\n elif back_rect.collidepoint(pygame.mouse.get_pos()):\n return\n\n if god_choose == True:\n for v in level_list:\n god.speed = [0, 0]\n god.skill_time = 3\n if v(god) == 1:\n if gameover.gameover2() == 0:\n break\n else:\n continue\n else:\n break\n gameover.gameover1()\n god_choose = False\n\n\n screen.fill(global_parameter.BLACK)\n screen.blit(god_select_background, god_select_background_rect)\n\n if god1_choose_rect.collidepoint(pygame.mouse.get_pos()):\n screen.blit(god1_choose2, god1_choose_rect)\n else:\n screen.blit(god1_choose1, god1_choose_rect)\n if god2_choose_rect.collidepoint(pygame.mouse.get_pos()):\n screen.blit(god2_choose2, god2_choose_rect)\n else:\n screen.blit(god2_choose1, god2_choose_rect)\n if back_rect.collidepoint(pygame.mouse.get_pos()):\n screen.blit(back2, back_rect)\n else:\n screen.blit(back1, back_rect)\n\n\n pygame.display.update()","sub_path":"Pygame_woke/god_select.py","file_name":"god_select.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"90731754","text":"from terminaltables import AsciiTable\nfrom colorama import init\ninit()\nfrom colorama import Fore, Back, Style\nimport random\nimport sys\nimport os\n\n\nshop_name = 'FIX PRICE'\n# customers = 0\nshop_category = 'canabis store'\ncapital = 0\nproduct_category = ['light', 'fast', 'medium', 'hard']\nproduct_list = []\ncustomers_list = []\n\ndef cls():\n os.system(['clear','cls'][os.name == 'nt'])\n\ndef welcome():\n # print(Back.GREEN)\n print(Back.GREEN,'Добро пожаловать в',shop_name,shop_category,Style.RESET_ALL)\n # print(Style.RESET_ALL)\n\n# печатает в консоль информацию о магазине\ndef print_info_about_shop():\n print(shop_name,shop_category)\n print('Покупателей в магазе',len(customers_list))\n print('Всего бабла',capital)\n\n# метод принимает имя нового пользователя\n# и увеличивает переменную customers на 1\ndef create_user(name, age):\n if age >= 18 and age <= 44:\n agree = input('мамка разрешает? Y or N: ')\n if agree == 'Y':\n print('all right')\n else:\n print(name,'phsel nah')\n elif age >= 45:\n print('all righ + дадим скидку')\n else:\n print(name, 'phsel nah')\n\n # global customers\n # customers += 1\n\n# метод создает словарь продукта\n# в качестве значений используются аргументы\ndef create_product(id, name, size, price, created_at):\n product = {\n 'id': id,\n 'name': name,\n 'size': size,\n 'price': price,\n 'created_at': created_at\n }\n product_list.append(product)\n\ndef get_random_name(name_lenght):\n name = ''\n for elem in range(0, name_lenght):\n rand_number = random.randint(65,90)\n rand_char = chr(rand_number)\n name += rand_char\n\n return name\n\ndef product_generator(number_of_iter):\n for element in range(0, number_of_iter):\n create_product(\n element,\n get_random_name(10),\n 25,\n 150,\n '10/12/2019'\n ) \n\n\n\n# метод выводит имена всех продуктов из листа\ndef print_product_list():\n table_data = []\n for element in product_list:\n item_data = []\n item_data.append(element['id'])\n item_data.append(element['name'])\n item_data.append(element['price'])\n item_data.append(element['size'])\n table_data.append(item_data)\n print_table(['id', 'name', 'price $', 'size g'], table_data)\n\n# метод рисует в консоль таблицу \n# принимает в себя список заголовков table_headers пример [123, 123, 123]\n# и список списков table_body пример [[1,2,3],[4,5,6]...[101,102,103]]\ndef print_table(table_headers, table_body):\n table_data = []\n table_data.append(table_headers)\n for element in table_body:\n table_data.append(element)\n table = AsciiTable(table_data)\n print(table.table)\n\ndef add_to_cart():\n pass\n\ndef get_order():\n pass\n\n# create_user('Vasya', 45)\n\n# product = create_product(1, 'product1', 100, 1000, '09.12.2019')\n# add_product_to_list(product)\n# product = create_product(2, 'product2', 100, 250, '09.12.2019')\n# add_product_to_list(product)\n# product = create_product(3, 'product3', 100, 250, '09.12.2019')\n# add_product_to_list(product)\n# product = create_product(4, 'product4', 100, 1000, '09.12.2019')\n# add_product_to_list(product)\n# print_product_list()\n\n# print(product_list)\n# get_info_about_shop()\n# create_user()\n# product_generator(10)\n\nwelcome()\nproduct_generator(15)\n\navailable_actions = [\n ['Есть че?','Отобразить витрину'],\n ['Закройся','Выход из магазина']\n]\n\nhandle = open(\"output.txt\", \"w\", encoding='utf-8')\n\ncls()\nprint(Back.GREEN)\nprint_table(['Доступные действия', 'Описание'], available_actions)\nprint(Style.RESET_ALL)\n\nwhile True:\n\n flag = input('Чего надо? Говори: ')\n \n handle.write(flag+'\\n')\n\n if flag == 'Закройся' :\n cls()\n handle.close()\n break\n elif flag == 'Есть че?':\n cls()\n print_product_list()\n else:\n print(Back.RED,'В глазки балуешься? Нет такого действия!',Style.RESET_ALL)\n\n\n","sub_path":"shop/shop.py","file_name":"shop.py","file_ext":"py","file_size_in_byte":4465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"12818200","text":"import numpy as np\nimport pandas as pd\nimport scipy.special as special\nfrom scipy.stats import kendalltau as kendalltau\n\nclass evaluation:\n def __init__(self, time_feature_list, fitted_result):\n self.time_list = time_feature_list.time_list\n self.feature_matrix = np.matrix(self.time_list.loc[:, 'feature0':])\n self.fitted_mu = fitted_result['mu']\n self.fitted_coeff = np.asarray(np.squeeze(fitted_result['coefficients']))[0]\n self.true_coeff = np.array(time_feature_list.coefficients)\n\n def RMSE_eta(self):\n true_eta = special.expit(self.feature_matrix.dot(self.true_coeff))\n fitted_eta = special.expit(self.feature_matrix.dot(self.fitted_coeff))\n return np.linalg.norm(true_eta - fitted_eta) / self.time_list.__len__()**0.5\n\n def RMSE_beta(self):\n return np.linalg.norm(self.fitted_coeff - self.true_coeff) / self.true_coeff.__len__() ** 0.5\n\n def Tau_beta(self):\n return kendalltau(self.fitted_coeff, self.true_coeff)[0]\n\n\n\nif __name__ == '__main__':\n import simulation2\n import learning\n import matplotlib.pyplot as plt\n\n T = 100\n mu = 0.2\n p = 1.6\n phi = 1\n time_feature_list = simulation2.simulation_baselines(T, mu, p, 8, kernel_bandwidth = 0.5)\n\n time_feature_list.simulate(method='SER', mu = 0.1, p=0.2)\n time_feature_list.time_list.__len__()\n\n self = learning.HawkesTweedie(time_feature_list.time_list, T, p = p, kernel_bandwidth = 0.5)\n # self.init_parameters['beta'] = time_feature_list.coefficients\n # self.init_parameters['mu'] = mu\n\n fitted_result = self.fit_VEM(iteration = 10, err = 1e-1)\n\n eva = evaluation(time_feature_list, fitted_result)\n eva.RMSE_beta()\n eva.RMSE_eta()\n","sub_path":"evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"398301485","text":"#!/usr/bin/python3\n# -*- coding:Utf-8 -*- \n\n\n\"\"\"\nHandyMenu : menu principal de la distribution\n HandyLinux \n\nAuteurs : Xavier Cartron \nlicence : GNU General Public Licence v3\nDescription : Handymenu from scratch\nDépendances : python3-gi xdg-user-dirs xdg-utils\n\n\"\"\"\n\nversion = \"4.0\"\nauteur = \"thuban\"\nlicence = \"GPLv3\"\nhomepage = \"https://handylinux.org\"\n\nimport os\nimport sys\nfrom gi.repository import Gtk, Gdk, GObject\nfrom gi.repository.GdkPixbuf import Pixbuf, InterpType\nfrom gi.repository.Gio import content_type_get_icon\nfrom textwrap import fill\nfrom math import ceil\nfrom concurrent.futures import ThreadPoolExecutor\nimport gettext\nfrom hm_utils import *\n\ngettext.bindtextdomain('handymenu', '/usr/share/locale')\ngettext.textdomain('handymenu')\n_ = gettext.gettext\n\nos.chdir(os.getenv('HOME'))\n\nclass Handymenu():\n def close_application(self, widget, event, data=None):\n # tests nécessaires pour que seul clic-gauche et Entrée soient valables\n if event.type == Gdk.EventType.BUTTON_RELEASE and \\\n event.state & Gdk.ModifierType.BUTTON1_MASK:\n Gtk.main_quit()\n elif event.type == Gdk.EventType.KEY_PRESS: \n if event.keyval == Gdk.KEY_Return:\n Gtk.main_quit()\n\n def configure(self, data=None):\n open_cmd(configcmd)\n Gtk.main_quit()\n\n def about(self, wid=None, data=None):\n # fenêtre à propos.\n m = Gtk.MessageDialog(parent=self.window)\n m.add_buttons(Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)\n m.set_markup(_('Handymenu\\n\\n\\\nversion : {0}\\n\\\nauthor : {1}\\n\\\nlicence : {2}\\n\\\nhomepage : {3}').format(version, auteur, licence, homepage))\n\n\n import base64\n import random\n imgsrc = random.choice(imglist)\n\n g = base64.b64decode(imgsrc)\n imgpath = \"/tmp/.hmbtn.png\"\n with open(imgpath, \"wb\") as t:\n t.write(g)\n image = Gtk.Image.new_from_file(imgpath)\n\n btnbox = m.get_action_area()\n for btn in btnbox: # il n'y en a qu'un\n btn.set_label(_(\"I click here because I love handylinux\"))\n btn.set_image(image)\n btn.set_image_position(Gtk.PositionType.TOP)\n\n ret = m.run()\n if ret == Gtk.ResponseType.CLOSE:\n open_cmd(\"x-www-browser https://handylinux.org/forum\")\n os.remove(imgpath)\n m.destroy()\n \n def add_recent(self,app):\n \"\"\"add a recent application\n appname, icon, cmd= app['name'], app['icon'], app['cmd']\n \"\"\"\n for s in self.config:\n if s['id'] == 'recent': # on prend la bonne section\n # check if app is not already in recents\n if app not in s['apps']:\n s['apps'].insert(0,app)\n # on vire les vieux éléments\n if len(s['apps']) > max:\n s['apps'].pop()\n save_config(self.config)\n\n def exec_app(self, widget, event, data):\n exe = False\n if event.type == Gdk.EventType.BUTTON_RELEASE and \\\n event.state & Gdk.ModifierType.BUTTON1_MASK:\n exe = True\n elif event.type == Gdk.EventType.KEY_PRESS: \n if event.keyval == Gdk.KEY_Return:\n exe = True\n\n if exe:\n appname, icon, cmd= data['name'], data['icon'], data['cmd']\n res = open_cmd(\"{}\".format(cmd.strip()))\n if res:\n self.add_recent(data)\n if self.closeafterrun:\n GObject.idle_add(self.window.hide)\n Gtk.main_quit()\n else:\n if os.path.isfile(\"/usr/bin/handysoft\"):\n m = Gtk.MessageDialog(self.window, 0, Gtk.MessageType.QUESTION, \\\n Gtk.ButtonsType.YES_NO, \\\n _('Error at launching {}\\n\\nDo you want to install it?').format(cmd))\n ret = m.run()\n m.destroy()\n\n if ret == Gtk.ResponseType.YES:\n open_cmd(\"handysoft {}\".format(cmd.strip()))\n \n self.window.show_all()\n \n def change_bg_on_focus(self,widget,b):\n widget.modify_bg(Gtk.StateFlags.NORMAL, self.selected_bg_color)\n widget.modify_bg(Gtk.StateFlags.PRELIGHT, self.selected_bg_color)\n \n def change_bg_on_focus_leave(self,widget,b):\n widget.modify_bg(Gtk.StateFlags.NORMAL, None)\n widget.modify_bg(Gtk.StateFlags.PRELIGHT, None)\n widget.modify_bg(Gtk.StateFlags.SELECTED, None)\n\n def create_tabs(self):\n modlist = load_modules()\n index = modlist[0] -1\n for m in modlist[1]:\n if m == \"_recent_files_\":\n recentfiles = get_recently_used(max)\n if recentfiles:\n self.config.insert(index,recentfiles)\n \n with ThreadPoolExecutor(max_workers=4) as executor:\n for page, label in executor.map(self.add_button, self.config):\n self.onglets.append_page(page, label)\n\n if len(self.config) > maxonglets: # dyp il aime pas :P\n self.onglets.set_scrollable(True)# dyp y veut pas :P\n self.window.set_size_request(win_max_width, -1) # pour éviter que la fenêtre soit trop large\n\n def add_button(self,s):\n # Description du bouton\n label = Gtk.Label()\n label.set_markup_with_mnemonic(\"_{}\".format(s['name']))\n label.set_width_chars(onglet_width) # pour avoir des onglets uniformes\n\n r = 2 # 2 lignes par défaut\n n = len(s['apps']) # number of apps to show\n if n > 0:\n r = ceil(n/3)\n if r > 2:\n r -= 1\n c = ceil(n/r)\n if c > 2:\n c -= 1\n\n if len(s['apps']) > 0:\n page = Gtk.Table(rows=r, columns=c, homogeneous=True)\n page.set_row_spacings(1)\n page.set_col_spacings(1)\n x, y = 0, 0\n\n for a in s['apps']:\n appname, icon, cmd, generic = a['name'], a['icon'], a['cmd'], a['generic']\n \n # image utilisée dans le bouton\n image = Gtk.Image()\n filename, ext = os.path.splitext(icon)\n if ext.lower() in ['.png', '.jpg', '.jpeg', '.gif'] :\n try:\n if os.path.isfile(icon):\n pixbuf = Pixbuf.new_from_file(icon)\n scaled_buf = pixbuf.scale_simple(iconsize,iconsize,InterpType.BILINEAR)\n image.set_from_pixbuf(scaled_buf)\n else:\n image.set_from_icon_name(\"image-missing\", Gtk.IconSize.DIALOG)\n except:\n image.set_from_icon_name(\"image-missing\", Gtk.IconSize.DIALOG)\n \n elif ext == \".ico\":\n if os.path.isfile(icon):\n pixbuf = Pixbuf.new_from_file(icon)\n scaled_buf = pixbuf.scale_simple(iconsize,iconsize,InterpType.BILINEAR)\n image.set_from_pixbuf(scaled_buf)\n else:\n image.set_from_icon_name(\"applications-internet\", Gtk.IconSize.DIALOG)\n \n elif len(icon.split('/')) == 2: # mimetype?\n icon = content_type_get_icon(icon)\n image.set_from_gicon(icon, Gtk.IconSize.DIALOG)\n \n else:\n image.set_from_icon_name(icon, Gtk.IconSize.DIALOG)\n \n image.set_pixel_size(iconsize)\n \n # nom de l'appli\n appname = fill(appname, button_width)\n bapp = Gtk.Button.new_with_mnemonic('_{}'.format(appname))\n bapp.set_border_width(1)\n bapp.set_image(image)\n # l'image est au dessus du texte\n bapp.set_image_position(Gtk.PositionType.TOP)\n # apparence du bouton\n bapp.set_relief(Gtk.ReliefStyle.NONE)\n # lancement au clic ou avec entrée\n bapp.connect(\"button_release_event\", self.exec_app, a)\n bapp.connect(\"key_press_event\", self.exec_app, a)\n bapp.set_tooltip_text(generic)\n\n page.attach(bapp, x, x+1, y, y+1,\\\n xoptions=Gtk.AttachOptions.EXPAND|Gtk.AttachOptions.FILL,\\\n yoptions=Gtk.AttachOptions.EXPAND|Gtk.AttachOptions.FILL,\\\n xpadding=1, ypadding=1)\n if x < c:\n x +=1\n elif x == c:\n x = 0\n y += 1\n\n else:\n page = Gtk.Label(_(\"This menu is still empty\"))\n label = Gtk.Label(_(\"This menu is still empty\"))\n\n return(page, label)\n\n def close_after(self, widget):\n self.closeafterrun = widget.get_active()\n if not self.closeafterrun: #on enregistre de ne pas fermer\n with open(noclose,'w') as n:\n n.write('Thuban veut un câlin :P')\n else:\n if os.path.isfile(noclose): #on ferme la prochiane fois\n os.remove(noclose)\n \n def make_menu(self):\n \"\"\"build the menu\"\"\"\n # Conteneur principal\n mainbox = Gtk.EventBox()\n \n # pour utiliser la couleur de fond du thème GTK\n mainbox.modify_bg(Gtk.StateFlags.NORMAL, self.bg_color) \n self.window.add(mainbox)\n\n vbox = Gtk.VBox(False, 2)\n vbox.set_border_width(15)\n mainbox.add(vbox)\n\n # Logo\n image = Gtk.Image()\n image.set_from_file(handymenuicon)\n logo = Gtk.EventBox()\n logo.add(image)\n logo.connect_object(\"button_release_event\", self.about, None)\n logo.set_tooltip_text(_(\"About\"))\n\n # Titre\n self.title = Gtk.Label()\n self.title.set_markup('HandyMenu ')\n self.title.set_justify(Gtk.Justification.CENTER)\n titlebox = Gtk.EventBox()\n titlebox.add(self.title)\n titlebox.connect_object(\"button_press_event\", self.move_win, None)\n titlebox.set_tooltip_text(\"handylinux.org\")\n\n # boutons\n # bouton pour fermer\n closebtn = Gtk.Button()\n croix = Gtk.Image()\n croix.set_from_stock(Gtk.STOCK_CLOSE, Gtk.IconSize.MENU)\n closebtn.set_image(croix)\n \n closebtn.set_relief(Gtk.ReliefStyle.NONE)\n closebtn.connect(\"button_release_event\", self.close_application)\n closebtn.connect(\"key_press_event\", self.close_application)\n closebtn.set_tooltip_text(_(\"Close\"))\n\n # configuration \n qbtn = Gtk.Button()\n image = Gtk.Image()\n image.set_from_stock(Gtk.STOCK_PREFERENCES, Gtk.IconSize.MENU)\n qbtn.set_image(image)\n qbtn.set_relief(Gtk.ReliefStyle.NONE)\n qbtn.connect_object(\"clicked\", self.configure, None)\n qbtn.set_tooltip_text(_(\"Configure\"))\n\n # fermer ou pas\n closeafterbtn = Gtk.CheckButton()\n closeafterbtn.connect(\"toggled\", self.close_after)\n closeafterbtn.set_active(self.closeafterrun)\n closeafterbtn.set_tooltip_text(_(\"Close after execution\"))\n closeafterbtn.set_halign(Gtk.Align.CENTER)\n\n # boite à boutons \n btnbox = Gtk.VBox(False,0)\n btnbox.pack_start(closebtn, True, True, 0)\n btnbox.pack_start(qbtn, True, True, 0)\n btnbox.pack_start(closeafterbtn, True, True, 0)\n\n # Boite d'en haut\n topbox = Gtk.HBox(False, 0)\n topbox.pack_start(logo, False, False, 0)\n topbox.pack_start(titlebox, True, True, 0)\n topbox.pack_start(btnbox, False, False, 0)\n\n vbox.pack_start(topbox, True, True, 0)\n\n # onglets\n self.onglets = Gtk.Notebook()\n self.onglets.set_tab_pos(Gtk.PositionType.TOP)\n self.onglets.set_show_border(False)\n self.onglets.add_events(Gdk.EventMask.SCROLL_MASK |\\\n Gdk.EventMask.SMOOTH_SCROLL_MASK)\n self.onglets.connect('scroll-event', self.scroll_tab)\n\n vbox.pack_start(self.onglets, True, True, 0)\n \n # Catégories\n self.create_tabs() \n self.window.show_all()\n\n def scroll_tab(self, widget, event):\n if event.get_scroll_deltas()[2] < 0:\n self.onglets.prev_page()\n else:\n self.onglets.next_page()\n \n\n def move_win(self, widget, event):\n \"\"\"move window with a simple click\"\"\"\n self.window.begin_move_drag(event.button, int(event.x_root), int(event.y_root), event.time)\n\n def get_theme_colors(self):\n\n style_context = self.window.get_style_context()\n bg_color = style_context.lookup_color('bg_color')\n selected_bg_color = style_context.lookup_color('selected_bg_color')\n self.bg_color = Gdk.color_parse(\"#ffffff\")\n self.selected_bg_color = Gdk.color_parse(\"#41B1FF\")\n \n try: # no error even if old gtk3\n if bg_color[0]:\n self.bg_color = bg_color[1].to_color()\n if selected_bg_color[0]:\n self.selected_bg_color = selected_bg_color[1].to_color()\n except:\n bg_color = Gdk.color_parse(\"#eeeeee\")\n self.selected_bg_color = Gdk.color_parse(\"#41B1FF\")\n\n\n def change_focus_colors(self,i): # change colors of the widget i\n i.connect(\"focus_in_event\", self.change_bg_on_focus)\n i.connect(\"enter_notify_event\", self.change_bg_on_focus)\n i.connect(\"focus_out_event\", self.change_bg_on_focus_leave)\n i.connect(\"leave_notify_event\", self.change_bg_on_focus_leave)\n\n def do_access(self, widget):\n for i in widget:\n if type(i) == Gtk.Button: \n self.change_focus_colors(i)\n elif type(i) == Gtk.HBox:\n self.do_access(i)\n elif type(i) == Gtk.VBox:\n self.do_access(i)\n elif type(i) == Gtk.Alignment:\n self.do_access(i)\n elif type(i) == Gtk.ScrolledWindow:\n self.do_access(i)\n elif type(i) == Gtk.EventBox:\n self.do_access(i)\n elif type(i) == Gtk.Notebook:\n self.do_access(i)\n elif type(i) == Gtk.Table:\n self.do_access(i)\n try: #HL-1.9\n if type(i) == Gtk.FlowBox:\n self.do_access(i)\n elif type(i) == Gtk.FlowBoxChild:\n self.change_focus_colors(i)\n except:\n pass\n \n\n def start(self):\n Gtk.main()\n\n def __init__(self):\n if os.path.isfile(noclose):\n self.closeafterrun = False\n else:\n self.closeafterrun = True\n \n try:\n self.config = load_config()\n except Exception as err:\n print(err)\n set_default_config()\n self.config = load_config()\n\n\n self.window = Gtk.Window(Gtk.WindowType.TOPLEVEL)\n self.window.connect(\"delete_event\", lambda x,y: Gtk.main_quit())\n\n self.window.set_title(menuname)\n self.window.set_border_width(1) # pour avoir une bordure noire\n self.window.set_icon_from_file(handymenuicon)\n\n self.window.set_position(Gtk.WindowPosition.CENTER_ALWAYS)\n self.window.set_resizable(False)\n self.window.set_decorated(False)\n self.window.modify_bg(Gtk.StateFlags.NORMAL, Gdk.color_parse(\"black\"))\n\n self.get_theme_colors()\n \n self.make_menu()\n self.onglets.grab_focus() # pour la gestion au clavier facilitée\n\n self.do_access(self.window)\n\n\n# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4\n","sub_path":"handymenu/handymenu-4.0/.pc/moveabout/handymenu.py","file_name":"handymenu.py","file_ext":"py","file_size_in_byte":16029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"605144883","text":"text = ''' \nThe Zen of Python, by Tim Peters\n美丽 is better than 丑陋.\n清楚 is better than 含糊.\n简单 is better than 复杂.\n复杂 is better than 难懂.\n单一 is better than 嵌套.\n稀疏 is better than 稠密.\n可读性计数.\nSpecial cases aren't special enough to 打破规则.\n即使练习会使得不再纯粹.\n但错误不应该用沉默来掩盖.\nUnless explicitly silenced.\n面对起义,拒绝猜的诱惑.\n有且只有一个办法.\nAlthough that way may not be obvious at first unless you're Dutch.\n尝试总比从未试过要强.\nAlthough never is often better than *right* now.\n如果执行很难被解释,那将是一个很糟的想法.\n如果执行很容易解释,这会是一个好点子.\nNamespaces are one honking great idea -- 让我们继续为之努力!\n'''\nimport re\ndictionary = {}\n# 统计参数中每个英文单词出现的次数,最后返还一个按词频降序排列的数组\ndef stats_text_en(text):\n text=text.replace(',',' ').replace('.',' ').replace('*',' ').replace('--',' ')\n text1=text.split()\n for i in text1:\n dictionary.update({i:text1.count(i)})#通过key:计数函数来更新字典\n return dictionary\n\n#打印统计英文词频的结果\nprint(\"统计英文词频的结果为:\")\nprint(sorted(dictionary.items(),key=lambda x:x[1],reverse=True))#sorted()排序;.items()遍历字典(键,值) 元组,\n\n\n#统计参数中每个中文汉字出现的次数,最后返回一个按字频降序排列的数组\ncndict = {}#定义一个空字典\ndef stats_text_cn(text):\n i = re.compile(\"[ \\,,\\;;\\.。:、\\{\\}\\[\\]「」\\*—~\\-\\??!\\!‘\\'’“\\\"”\\nA-Za-z0-9]\")\n text_rm_symbol = i.sub(\"\", text)\n for i in text:\n if u'\\u4e00' <= i <= u'\\u9fff': #判断一个unicode是否是汉字\n cndict[i] = text.count(i)\n return cndict\n\n#打印统计中文词频的结果\nprint(\"统计中文词频的结果为:\")\nprint(sorted(cndict.items(),key=lambda item:item[1],reverse = True))#为了阅读方便,检索完毕后对字典进行按值从大到小排序 \ndef stats_text(text):\n return dict(stats_text_en(text),**stats_text_cn(text))\ndef main():\n mdict={}\n mdict=stats_text(text)\n print(mdict)\n\nif __name__=='__main__':\n main() \n\n\n ","sub_path":"19100401/congboqiu/stats_word1.py","file_name":"stats_word1.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"617509068","text":"#!/usr/bin/python3\r\n\r\nimport sys, threading\r\n\r\nsys.setrecursionlimit(10**7) # max depth of recursion\r\nthreading.stack_size(2**25) # new thread will get stack of such size\r\n\r\nINT_MIN, INT_MAX = -4294967296,4294967296\r\nclass Tree:\r\n def read(self,nodes,lines):\r\n self.n = nodes\r\n self.key = [0 for i in range(self.n)]\r\n self.left = [0 for i in range(self.n)]\r\n self.right = [0 for i in range(self.n)]\r\n for i in range(self.n):\r\n [a, b, c] = lines[i]\r\n self.key[i] = a\r\n self.left[i] = b\r\n self.right[i] = c\r\n \r\n def isBSTUtil(self, ind, mini, maxi):\r\n # An empty tree is BST \r\n if ind == -1:\r\n return True\r\n \r\n # False if this node violates min/max constraint \r\n if self.key[ind] < mini or self.key[ind] > maxi: \r\n return False\r\n \r\n # Otherwise check the subtrees recursively \r\n # tightening the min or max constraint \r\n return (self.isBSTUtil(self.left[ind], mini, self.key[ind]-1) and\r\n self.isBSTUtil(self.right[ind], self.key[ind]+1, maxi)) \r\n\r\n def isBST(self):\r\n if self.n == 0:\r\n return True\r\n else:\r\n return (self.isBSTUtil(0, INT_MIN, INT_MAX)) \r\n \r\ndef main():\r\n tree = []\r\n nodes = int(sys.stdin.readline().strip())\r\n for i in range(nodes):\r\n tree.append(list(map(int, sys.stdin.readline().strip().split())))\r\n new_tree = Tree()\r\n new_tree.read(nodes,tree)\r\n if new_tree.isBST():\r\n print(\"CORRECT\")\r\n else:\r\n print(\"INCORRECT\")\r\n\r\n#nodes = 3\r\n#tree = [[2,1,2],[1,-1,-1],[3,-1,-1]]\r\n#new_tree = Tree()\r\n#new_tree.read(nodes,tree)\r\n#new_tree.isBST()\r\n\r\nthreading.Thread(target=main).start()\r\n","sub_path":"coursera exercises/is_bst.py","file_name":"is_bst.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"246932580","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\n\n\ndef cpu():\n\ttry:\n\t\tcpu = '%.2f%%' % (float(os.popen(\"uptime | awk '{print $11}' | sed 's/,//g'\").read().strip()) * 100,)\n\texcept:\n\t\tcpu = \"0.00%\"\n\treturn cpu\n\n\ndef memory():\n\ttry:\n\t\ttotal = float(os.popen(\"free -m | grep Mem | awk '{print $2}'\").read().strip())\n\t\tused = float(os.popen(\"free -m | grep /cache | awk '{print $3}'\").read().strip())\n\t\tmemory = '%.2f%%' % (used / total * 100,)\n\texcept:\n\t\tmemory = \"0.00%\"\n\treturn memory\n\n\ndef disk(loc='/dev/sda1'):\n\ttry:\n\t\tdisk = os.popen(\"df | grep %s | awk '{print $5}'| sed 's/G//g'\" % (loc,)).read().strip()\n\texcept:\n\t\tdisk = \"0.00%\"\n\treturn disk\n\n\ndef cache():\n\ttry:\n\t\ttotal = float(os.popen(\"free -m | grep Mem | awk '{print $2}'\").read().strip())\n\t\tused = float(os.popen(\"free -m | grep Mem | awk '{print $7}'\").read().strip())\n\t\tcache = '%.2f%%' % (used / total * 100,)\n\texcept:\n\t\tcache = \"0.00%\"\n\treturn cache\n\n\ndef bind():\n\ttry:\n\t\tos.popen(\"rm -f /home/wkubuntu/named/logs/named.stats\")\n\t\tos.popen(\"/home/wkubuntu/named/sbin/rndc stats\")\n\t\tbind = os.popen(\"grep 'queries resulted in successful answer' /home/wkubuntu/named/logs/named.stats | awk '{print $1}'\").read().strip()\n\t\tbind = int(bind)\n\texcept:\n\t\treturn 0\n\telse:\n\t\treturn bind","sub_path":"sub-daSta/src/fetchLocal.py","file_name":"fetchLocal.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"397583811","text":"ListaSusjedstvaGrafa = []\nbrojac = 0\n\ndef provjeraVrste(line, vrstaG):\n if line == '*Vertices': return 'V'\n elif line == '*Arcs': return 'A'\n elif line == '*Edges': return 'E'\n else: return vrstaG\n\ndef ciscenjeLinije(line):\n lista = line.split(' ') \n return lista[0]\n \ndef brisanjeNovihRedova(line):\n line = line.replace(\"\\r\",\"\")\n line = line.replace(\"\\n\",\"\")\n return (line)\n\ndef citajDatoteku(myMethod):\n global brojac\n global ListaSusjedstvaGrafa\n myEmptyIndexes = []\n \n prviBrojac = 0\n vrstaG = 'N' #N - Nema, V - Vertices, A - Arcs, E - Edges\n \n myFile = str(input(\"Unesite ime datoteke: \"))\n with open(myFile) as f:\n for line in f:\n line = brisanjeNovihRedova(line)\n if prviBrojac == 0:\n line = ciscenjeLinije(line)\n prviBrojac = prviBrojac+1\n \n vrstaG = provjeraVrste(line, vrstaG)\n \n if myMethod == 1: ucitMatrSus(line, vrstaG)\n if myMethod == 2: ucitMatrInc(line, vrstaG)\n if myMethod == 3: myEmptyIndexes = ucitListSus(line, vrstaG, myEmptyIndexes)\n \n if ListaSusjedstvaGrafa != '': \n concUcitListSus(myEmptyIndexes) \n \n \ndef concUcitListSus(myEmptyIndexes):\n global ListaSusjedstvaGrafa\n myStringList = []\n \n for i in range(0,len(ListaSusjedstvaGrafa),2):\n myConcat = str(ListaSusjedstvaGrafa[i]) + str(ListaSusjedstvaGrafa[i+1])\n myStringList.insert(len(myStringList), myConcat)\n \n ListaSusjedstvaGrafa.clear\n ListaSusjedstvaGrafa = myStringList\n #Ispis liste susjedstva grafa\n print (ListaSusjedstvaGrafa)\n\n\ndef ucitMatrSus(line, vrstaG):\n print(line)\n print(vrstaG)\n\ndef ucitMatrInc(line, vrstaG):\n print(line)\n print(vrstaG)\n \ndef zamjenaNavodnika(mojTrenutniString):\n \n numbChar = len(mojTrenutniString)\n mojTrenutniString = mojTrenutniString[:numbChar].replace('\"', \"'\") + mojTrenutniString[numbChar:]\n return mojTrenutniString\n\ndef removeDuplicates(listofElements):\n\n uniqueList = []\n for elem in listofElements:\n if elem not in uniqueList:\n uniqueList.append(elem) \n return uniqueList \n \ndef ucitListSus(line, vrstaG, myEmptyIndexes): \n global brojac\n global ListaSusjedstvaGrafa\n \n thisList = []\n\n if vrstaG == 'V':\n lista = line.split(' ') \n if line != '*Vertices':\n mojTrenutniString = lista[3]\n mojTrenutniString = zamjenaNavodnika(mojTrenutniString) \n ListaSusjedstvaGrafa.insert(brojac, mojTrenutniString + \":\")\n ListaSusjedstvaGrafa.insert(brojac+1, thisList)\n brojac = brojac + 2\n #print (ListaSusjedstvaGrafa)\n \n if vrstaG == 'E':\n lista = line.split(' ') \n if line != '*Edges' and line != '':\n mojIndex = int(lista[2])\n mojIndex = mojIndex + (mojIndex - 1)\n myEmptyIndexes.extend(str(mojIndex))\n \n ListaSusjedstvaGrafa[mojIndex].extend([lista[3]]) \n return myEmptyIndexes\n \ndef main():\n\n myMethod = int(input(\"1.) Ucitaj u matricu susjedstva\\n2.) Ucitaj u matricu incidencije\\n3.) Ucitaj u listu susjedstva grafa\\n \\nUnos: \"))\n citajDatoteku(myMethod)\n\n \nmain() \n","sub_path":"graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"464273357","text":"#! /usr/bin/env python3\n\n\"\"\"\n counts barcodes assigned to each variant(consider alternative and reference alleles independently),\n and writes only variants that havepassed a filter of at least 6 barcodes to an output file called\n filtered_variant_to_barcode.txt.​ The output file should use the same format as\n variant_to_barcode.txt​.\n\n usage: filter_variants.py -i variant_to_barcode.txt\n\"\"\"\nimport sys\nimport argparse\nimport logging\nimport numpy as np\n\ndef main(argv):\n \"\"\" main method\n :param argv: cmd line arguments\n \"\"\"\n # create logger\n # global logger\n # logger = createLogger('./log/assignment11.log',__name__)\n\n # parse cmd line arguments\n args = parseArgs(argv)\n variants_to_barcode_path = args.variant_to_barcode\n\n # read in file, return list of lines as iterable object\n line_generator = createLineGenerator(variants_to_barcode_path)\n # parse lines into dict retaining only unique barcodes\n variant_dict = createVariantBarcodeDict(line_generator)\n # write to file, applying filter\n writeFilteredVariantToBarcode(variant_dict, 6, 'filtered_variant_to_barcode.tsv')\n\ndef parseArgs(argv):\n parser = argparse.ArgumentParser(\n description=\"description here\")\n parser.add_argument(\"-i\", \"--variant_to_barcode\", required=True,\n help='path to variant_to_barcode.txt')\n\n args = parser.parse_args(argv[1:])\n return args\n\ndef createLineGenerator(variant_to_barcode_path):\n \"\"\"\n read in variant_to_barcode, return a iter object\n :param variant_to_barcode_path:\n :return: iter object\n \"\"\"\n with open(variant_to_barcode_path) as file:\n lines = file.readlines()\n\n return iter(lines)\n\n# split line on tab, take only unique in cols 1 and 2. return [name, ref_list, alt_list]\ndef createVariantBarcodeDict(line_generator):\n \"\"\"\n iterate through line_generator, create dictionary with structure ('variant':\n :param line_generator:\n :return: dict in structure {variant_id_!: [[UNIQUE ref barcodes], [UNIQUE alt barcodes]], variant_id_2: ...}\n \"\"\"\n barcode_dict = {}\n header = next(line_generator).strip()\n if not header.strip() == 'Variant_ID\\tREF_barcode\\tALT_barcode':\n raise Exception('The variant_to_barcode file does not have the expected header.\\n'\n 'Check your file. The header needs to be present and in format:\\n'\n 'Variant_ID\\tREF_barcode\\tALT_barcode')\n\n for line in line_generator:\n # strip white space and split on \\t\n line = line.strip().split('\\t')\n barcode_dict.setdefault(line[0], [])\n if not len(barcode_dict[line[0]]) == 0:\n # logger.warning('the barcode %s is not unique' % line[0])\n pass\n # split each column on ':'\n if len(line) < 3:\n # logger.warning('Variant %s has less than 2 sets of barcodes. '\n # 'Check the formatting and enter a dummy value for the missing values in the line.' % line)\n pass\n else:\n line[1] = np.array(line[1].split(':'))\n barcode_dict[line[0]].append(list(np.unique(line[1])))\n line[2] = np.array(line[2].split(':'))\n barcode_dict[line[0]].append(list(np.unique(line[2])))\n\n return barcode_dict\n\ndef writeFilteredVariantToBarcode(variant_barcode_dict, threshold, output_filename):\n \"\"\"\n write variant_barcode_dict to file, filtering on threshold\n :param variant_barcode_dict: see return explanation in createVariantBarcodeDict()\n :param threshold: number of (unique) barcodes below which to discard variant (filters strictly less than)\n :param output_filename: path to output file\n :return: none -- write to file\n \"\"\"\n with open(output_filename, 'w') as output_file:\n output_file.write('Variant_ID\\tREF_barcode\\tALT_barcode\\n')\n for variant_id, ref_alt in variant_barcode_dict.items():\n if len(ref_alt[0]) > threshold and len(ref_alt[1]) > threshold:\n line = variant_id + '\\t' + ':'.join(ref_alt[0]) + '\\t' + ':'.join(ref_alt[1]) + '\\n'\n output_file.write(line)\n\ndef createLogger(filename, logger_name, logging_conf = None):\n \"\"\"\n create logger in filemode append and format name-levelname-message with package/module __name__ (best practice from logger tutorial)\n :param filename: name of the file in which to log.\n :param logger_name: __name__ is recommended as a best practice in logger.config eg you can call this like so: createLogger(, __name__)\n (__name__ is a special variable in python)\n :param logging_conf: path to logging configuration file\n :returns: an instance of the configured logger\n \"\"\"\n # a config file is passed, load it\n if logging_conf:\n logging.config.fileConfig(logging_conf) # should include at least what is below\n # if it is not, configure as follows\n else:\n # create log for the year-month-day\n logging.basicConfig(\n filename='%s' % filename,\n filemode='w',\n format='%(name)s-%(levelname)s-%(asctime)s-%(message)s',\n datefmt='%I:%M:%S %p', # set 'datefmt' to hour-minute-second AM/PM\n level='DEBUG'\n )\n # return an instance of the configured logger\n return logging.getLogger(logger_name)\n\n\nif __name__ == \"__main__\":\n main(sys.argv)","sub_path":"assignment11/filter_variants.py","file_name":"filter_variants.py","file_ext":"py","file_size_in_byte":5421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"612453603","text":"from django.shortcuts import render\nfrom django.http import HttpResponse,Http404,HttpResponseRedirect\nfrom .models import Image, Location, Category\n# Create your views here.\n\ndef index(request):\n images =Image.objects.all()\n return render(request, 'index.html',{\"images\":images})\n\ndef search_results(request):\n if 'image' in request.GET and request.GET['image']:\n search_input = request.GET.get('image')\n searched_images = Image.search_by_category(search_input)\n message = f\"{search_input}\"\n\n return render(request, 'search.html', {\"message\":message, \"images\":searched_images})\n\n # el:\n # message = \"Please input something in the search field\"\n # return render(request, 'search.html', {'message':message})\n\n if 'location' in request.GET and request.GET['location']:\n search_term = request.GET.get('location')\n searched_images = Image.search_by_location(search_term)\n message = f\"{search_term}\"\n\n return render(request, 'search.html', {\"message\":message, \"images\":searched_images})\n\n else:\n message = \"Please input something in the search field\"\n return render(request, 'search.html', {'message':message}) \n\ndef get_image_by_id(request,image_id):\n try: \n images = Image.objects.get(id = image_id)\n except DoesNotExist:\n raise Http404()\n return render(request,\"image.html\", {\"image\":images})","sub_path":"gallery/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"484523189","text":"#!/usr/bin/env python3\n\nimport sys, json\nfrom collections import defaultdict\n\ndef val(regs, x):\n if x in regs:\n return regs[x]\n else:\n return int(x)\n\n\ndef main(args):\n program = [s.strip().split(\" \") for s in sys.stdin]\n regs = {c: 0 for c in \"abcd\"}\n\n pc = 0\n\n while pc < len(program):\n cmd = program[pc]\n if cmd[0] == \"cpy\":\n regs[cmd[2]] = val(regs, cmd[1])\n elif cmd[0] == \"inc\":\n regs[cmd[1]] += 1\n elif cmd[0] == \"dec\":\n regs[cmd[1]] -= 1\n elif cmd[0] == \"jnz\":\n if val(regs, cmd[1]) != 0:\n pc += int(cmd[2]) - 1\n pc += 1\n\n print(regs[\"a\"])\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv))\n","sub_path":"2016/A12a.py","file_name":"A12a.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"504086229","text":"#First we need to setup the dictionary with the answers and the questions\nquiz_dict={\"What is half of 18\":\"9\",\"what is half of 78\":\"39\"}\nfor i in range(0,len(quiz_dict.keys())):\n #my_answer=input(list(quiz_dict.keys())[i]+\"\\n\")\n if my_answer==list(quiz_dict.values())[i]:\n print (\"You have chosen the correct answer\")\n else:\n my_answer=input(list(quiz_dict.keys())[i]+\"\\n\")\n\n\n","sub_path":"Home Python Code/half_quiz.py","file_name":"half_quiz.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"306857989","text":"def divisor(num):\n divisors = []\n for i in range(1, num+1):\n if num%i == 0 :\n divisors.append(i)\n return divisors\n\ndef run():\n num = int(input(\"Ingresa un número: \"))\n print(divisor(num))\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"debugging.py","file_name":"debugging.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"201392243","text":"import tensorflow as tf \nimport numpy\nimport pandas as pd\ndf=pd.read_csv('/dmhack2017/tensorBoard/tensorflow_test_input.tsv', sep='\\t', header=None)\nd = df.values\nl = pd.read_csv('/dmhack2017/tensorBoard/tensorflow_test_label.tsv', sep='\\t', header=None)\nlabels = l.values\ndata = numpy.float32(d)\nlabels = numpy.array(l,'str')\n#print data, labels\n\nprint(data)\n\nlog_dir = '/dmhack2017/tensorBoard/logs'\nmax_steps = 10000\n\n#tensorflow\nsess = tf.InteractiveSession()\n\nembedding = tf.Variable(tf.stack(data), trainable=False, name=\"embedding\")\n\ntf.global_variables_initializer().run()\n\nsaver = tf.train.Saver()\nwriter = tf.summary.FileWriter(log_dir + '/projector', sess.graph)\n\nsaver.save(sess, log_dir+'/model.ckpt', global_step=max_steps)\n\n\n","sub_path":"tensorBoard/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"230004771","text":"import pymongo\nimport json\n\nconfig = json.loads(open(\"../site-config.json\").read())\nprint(config)\nclient = pymongo.MongoClient(config[\"mongoAddress\"])\n\ndb = client[config[\"mongoDatabase\"]]\ncouncils = db.councils\n\nif(councils.count() == 0):\n with open(\"councils.txt\") as file:\n lines = file.readlines()\n i = 0;\n for l in lines:\n c = l.strip(\"\\n\").split(\",\")\n display_name = c[0]+\" (\"+c[1]+\")\"\n councils.insert_one({\"name\": c[0], \"type\": c[1], \"display_name\": display_name, \"id\": i})\n i += 1\n\ncodes = db.pcncodes\nif codes.count() == 0:\n with open(\"codes.txt\") as file2:\n lines = file2.readlines()\n for l in lines:\n c = l.strip(\"\\n\").split(\",\")\n full = c[0] + \" : \" + c[1];\n codes.insert_one({\"code\": int(c[0]), \"type\": c[1], \"display_name\": full})\n\nstages = db.stages\nif stages.count() == 0:\n with open(\"stages.txt\") as file3:\n lines = file3.readlines()\n for l in lines:\n c = l.strip(\"\\n\").split(\",\")\n stages.insert_one({\"stage\": c[0], \"badge\": c[1], \"description\": c[2]})\n","sub_path":"seed_files/import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"431342273","text":"#\n# [274] H-Index\n#\n# https://leetcode.com/problems/h-index/description/\n#\n# algorithms\n# Medium (34.14%)\n# Total Accepted: 107K\n# Total Submissions: 313.5K\n# Testcase Example: '[3,0,6,1,5]'\n#\n# Given an array of citations (each citation is a non-negative integer) of a\n# researcher, write a function to compute the researcher's h-index.\n#\n# According to the definition of h-index on Wikipedia: \"A scientist has index h\n# if h of his/her N papers have at least h citations each, and the other N − h\n# papers have no more than h citations each.\"\n#\n# Example:\n#\n#\n# Input: citations = [3,0,6,1,5]\n# Output: 3\n# Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each\n# of them had\n# ⁠ received 3, 0, 6, 1, 5 citations respectively.\n# Since the researcher has 3 papers with at least 3 citations each and the\n# remaining\n# two with no more than 3 citations each, her h-index is 3.\n#\n# Note: If there are several possible values for h, the maximum one is taken as\n# the h-index.\n#\n#\n\n# Jarron:\n# - Sort, find. O(N lg N)\n# - b search\n\n# REVIEW:\n# - bucket\n\n\nclass Solution:\n # Sort\n # def hIndex(self, citations):\n # \"\"\"\n # :type citations: List[int]\n # :rtype: int\n # \"\"\"\n # if not citations:\n # return 0\n #\n # citations.sort()\n # if citations[0] >= len(citations):\n # return len(citations)\n #\n # for h in reversed(range(1, len(citations))):\n # if citations[len(citations) - h] >= h and citations[len(citations) - h - 1] <= h:\n # return h\n #\n # return 0\n\n # binary search\n # def hIndex(self, citations):\n # \"\"\"\n # :type citations: List[int]\n # :rtype: int\n # \"\"\"\n # if not citations:\n # return 0\n #\n # left = 0\n # right = len(citations)\n #\n # while left < right:\n # mid = (left + right) // 2\n #\n # count = sum(c <= mid for c in citations)\n # if count < len(citations) - mid:\n # left = mid + 1\n # else:\n # right = mid\n # return left\n\n # Bucket\n def hIndex(self, citations):\n \"\"\"\n :type citations: List[int]\n :rtype: int\n \"\"\"\n\n bucket = [0] * (len(citations) + 1)\n for c in citations:\n if c >= len(citations):\n bucket[-1] += 1\n else:\n bucket[c] += 1\n\n total = 0\n for i in reversed(range(len(bucket))):\n total += bucket[i]\n if total >= i:\n return i\n return 0\n","sub_path":"src/274.h-index.python3.py","file_name":"274.h-index.python3.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"146036794","text":"from queue import PriorityQueue\n\nimport pygame\nfrom pygame.locals import *\n\n\nclass Drone:\n def __init__(self, x, y):\n self._x = x\n self._y = y\n self.open_list = []\n self.close_list = dict()\n self.open_list.append((0, (self._x, self._y)))\n self.visited = []\n self.priority_queue = PriorityQueue()\n\n def get_X(self):\n return self._x\n\n def get_Y(self):\n return self._y\n\n def move(self, detectedMap):\n pressed_keys = pygame.key.get_pressed()\n if self.x > 0:\n if pressed_keys[K_UP] and detectedMap.surface[self.x - 1][self.y] == 0:\n self.x = self.x - 1\n if self.x < 19:\n if pressed_keys[K_DOWN] and detectedMap.surface[self.x + 1][self.y] == 0:\n self.x = self.x + 1\n\n if self.y > 0:\n if pressed_keys[K_LEFT] and detectedMap.surface[self.x][self.y - 1] == 0:\n self.y = self.y - 1\n if self.y < 19:\n if pressed_keys[K_RIGHT] and detectedMap.surface[self.x][self.y + 1] == 0:\n self.y = self.y + 1\n\n def mapWithDrone(self, mapImage):\n drona = pygame.image.load(\"drona.png\")\n mapImage.blit(drona, (self.y * 20, self.x * 20))\n\n return mapImage\n\n\n","sub_path":"UBB_CS_II_sem_2/AI/Laboratory_2/Assignment2/taks1/Model/DroneClass.py","file_name":"DroneClass.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"384722942","text":"from JumpScale import j\nimport signal\nimport time\nfrom multiprocessing import Pool\nfrom threading import Thread\nfrom JumpScale.baselib.jobcontroller.models.JobsCollections import JobsCollection\nimport requests\n\n\ndef run_action(repo_path, service_key, action_name, args=None):\n \"\"\"\n run_action execute a single action from a service\n \"\"\"\n if not args:\n args = {}\n\n repo = j.atyourservice.repoGet(repo_path)\n service = repo.db.services.get(service_key).objectGet(repo)\n\n job = service.getJob(action_name, args=args)\n p = job.executeInProcess()\n service.model.actions[action_name].lastRun = j.data.time.epoch\n service.saveAll()\n\n\ndef job_cleanup():\n jobs = set()\n jc = JobsCollection()\n job_keys = jc._list_keys(toEpoch=j.data.time.getEpochAgo('-2d'))\n for job_key in job_keys:\n index = jc.getIndexFromKey(job_key)\n if index:\n items = index.split(':')\n regex = \"%s:%s:%s:.*:%s:%s\" % (items[0], items[1], items[2], items[4], items[5])\n jobs.add(regex)\n jc._db.index_remove(list(jobs))\n return\n\n\ndef do_run(run_key, callback=None):\n \"\"\"\n do_run execute a run asyncronously\n at the end of the run or if an error occurs during exection a request is made to callback to\n notify the event (ok/error)\n \"\"\"\n\n error_msg = None\n\n try:\n run = j.core.jobcontroller.db.runs.get(run_key).objectGet()\n run.execute()\n except Exception as e:\n # WE TRY TO RE-EXECUTE THE FAILING RUN.\n error_msg = str(e)\n try:\n run = j.core.jobcontroller.db.runs.get(run_key).objectGet()\n run.execute()\n except Exception as e:\n error_msg = str(e)\n finally:\n if callback:\n body = {\n 'state': str(run.state),\n 'key': run.key\n }\n if error_msg:\n body['error'] = error_msg\n requests.post(callback, json=body)\n\n\nclass Server:\n \"\"\"AtYourService server\"\"\"\n\n def __init__(self, redis_config=None):\n redis_config = redis_config or j.atyourservice.config['redis']\n self._command_queue = j.servers.kvs.getRedisStore(\"ays_server\", namespace='db', **redis_config)\n\n self.logger = j.atyourservice.logger\n\n self._recurring_loop = RecurringLoop()\n self._workers = Pool()\n\n # self._set_signale_handler()\n\n self._running = False\n\n def _set_signale_handler(self):\n def stop(signum, stack_frame):\n self.stop()\n\n signal.signal(signal.SIGINT, stop)\n\n def start(self):\n if self._running is True:\n return\n\n self._recurring_loop.start()\n\n self.logger.info('starting server')\n self._running = True\n\n while self._running:\n payload = self._command_queue.queueGet('command', timeout=2)\n if payload is None:\n # timeout without receiving command\n continue\n\n try:\n request = j.data.serializer.json.loads(payload.decode())\n except Exception as e:\n self.logger.error(\"can't deserialize payload : %s\" % str(e))\n continue\n\n if not j.data.types.dict.check(request) or 'command' not in request:\n self.logger.error(\"request doesn't have proper format, should be a dict with a 'command' key. request is: %s\" % request)\n continue\n\n self._dispatch(request)\n\n self.logger.info('server stopped')\n\n def stop(self):\n if self._recurring_loop.is_alive():\n self.logger.info(\"stopping monitor recurring process\")\n self._recurring_loop.stop()\n # FIXME: why: assert self._parent_pid == os.getpid(), 'can only join a child process'\n # self._recurring_loop.join()\n\n if self._running:\n self._running = False\n self.logger.info(\"stopping server\")\n\n self.logger.info(\"wait for all jobs to finish\")\n self._workers.close()\n self._workers.join()\n\n def _dispatch(self, request):\n self.logger.info('dispatch request %s' % request)\n\n # TODO: implement other commands\n if request['command'] == 'execute':\n self._execute(request)\n\n elif request['command'] == 'event':\n self._progagate_event(request)\n\n elif request['command'] == 'run':\n self._do_run(request)\n\n def _execute(self, request):\n if 'action' not in request:\n self.logger.error('execute command received but not action specified in request.')\n return\n\n try:\n self.logger.info(\"execute action {action} on {service_key}\".format(**request))\n self._workers.apply_async(run_action, (\n request['repo_path'],\n request['service_key'],\n request['action'],\n request.get('args', {})))\n except Exception as e:\n self.logger.error('error: %s' % str(e))\n\n def _progagate_event(self, request):\n\n if 'event' not in request:\n self.logger.error('event command received but not event type specified in request.')\n return\n\n event_type = request['event']\n args = request.get('args', {})\n\n for repo in j.atyourservice.reposList():\n for service in repo.services:\n if len(service.model.actionsEvent) <= 0:\n continue\n\n for action_name, event_obj in service.model.actionsEvent.items():\n if event_obj.event != event_type:\n continue\n\n self.logger.info('event %s propagated to %s from %s' % (event_type, service, repo))\n\n event_obj.lastRun = j.data.time.epoch\n service.save()\n\n self._workers.apply_async(run_action, (\n service.aysrepo.path,\n service.model.key,\n event_obj.action,\n args))\n\n def _do_run(self, request):\n if 'run_key' not in request:\n self.logger.error(\"run_key not present in request. can't execute run\")\n return\n\n self.logger.info(\"execute run {}\".format(request['run_key']))\n self._workers.apply_async(do_run, (\n request['run_key'],\n request.get('callback_url')))\n\n\nclass RecurringLoop(Thread):\n \"\"\"\n Loop that triggers the recurring action of all the services\n\n The loop walks over all the services from all the repos. When it find a service with recurring actions,\n it send a command to the main server to ask to execute the action.\n The main server then received the request, create the jobs and execute it asynchronously.\n The main server doesn't wait for the job to complete but instead send the execute of the job to a pool of processes\n that take care of waiting for the job to complete and saving it's state back the db.\n \"\"\"\n\n def __init__(self):\n super(RecurringLoop, self).__init__()\n self.logger = j.atyourservice.logger\n self._running = False\n self._workers = Pool()\n\n def run(self):\n self.logger.info('starting recurring thread')\n self._running = True\n\n while self.is_alive() and self._running:\n try:\n job_cleanup()\n except Exception as e:\n self.logger.error(\"error while cleaning jobs : %s\" % str(e))\n continue\n repos = j.atyourservice.reposList()\n for repo in repos:\n self.logger.debug('inspect %s for recurring actions' % repo)\n for service in repo.services:\n if len(service.model.actionsRecurring) <= 0:\n continue\n\n now = j.data.time.epoch\n for action_name, recurring_obj in service.model.actionsRecurring.items():\n\n if recurring_obj.lastRun == 0 or now > (recurring_obj.lastRun + recurring_obj.period):\n\n self.logger.info('recurring job for %s' % service)\n\n try:\n self._workers.apply_async(run_action, (\n service.aysrepo.path,\n service.model.key,\n action_name,\n ))\n except Exception as e:\n self.logger.error('error: %s' % str(e))\n\n time.sleep(5)\n\n def stop(self):\n if self._running:\n self._running = False\n\n\n\ndef main():\n \"\"\"\n only for testing\n \"\"\"\n server = Server()\n server.start()\n\nif __name__ == '__main__':\n main()\n","sub_path":"lib/JumpScale/baselib/atyourservice81/AtYourServiceDaemon.py","file_name":"AtYourServiceDaemon.py","file_ext":"py","file_size_in_byte":8827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"109623354","text":"# 公共工具类\nimport functools\n\nfrom flask import session, current_app, g\nfrom info.models import User\n\n\n# 模版过滤器\ndef do_index_class(index):\n index_mapping = {1: 'first',\n 2: 'second',\n 3: 'third'}\n return index_mapping.get(index, '')\n\ndef gender2zh(gender):\n gender_mapping = {'MAN': '男',\n 'WOMAN': '女'}\n return gender_mapping.get(gender)\n\n# def get_login_user():\n# user_id = session.get('user_id', None)\n# user = None\n# if user_id:\n# try:\n# user = User.query.get(user_id)\n# except Exception as e:\n# current_app.logger.error(e)\n# return user\n# return None\n\n# 用来获取user信息并保持在g变量中的装饰器\ndef get_login_user(f):\n @functools.wraps(f)\n def warrper(*args, **kwargs):\n user_id = session.get('user_id', None)\n user = None\n if user_id:\n try:\n user = User.query.get(user_id)\n except Exception as e:\n current_app.logger.error(e)\n g.user = user\n return f(*args, **kwargs)\n\n return warrper\n","sub_path":"info/utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"286800300","text":"\"\"\"\nConversion of scattering cross section from SANS (I(q), or rather, ds/dO) in absolute\nunits (cm-1)into SESANS correlation function G using a Hankel transformation, then converting\nthe SESANS correlation function into polarisation from the SESANS experiment\n\nEverything is in units of metres except specified otherwise (NOT TRUE!!!)\nEverything is in conventional units (nm for spin echo length)\n\nWim Bouwman (w.g.bouwman@tudelft.nl), June 2013\n\"\"\"\n\nfrom __future__ import division\n\nimport numpy as np\nfrom numpy import pi, exp\nfrom scipy.special import jv as besselj\n#import direct_model.DataMixin as model\n \ndef make_q(q_max, Rmax):\n r\"\"\"\n Return a $q$ vector suitable for SESANS covering from $2\\pi/ (10 R_{\\max})$\n to $q_max$. This is the integration range of the Hankel transform; bigger range and \n more points makes a better numerical integration.\n Smaller q_min will increase reliable spin echo length range. \n Rmax is the \"radius\" of the largest expected object and can be set elsewhere.\n q_max is determined by the acceptance angle of the SESANS instrument.\n \"\"\"\n from sas.sascalc.data_util.nxsunit import Converter\n\n q_min = dq = 0.1 * 2*pi / Rmax\n return np.arange(q_min,\n Converter(q_max[1])(q_max[0],\n units=\"1/A\"),\n dq)\n \ndef make_all_q(data):\n \"\"\"\n Return a $q$ vector suitable for calculating the total scattering cross section for\n calculating the effect of finite acceptance angles on Time of Flight SESANS instruments.\n If no acceptance is given, or unwanted (set \"unwanted\" flag in paramfile), no all_q vector is needed.\n If the instrument has a rectangular acceptance, 2 all_q vectors are needed.\n If the instrument has a circular acceptance, 1 all_q vector is needed\n \n \"\"\"\n if not data.has_no_finite_acceptance:\n return []\n elif data.has_yz_acceptance(data):\n # compute qx, qy\n Qx, Qy = np.meshgrid(qx, qy)\n return [Qx, Qy]\n else:\n # else only need q\n # data.has_z_acceptance\n return [q]\n\ndef transform(data, q_calc, Iq_calc, qmono, Iq_mono):\n \"\"\"\n Decides which transform type is to be used, based on the experiment data file contents (header)\n (2016-03-19: currently controlled from parameters script)\n nqmono is the number of q vectors to be used for the detector integration\n \"\"\"\n nqmono = len(qmono)\n if nqmono == 0:\n result = call_hankel(data, q_calc, Iq_calc)\n elif nqmono == 1:\n q = qmono[0]\n result = call_HankelAccept(data, q_calc, Iq_calc, q, Iq_mono)\n else:\n Qx, Qy = [qmono[0], qmono[1]]\n Qx = np.reshape(Qx, nqx, nqy)\n Qy = np.reshape(Qy, nqx, nqy)\n Iq_mono = np.reshape(Iq_mono, nqx, nqy)\n qx = Qx[0, :]\n qy = Qy[:, 0]\n result = call_Cosine2D(data, q_calc, Iq_calc, qx, qy, Iq_mono)\n\n return result\n\ndef call_hankel(data, q_calc, Iq_calc):\n return hankel((data.x, data.x_unit),\n (data.lam, data.lam_unit),\n (data.sample.thickness,\n data.sample.thickness_unit),\n q_calc, Iq_calc)\n \ndef call_HankelAccept(data, q_calc, Iq_calc, q_mono, Iq_mono):\n return hankel(data.x, data.lam * 1e-9,\n data.sample.thickness / 10,\n q_calc, Iq_calc)\n \ndef call_Cosine2D(data, q_calc, Iq_calc, qx, qy, Iq_mono):\n return hankel(data.x, data.y, data.lam * 1e-9,\n data.sample.thickness / 10,\n q_calc, Iq_calc)\n \ndef TotalScatter(model, parameters): #Work in progress!!\n# Calls a model with existing model parameters already in place, then integrate the product of q and I(q) from 0 to (4*pi/lambda)\n allq = np.linspace(0,4*pi/wavelength,1000)\n allIq = 1\n integral = allq*allIq\n \n\n\ndef Cosine2D(wavelength, magfield, thickness, qy, qz, Iqy, Iqz, modelname): #Work in progress!! Needs to call model still\n#==============================================================================\n# 2D Cosine Transform if \"wavelength\" is a vector\n#==============================================================================\n#allq is the q-space needed to create the total scattering cross-section\n\n Gprime = np.zeros_like(wavelength, 'd')\n s = np.zeros_like(wavelength, 'd')\n sd = np.zeros_like(wavelength, 'd')\n Gprime = np.zeros_like(wavelength, 'd')\n f = np.zeros_like(wavelength, 'd')\n for i, wavelength_i in enumerate(wavelength):\n z = magfield*wavelength_i\n allq=np.linspace() #for calculating the Q-range of the scattering power integral\n allIq=np.linspace() # This is the model applied to the allq q-space. Needs to refference the model somehow\n alldq = (allq[1]-allq[0])*1e10\n sigma[i]=wavelength[i]^2*thickness/2/pi*np.sum(allIq*allq*alldq)\n s[i]=1-exp(-sigma)\n for j, Iqy_j, qy_j in enumerate(qy):\n for k, Iqz_k, qz_k in enumerate(qz):\n Iq = np.sqrt(Iqy_j^2+Iqz_k^2)\n q = np.sqrt(qy_j^2 + qz_k^2)\n Gintegral = Iq*cos(z*Qz_k)\n Gprime[i] += Gintegral\n# sigma = wavelength^2*thickness/2/pi* allq[i]*allIq[i]\n# s[i] += 1-exp(Totalscatter(modelname)*thickness)\n# For now, work with standard 2-phase scatter\n\n\n sd[i] += Iq\n f[i] = 1-s[i]+sd[i]\n P[i] = (1-sd[i]/f[i])+1/f[i]*Gprime[i]\n\n\n\n\ndef HankelAccept(wavelength, magfield, thickness, q, Iq, theta, modelname):\n#==============================================================================\n# HankelTransform with fixed circular acceptance angle (circular aperture) for Time of Flight SESANS\n#==============================================================================\n#acceptq is the q-space needed to create limited acceptance effect\n SElength= wavelength*magfield\n G = np.zeros_like(SElength, 'd')\n threshold=2*pi*theta/wavelength\n for i, SElength_i in enumerate(SElength):\n allq=np.linspace() #for calculating the Q-range of the scattering power integral\n allIq=np.linspace() # This is the model applied to the allq q-space. Needs to refference the model somehow\n alldq = (allq[1]-allq[0])*1e10\n sigma[i]=wavelength[i]^2*thickness/2/pi*np.sum(allIq*allq*alldq)\n s[i]=1-exp(-sigma)\n\n dq = (q[1]-q[0])*1e10\n a = (x 1:\n lo = heappop(heap)\n hi = heappop(heap)\n for pair in lo[1:]:\n pair[1] = '0' + pair[1]\n for pair in hi[1:]:\n pair[1] = '1' + pair[1]\n heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])\n return sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p))\n","sub_path":"compression/custom_hmm/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"640290341","text":"# Chocolate Feast \n'''\n feast 잔치\n wrappers 포장지\n\n 초콜릿을 사먹는데 포장지를 2개 반납하면 초콜릿을 1개 줌\n 총 초콜릿을 몇개 먹는지 구하기\n \n ex)\n n = 15\n cost = 3\n m = 2 (포장지 몇 개 반납시 초콜릿 주는지)\n\n 초콜릿 5 포장지 5\n -> 4 반납 2 초콜릿 나머지 1\n 초콜릿 2 포장지 3\n -> 2 반납 1 초콜릿 나머지 1\n 초콜릿 1 포장지 2\n -> 2 반납 1 초콜릿 나머지 0\n 초콜릿 1 포장지 1\n => 5 + 2 + 1 + 1 = 9\n\n 1 <= t <= 1000 test cases\n 2 <= n <= 10^5\n 1 <= c <= n\n 2 <= m <= n\n'''\n\ndef chocolateFeast(n, c, m):\n chocolate = int(n / c)\n wrappers = chocolate\n\n while wrappers >= m:\n temp = int(wrappers / m)\n wrappers %= m\n chocolate += temp\n wrappers += temp\n\n return chocolate\n\nif __name__ == '__main__':\n t = int(input())\n\n for t_itr in range(t):\n ncm = input().split()\n n = int(ncm[0])\n c = int(ncm[1])\n m = int(ncm[2])\n\n result = chocolateFeast(n, c, m)\n\n print(result)\n","sub_path":"Chocolate Feast/Chocolate_Feast.py","file_name":"Chocolate_Feast.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"577548315","text":"import urllib.request, urllib.error, urllib.parse, http.cookiejar\nimport os\nfrom bs4 import BeautifulSoup\nfrom common import HttpHeaders\n\nMASTER_NAME = '大神戴腾的爪牙'\n\nHOST = 'http://www.qiushibaike.com'\nDIRNAME = 'qb'\n\ncwdpath = os.getcwd()\nprint(cwdpath)\n\n\ndef decode_page(content):\n soup = BeautifulSoup(content)\n for tag in soup.find_all('div', class_='thumb'):\n sub = tag.find('a')\n href = sub.attrs['href']\n request = urllib.request.Request(HOST + href)\n print(MASTER_NAME + \"打开了网页: <\" + request.get_full_url() + \">\")\n for key in HttpHeaders.headers:\n request.add_header(key, HttpHeaders.headers[key])\n request.add_header('Referer', 'http://www.qiushibaike.com/')\n request.add_header('Origin', 'http://www.qiushibaike.com/')\n try:\n response = urllib.request.urlopen(request)\n except urllib.error.HTTPError as e:\n print(e.reason, e.code, e.msg)\n print('出现异常,%s已停止运行' % MASTER_NAME)\n return\n data = response.read()\n if data is not None:\n decode_detail(data)\n\n\ndef decode_detail(content):\n soup = BeautifulSoup(content)\n for tag in soup.find_all('div', class_='content'):\n submit_date = tag.attrs['title']\n submit_date = submit_date.split(' ')[0]\n for tag in soup.find_all('div', class_='thumb'):\n try:\n sub = tag.find('img')\n href = sub.attrs['src']\n filename = sub.attrs['alt']\n print(MASTER_NAME + \"发现标题: <\" + filename + \">\")\n print(MASTER_NAME + \"发现链接: <\" + href + \">\")\n download_file(href, submit_date, filename)\n except AttributeError as e:\n print(e)\n print('出现异常,%s已停止运行' % MASTER_NAME)\n\n\ndef download_file(url, date, filename):\n request = urllib.request.urlopen(url)\n data = request.read()\n fileDir = cwdpath + \"\\\\\" + DIRNAME + \"\\\\\" + date\n try:\n if not os.path.exists(fileDir):\n os.makedirs(fileDir)\n except Exception as e:\n print(e)\n print('出现异常,%s已停止运行' % MASTER_NAME)\n filePath = fileDir + \"\\\\\" + filename + \".jpg\"\n if not os.path.exists(filePath):\n file = open(filePath, 'wb')\n file.write(data)\n file.close()\n print(MASTER_NAME + \"保存文件成功!\")\n else:\n print(MASTER_NAME + \"侦测到文件已存在,未下载!\")\n\n\ndef page_loop(page=1):\n print(\"第%s页\" % page)\n url = \"http://www.qiushibaike.com/imgrank/page/%s?s=4743947\" % page\n request = urllib.request.Request(url)\n print(request.get_full_url())\n for key in HttpHeaders.headers:\n request.add_header(key, HttpHeaders.headers[key])\n request.add_header('Referer', 'http://www.qiushibaike.com/')\n request.add_header('Origin', 'http://www.qiushibaike.com/')\n try:\n response = urllib.request.urlopen(request)\n except urllib.error.HTTPError as e:\n print(e.reason, e.code, e.msg)\n print('出现异常,%s已停止运行' % MASTER_NAME)\n return\n\n text = response.read()\n decode_page(text)\n page_loop(page + 1)\n\n\ndef login():\n url = 'http://www.qiushibaike.com/session.js'\n postData = {\n 'login': '江东子弟何惧于天下',\n 'password': '223512',\n 'remember_me': 'checked',\n 'duration': '-1'\n }\n cj = http.cookiejar.LWPCookieJar()\n cookie_support = urllib.request.HTTPCookieProcessor(cj)\n opener = urllib.request.build_opener(cookie_support, urllib.request.HTTPHandler)\n urllib.request.install_opener(opener)\n postDataStr = urllib.parse.urlencode(postData)\n headers = HttpHeaders.headers\n headers['Accept'] = 'application/json, text/javascript, */*; q=0.01'\n headers['Referer'] = 'http://www.qiushibaike.com/'\n headers['Origin'] = 'http://www.qiushibaike.com'\n headers['Host'] = 'www.qiushibaike.com'\n request = urllib.request.Request(url=url, data=postDataStr.encode(\"utf-8\"), headers=headers, method='POST')\n print(request.get_full_url())\n try:\n response = urllib.request.urlopen(request)\n except urllib.error.HTTPError as e:\n print(e.reason, e.code, e.msg)\n print('出现异常,%s已停止运行' % MASTER_NAME)\n return\n\n text = response.read()\n print(text)\n print(MASTER_NAME + \"登录了糗百网页\")\n\nif __name__ == '__main__':\n login()\n page_loop()\n\n\n","sub_path":"qsbk.py","file_name":"qsbk.py","file_ext":"py","file_size_in_byte":4489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"510921997","text":"from simplejson.tests import test_namedtuple\n#from __main__ import name\n_plugins_path_list=[]\n_plugins={}\nheaders={}\n\nimport os\nimport importlib\n\n_filehandles={}\n\nimport namb.files\n\nclass FileHandle(object):\n\n def __init__(self, pluginname):\n _filehandles[pluginname]=self\n self.__path=os.path.join(__path__[0], \"..\", \".settings\", pluginname)\n if not os.path.isdir(self.path):\n os.mkdir(self.path)\n\n def get_file_handle(self, *path):\n if \".\" in path or \"..\" in path:\n raise Exception(\"Illegal to traverse out of path!\")\n return None\n dirs=path[:-1]\n if dirs:\n os.makedirs(os.path.join(*dirs))\n p=os.path.join(dirs)\n return namb.files.file_handle(p, 'a+')\n\ndef load():\n init()\n load_plugins_headers()\n\ndef init():\n l = [os.path.join(__path__[0], i) for i in os.listdir(__path__[0])]\n ll = [i for i in l if os.path.isdir(i)]\n global _plugins_path_list\n _plugins_path_list=ll\n return _plugins_path_list\n\ndef load_plugins_headers():\n for e in _plugins_path_list:\n name = e.split(os.sep)[-1]\n m=importlib.import_module(\"plugins.\"+name)\n headers[m.NAME]=m\n return headers\n\ndef install_plugin(name):\n if headers[name].is_installed():\n return\n return headers[name].install()\n \ndef is_installed(name):\n return headers[name].is_installed()\n\ndef load_plugin(name):\n import main\n if compare_versions(main.NAMB_VERSION, headers[name].NAMB_VERSION) > -1:\n import extensions\n for i in headers[name].DEPENDENCIES:\n if i not in extensions.headers:\n raise Exception(\"Dependency not satisfied: %s\" % (i))\n if not headers[name].is_installed():\n raise Exception(\"Plugin not installed\")\n #headers[name].install()\n _plugins[name]=headers[name].load()\n return _plugins[name]!=None\n else:\n raise Exception(\"Version of plugin not supported.\")\n\ndef get_plugin(name):\n return _plugins[name] if name in _plugins else None\n\ndef is_loaded(name):\n return name in _plugins\n\ndef compare_versions(v1, v2):\n v1_splitted=tuple(int(i) for i in v1.split(\".\"))\n v2_splitted=tuple(int(i) for i in v2.split(\".\"))\n if v1_splitted == v2_splitted:\n return 0\n elif v1_splitted > v2_splitted:\n return 1\n elif v1_splitted < v2_splitted:\n return -1\n else:\n raise Exception(\"Version checking failed for versions: %s and %s\" % (v1, v2))\n return -99\n \n \n","sub_path":"plugins/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"445625539","text":"import numpy as np ## Imports Python's numerical library\nimport matplotlib.pyplot as plt ## Import matplotlib for plotting\nplt.style.use('fivethirtyeight') ## Sets up pretty plots and python magic for inline plots\n#%matplotlib inline\n\nk = 9e9 ## 1 over 4 pi epsilon zero\nQ = 1e-3 ## Charge of ring\na = 1 ## Radius of ring\nq = 1e-6 ## Charge of test charge\nm = 1e-3 ## Mass of test charge\nc = k*q*Q/m ## Collecting all the constants\n\ndt=0.001\ntime = np.arange(0,0.1,dt)\n\n## Set up arrays for exact differential equation and set all entries to zero initially\npos = np.zeros(len(time))\nvel = np.zeros(len(time))\naccel = np.zeros(len(time))\n\n## Set up arrays for approximate differential equation and set all entries to zero initially\nposapprox = np.zeros(len(time))\nvelapprox = np.zeros(len(time))\naccelapprox = np.zeros(len(time))\n\n## Set the initial position and velocity for the exact model\npos[0] = 10\nvel[0] = 0\n\n## Tell the approximate model to start from the same conditions\nposapprox[0] = pos[0]\nvelapprox[0] = vel[0]\n\ni = 0 ## Set up counter\n## Calculation loop\nwhile i < len(time) - 1:\n ## Perform Euler-Chromer integration for the exact differential equation\n accel[i] = -1*c*pos[i]/np.sqrt(pos[i]**2+a**2)**(3/2)\n vel[i+1] = vel[i] + accel[i]*dt\n pos[i+1] = pos[i] + vel[i+1]*dt\n ## Perform Euler-Chromer integration for the approximate differential equation\n accelapprox[i] = -1*c*posapprox[i]/a**3\n velapprox[i+1] = velapprox[i] + accelapprox[i]*dt\n posapprox[i+1] = posapprox[i] + velapprox[i+1]*dt\n ## Update the step\n i = i + 1\n \n## Plot the results\nplt.figure(figsize=(8,8))\nplt.plot(time,pos)\nplt.plot(time,posapprox)\nplt.show() \n","sub_path":"week1/exercise11.py","file_name":"exercise11.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"80353926","text":"def add(stringNumbers):\n if stringNumbers == \"\":\n return 0\n else:\n if stringNumbers[0:2] == '//':\n delimiter = stringNumbers[2]\n stringNumbers = stringNumbers[4:]\n else:\n delimiter = ','\n \n numbers = []\n splited = stringNumbers.split(delimiter)\n for num in splited:\n numbers += num.split('\\n')\n if any(int(number) < 0 for number in numbers):\n raise Exception(\"Negative number is not allow\")\n return sum([int(number) for number in numbers])\n","sub_path":"string_calculator.py","file_name":"string_calculator.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"234376030","text":"import random\n# 定义参量\nNUM_OF_PARTS = 5\nTEST_PART = 4\n# 训练集随机选取部分\nPART_OF_TRAIN = 1\n\n# 数据集划分函数\ndef set_divide(set, isTrain):\n assert TEST_PART in range(NUM_OF_PARTS)\n assert PART_OF_TRAIN <= 1 and PART_OF_TRAIN >= 0\n sum = len(set)\n part = int(sum/NUM_OF_PARTS)\n # 余数\n rest = sum % NUM_OF_PARTS\n # 开始位置和结束位置\n start = TEST_PART*part + min(rest,TEST_PART)\n end = start + part\n if TEST_PART None :\n self.b = b\n self.e = e\n\n def __iter__ (self) -> Iterator[int] :\n return self\n\n def __next__ (self) -> int :\n if self.b == self.e :\n raise StopIteration()\n v = self.b\n self.b += 1\n return v\n\nclass MyUnitTests (TestCase) :\n def setUp (self) :\n self.a = [\n range_iterator_1,\n lambda b, e : iter(range(b, e))]\n\n def test_1 (self) :\n for f in self.a :\n with self.subTest(msg=f.__name__) :\n p = f(2, 2)\n self.assertIs(p, iter(p))\n self.assertRaises(StopIteration, next, p)\n\n def test_2 (self) :\n for f in self.a :\n with self.subTest(msg=f.__name__) :\n p = f(2, 3)\n self.assertIs(p, iter(p))\n self.assertEqual(next(p), 2)\n self.assertRaises(StopIteration, next, p)\n\n def test_3 (self) :\n for f in self.a :\n with self.subTest(msg=f.__name__) :\n p = f(2, 4)\n self.assertIs(p, iter(p))\n self.assertEqual(next(p), 2)\n self.assertEqual(next(p), 3)\n self.assertRaises(StopIteration, next, p)\n\n def test_4 (self) :\n for f in self.a :\n with self.subTest(msg=f.__name__) :\n p = f(2, 5)\n self.assertIs(p, iter(p))\n a = []\n for v in p :\n a.append(v)\n self.assertEqual(a, [2, 3, 4])\n\n def test_5 (self) :\n for f in self.a :\n with self.subTest(msg=f.__name__) :\n p = f(2, 5)\n self.assertIs(p, iter(p))\n self.assertEqual(list(p), [2, 3, 4])\n self.assertEqual(list(p), [])\n\nif __name__ == \"__main__\" : # pragma: no cover\n main()\n","sub_path":"examples/RangeIteratorT.py","file_name":"RangeIteratorT.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"643546866","text":"import numpy as np\n\n\nclass Modelagem:\n def __init__(self):\n pass\n\n def importancia(self): # calcular a importancia - trasformar a parte de tres colunas da tabela em uma coluna\n\n cliente_requisito = np.array(\n [[10, 10, 5], [8, 10, 6], [6, 4, 8], [5, 9, 1], [7, 7, 5], [8, 6, 2], [6, 6, 4], [9, 8, 3], [6, 7, 5],\n [10, 10, 7]]) # criação da matriz contendo os clientes e os requisitos V(ci,rj)\n relevancia = np.array([3, 4, 2]) # array de relevancia dos clientes\n produto = relevancia * cliente_requisito\n res_importancia = list(produto.sum(axis=1)) # soma das linhas de produto para retornar um unico vetor\n\n return res_importancia\n\n def risco(self):\n risco = (3, 6, 2, 6, 4, 8, 9, 7, 6, 6) # valor informado na tabela\n return risco\n\n\nclass FuncaoFitness:\n\n def funcaoFitness(self, populacao):\n\n n = 0\n imp = Modelagem().importancia()\n ris = Modelagem().risco()\n y = np.ones(10, int)\n res_fitness = []\n #xi = np.array([1, 2, 3, 2, 1, 1, 0, 3, 2, 1])\n\n for ind in populacao:\n\n while n < 10:\n if ind[n] == 0:\n y[n] = 0\n n += 1\n\n ind = np.array(ind)\n val = (3 - ind + 1)\n fitness = (imp * val - ris * ind) * y\n res_fitness.append(fitness.sum(axis=0))\n\n return res_fitness\n\n","sub_path":"PlanejamentoRelease/modelagem.py","file_name":"modelagem.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"156150149","text":"# -*- coding: utf-8 -*-\n# @Time : 4/11/18 1:25 PM\n# @Author : xugaoxiang\n# @Email : djstava@gmail.com\n# @File : constant.py\n# @Software: PyCharm\n\nimport os\nimport sys\n\nVERSION = 'v1.0.2'\n\nCURRENT_DIR = os.path.dirname(os.path.realpath(sys.argv[0]))\n\n# for models\nMODEL_DIR = os.path.join(CURRENT_DIR, 'models')\nDLIB_MODEL_DIR = os.path.join(MODEL_DIR, 'dlib')\nOPENFACE_MODEL_DIR = os.path.join(MODEL_DIR, 'openface')\nALIGN_DLIB_FILE = '{}/shape_predictor_68_face_landmarks.dat'.format(DLIB_MODEL_DIR)\nDEFAULT_NETWORK_MODEL_FILE = '{}/nn4.small2.v1.t7'.format(OPENFACE_MODEL_DIR)\n\n# for recognition\nRECOGNITION_DIR = os.path.join(CURRENT_DIR, 'recognition')\nRECOGNITION_CLASSIFIER_DIR = os.path.join(RECOGNITION_DIR, 'generated-embeddings')\nRECOGNITION_CLASSIFIER_PKL_FILE = os.path.join(RECOGNITION_CLASSIFIER_DIR, 'classifier.pkl')\n\n# for re-training\nRETRAINING_DIR = os.path.join(CURRENT_DIR, 'retraining')\nRETRAINING_ALIGN_DIR = os.path.join(RETRAINING_DIR, 'aligned-images')\nRETRAINING_TEMP_DIR = os.path.join(RETRAINING_DIR, 'temp')\nRETRAINING_CLASSIFIER_DIR = os.path.join(RETRAINING_DIR, 'generated-embeddings')\nRETRAINING_TRAINING_IMAGES_DIR = os.path.join(RETRAINING_DIR, 'training-images')\n\n# for POST image size\nMAX_POST_IMAGE_SIZE = 2 * 1024 * 1024","sub_path":"src/utils/constant.py","file_name":"constant.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"622369076","text":"#!/usr/bin/env python\n\nimport roslib\nimport rospy\nimport smach\nimport smach_ros\n\nfrom std_msgs.msg import *\nfrom geometry_msgs.msg import *\n\n\nfrom States.searchingState import *\nfrom States.movingState import *\nfrom States.lift import *\nfrom States.back2Base import *\nfrom States.util import *\nfrom States.getPose import *\n\n\n\n\ndef main():\n\trospy.init_node('MotherBrain')\n\t\n\tpose = PoseStamped()\n\tpose.pose.position.x=0\n\tpose.pose.orientation.w=1\n\t\n\tpose2 = PoseStamped()\n\tpose2.pose.position.x=2\n\tpose2.pose.position.y=2\n\tpose2.pose.orientation.w=1\n\t\n\tpose_base = PoseStamped()\n\tpose_base.header.frame_id=\"map\"\n\tpose_base2 = PoseStamped()\n\tpose_base2.header.frame_id=\"map\"\n\tpose_base2.pose.position.y=2\n\tpose_base.pose.orientation.w=1\n\tpose_base2.pose.orientation.w=1\n\t\n\trospy.loginfo(\"Going in ;)\")\n\tmover=GoalMaker(False,1, 60) #set at true for testing !\n\trospy.loginfo(\"Done\")\n\t# Create a SMACH state machine\n\tsm = smach.StateMachine(outcomes=['End'])\n\t#sm.userdata.sm_counter = 0\n\tsm.userdata.sm_pose_goal = list()\n\tsm.userdata.sm_pose_goal.append(pose) #Don't know how to declare a message...\n\t#sm.userdata.sm_pose_goal.append(pose2) #Don't know how to declare a message...\n\t\n\tsm.userdata.sm_pose_test = list(sm.userdata.sm_pose_goal) #copy\n\n\tsm.userdata.sm_object_flag = list()\n\tsm.userdata.sm_object_flag.append(False)\n\t#sm.userdata.sm_object_flag.append(False)\n\t\n\tsm.userdata.sm_pose_base=list()\n\tsm.userdata.sm_pose_base.append(pose_base)\n\t#sm.userdata.sm_pose_base.append(pose_base2)\n\t\n\tsm.userdata.sm_object_flag=False\n\tsm.userdata.sm_iteration_get_pose=0\n\tsm.userdata.nb_robot=1\n\tsm.userdata.stack=Stack(0.5, 0.5)\n\t\n\t# Open the container\n\twith sm: \n\t\t# Add states to the container\n\t\t\n\t\t#Send back the object to the base before launching the search\n\t\tsmach.StateMachine.add('Init',Move(mover), \n\t\ttransitions={'invalid':'End', 'valid':'Search', 'preempted':'End', 'invalid' : 'End', 'valid_no_object' : 'Search'}, \n\t\tremapping={'move_pose_list':'sm_pose_base' , 'move_object_flag':'sm_object_flag'})\n\t\t\n\t\t#Wait for object positions\n\t\tsmach.StateMachine.add('Search', Search(1, sm.userdata.stack), \n\t\ttransitions={'invalid':'Search', 'valid':'Move'}, \n\t\tremapping={'flag' : 'sm_object_flag', 'end_object_flag':'sm_object_flag', 'pose' : 'sm_pose_goal', 'pose_end': 'sm_pose_goal', 'stack' : 'stack'})\n\t\t \n\t\t#Move the robot to the specified goal\n\t\tsmach.StateMachine.add('Move',Move(mover), \n\t\ttransitions={'invalid':'Change_flag_lift', 'valid':'Lift', 'preempted':'Change_flag_lift', 'valid_no_object' : 'Lift'}, \n\t\tremapping={'move_pose_list':'sm_pose_goal' , 'move_object_flag':'sm_object_flag'})\n\n\t\t\n\t\t#Lift or unlift the robot platform\n\t\tsmach.StateMachine.add('Lift', Lift(1), transitions={'invalid':'Lift', 'valid':'getPose', 'preempted':'Lift', 'valid_unlift' : 'Init'}, remapping={'flag' : 'sm_object_flag', 'end_object_flag':'sm_object_flag'})\n\t \n\t\t#Get pose from the user\n\t\tsmach.StateMachine.add('getPose', WaitForMsgState(\"/user_pose\", Pose, getPositionUser_V2, ['pose_user', 'pose_iteration', 'nb_robot', 'stack'], ['pose_user', 'pose_iteration']), \n\t\ttransitions={'preempted' : 'getPose', 'aborted' : 'Change_flag_lift', 'succeeded' : 'Move'},\n\t\tremapping={'pose_user':'sm_pose_goal' , 'pose_iteration' : 'sm_iteration_get_pose', 'nb_robot' : 'nb_robot', 'stack' : 'stack'})\n\n\t\t#State for testing (?) that input goals for the robot if we do no visual search\n\t\tsmach.StateMachine.add('CreateGoal', Back2Base(), \n\t\ttransitions={'invalid':'Init', 'valid':'Move', 'preempted':'Init'}, \n\t\tremapping={'pose':'sm_pose_goal' , 'pose_base' : 'sm_pose_test'}) \n\t\t\n\t\t#LIFT BUG IN TWO NODE\n\t\tsmach.StateMachine.add('Change_flag_lift', Change_variable(), transitions={'invalid':'Change_flag_lift', 'valid':'Lift', 'preempted':'Change_flag_lift'}, remapping={'flag' : 'sm_object_flag', 'end_object_flag':'sm_object_flag'})\n\t\t \n\n\t# Create and start the introspection server\n\n\n\t# Execute the state machine\n\toutcome = sm.execute()\n\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/MultipleRobot/main1robot.py","file_name":"main1robot.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"470405218","text":"from django.contrib.auth import get_user_model\nfrom django.core.exceptions import ValidationError\n\nfrom listapp.models import Item, List\nimport pytest\n\nUser = get_user_model()\n\nclass TestItemModel:\n\n def test_default_text(self, db):\n item = Item()\n assert item.text == \"\"\n\n def test_items_is_related_to_list(self, db):\n _list = List.objects.create()\n item = Item()\n item.list = _list\n item.save()\n assert item in _list.item_set.all()\n\n def test_cannot_save_empty_list_items(self, db):\n _list = List.objects.create()\n item = Item.objects.create(list=_list, text=\"\")\n with pytest.raises(ValidationError):\n item.save()\n item.full_clean()\n\n def test_duplicate_items_are_invalid(self, db):\n _list = List.objects.create()\n Item.objects.create(list=_list, text=\"asdf\")\n with pytest.raises(ValidationError):\n item = Item(list=_list, text=\"asdf\")\n item.full_clean()\n\n @pytest.mark.skip(reason=\"Delete after chapter 15\")\n def test_can_save_item_to_different_lists(self, db):\n list_1 = List.objects.create()\n list_2 = List.objects.create()\n Item.objects.create(list=list_1, text=\"asdf\")\n item = Item(list=list_2, text=\"asdf\")\n item.full_clean()\n\n def test_string_representation(self, db):\n item = Item(text=\"some text\")\n assert item.text == \"some text\"\n\n def test_list_ordering(self, db):\n list_1 = List.objects.create()\n item_1 = Item.objects.create(list=list_1, text=\"item 1\")\n item_2 = Item.objects.create(list=list_1, text=\"item 2\")\n item_3 = Item.objects.create(list=list_1, text=\"item 3\")\n assert list(Item.objects.all()) == [item_1, item_2, item_3]\n\n\nclass TestListModel:\n\n def test_get_absolute_url(self, db):\n _list = List.objects.create()\n assert _list.get_absolute_url() == f\"/lists/{_list.id}/\"\n\n def test_lists_can_have_owners(self, db):\n user = User.objects.create(email=\"a@b.com\")\n _list = List.objects.create(owner=user)\n assert _list in user.list_set.all()\n\n def test_list_owner_is_optional(self, db):\n List.objects.create()\n\n def test_list_name_is_first_item_text(self, db):\n _list = List.objects.create()\n Item.objects.create(list=_list, text=\"First item\")\n Item.objects.create(list=_list, text=\"Second item\")\n assert _list.name == \"First item\"\n","sub_path":"django-pytest/djangotdd/listapp/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"4084378","text":"from django.core import management # type: ignore\nfrom django.core.management.base import BaseCommand # type: ignore\nfrom carts.carts_api.models import (\n ACS,\n FMAP,\n Section,\n SectionBase,\n SectionSchema,\n State,\n)\n\nfrom json import loads\nimport jsonschema # type: ignore\nfrom pathlib import Path\n\n\nclass Command(BaseCommand):\n help = \"\".join(\n [\n \"Imports base data, but doesn't overwrite existing \",\n \"data unless --overwrite is present as a flag.\",\n ]\n )\n\n def add_arguments(self, parser):\n # Named (optional) arguments\n parser.add_argument(\n \"--overwrite\",\n action=\"store_true\",\n help=\"Overwrite existing instead of leaving as is\",\n )\n\n def handle(self, *args, **options):\n fd = Path(\"fixtures\")\n globs = (\"states.json\", \"backend-j*.json\", \"2020-*.json\", \"acs.json\")\n paths = []\n for glob in globs:\n paths = paths + [_ for _ in sorted(fd.glob(glob))]\n\n schemapath = Path(fd, \"backend-section.schema.json\")\n paths = paths + [schemapath]\n schemabase = loads(Path(fd, \"backend-section.schema.json\").read_text())\n schema = schemabase[0][\"fields\"][\"contents\"]\n\n overwrite = options.get(\"overwrite\", False)\n\n def validate(s, i):\n jsonschema.validate(schema=s, instance=i[\"fields\"][\"contents\"])\n\n paths_to_load = []\n\n for path in paths:\n fixture = loads(path.read_text())[0]\n is_new, validating = False, False\n if fixture[\"model\"] == \"carts_api.sectionschema\":\n year = fixture[\"fields\"][\"year\"]\n try:\n existing = SectionSchema.objects.filter(year=year)\n if overwrite:\n existing.delete()\n is_new = True\n except SectionSchema.DoesNotExist:\n is_new = True\n validating = True\n elif fixture[\"model\"] == \"carts_api.sectionbase\":\n year = fixture[\"fields\"][\"contents\"][\"section\"].get(\"year\")\n ordinal = fixture[\"fields\"][\"contents\"][\"section\"].get(\n \"ordinal\"\n )\n try:\n existing = SectionBase.objects.filter(\n contents__section__year=year,\n contents__section__ordinal=ordinal,\n )\n if overwrite:\n existing.delete()\n is_new = True\n except SectionBase.DoesNotExist:\n is_new = True\n try:\n validate(schema, fixture)\n validating = True\n except jsonschema.exceptions.ValidationError:\n print(path, \"failed validation\")\n elif fixture[\"model\"] == \"carts_api.section\":\n year = fixture[\"fields\"][\"contents\"][\"section\"].get(\"year\")\n ordinal = fixture[\"fields\"][\"contents\"][\"section\"].get(\n \"ordinal\"\n )\n state = fixture[\"fields\"][\"contents\"][\"section\"].get(\"state\")\n try:\n existing = Section.objects.filter(\n contents__section__year=year,\n contents__section__ordinal=ordinal,\n contents__section__state=state,\n )\n if overwrite:\n existing.delete()\n is_new = True\n except Section.DoesNotExist:\n is_new = True\n try:\n validate(schema, fixture)\n validating = True\n except jsonschema.exceptions.ValidationError:\n print(path, \"failed validation\")\n elif fixture[\"model\"] == \"carts_api.State\":\n State.objects.all().delete()\n # We have to put the state data at the start of the list\n # because the FMAP and ACS models have foreign keys that\n # require the state data to already be present.\n paths_to_load.insert(0, path)\n continue\n elif fixture[\"model\"] == \"carts_api.FMAP\":\n # these are reference objects so we should be safe dumping all\n FMAP.objects.all().delete()\n paths_to_load.append(path)\n continue\n elif fixture[\"model\"] == \"carts_api.ACS\":\n # these are reference objects so we should be safe dumping all\n ACS.objects.all().delete()\n paths_to_load.append(path)\n else:\n print(\"No match on model\")\n if validating and is_new:\n paths_to_load.append(path)\n\n for i, path in enumerate(paths_to_load):\n print(i, path, flush=True)\n management.call_command(\"loaddata\", path)\n","sub_path":"frontend/api_postgres/carts/management/commands/idempotent_fixtures.py","file_name":"idempotent_fixtures.py","file_ext":"py","file_size_in_byte":5032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"523134655","text":"import json\nimport os\nimport random\nimport shutil\nimport base64\n\nimport io\nfrom PIL import Image,ImageFile\nfrom flask import Flask,request\nfrom faker import Faker\nfrom flask import Response\nfrom flask import make_response\nfrom flask import send_file\n\n# from io import StringIO\n\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nprint(BASE_DIR)\napp = Flask(__name__)\nfake = Faker()\n\n# prev_name = None\n\ndef make_dat(bydata):\n if not os.path.exists(os.path.join(BASE_DIR,'datf/')):\n os.makedirs(os.path.join(BASE_DIR,'datf/'))\n name = fake.name()+\".dat\"\n path = os.path.join(BASE_DIR,'datf/'+name)\n if isinstance(bydata,str):\n bydata = bydata.encode()\n barr= bytearray(bydata)\n with open(path,'wb') as f:\n f.write(barr)\n\ndef make_wsq(bydata,name):\n if not os.path.exists(os.path.join(BASE_DIR,'wsqf/')):\n os.makedirs(os.path.join(BASE_DIR,'wsqf/'))\n name = name+\".wsq\"\n # prev_name= name\n path = os.path.join(BASE_DIR,'wsqf/'+name)\n # if isinstance(bydata,str):\n # bydata = bydata.encode()\n # barr= bytearray(bydata)\n with open(path,'wb') as f:\n f.write(bydata)\n\ndef make_bmp(bydata, name):\n # img_stream = Image.open(bydata)\n if not os.path.exists(os.path.join(BASE_DIR,'bmpf/')):\n os.makedirs(os.path.join(BASE_DIR,'bmpf/'))\n name = name + \".bmp\"\n basewidth = 800\n baseheight = 800\n path = os.path.join(BASE_DIR, 'bmpf/' + name)\n image = Image.open(io.BytesIO(bydata))\n # wpercent = (basewidth/float(ima))\n image = image.resize((basewidth,baseheight),Image.ANTIALIAS)\n image.save(path)\n # with open(path,'wb') as f:\n # f.write(bydata)\n\ndef make_png(bydata,name):\n if not os.path.exists(os.path.join(BASE_DIR,'pngf/')):\n os.makedirs(os.path.join(BASE_DIR,'pngf/'))\n name = name+\".png\"\n path = os.path.join(BASE_DIR,'pngf/'+name)\n # if isinstance(bydata,str):\n # bydata = bydata.encode()\n # barr= bytearray(bydata)\n with open(path,'wb') as f:\n f.write(bydata)\n\n\n# barr = bytearray(random.getrandbits(8) for i in range (256))\n# make_dat(barr)\n\ndef make_zip(directory):\n # print(os.path.isdir(directory))\n shutil.make_archive(directory, 'zip', directory)\n\n# make_zip()\n\n@app.route(\"/generate_dat\",methods=['POST'])\ndef generate():\n incoming = request.data\n make_dat(incoming)\n return Response(status=200)\n\n@app.route(\"/download\",methods=['GET'])\ndef download_dat():\n make_zip('datf')\n try:\n return send_file('datf.zip',\n attachment_filename='template_images.zip')\n except Exception as e:\n return str(e)\n\n@app.route(\"/hello\",methods=['GET'])\ndef hello():\n return \"

hello

\"\n\n\n\n\n\n@app.route(\"/generate_images\",methods=['POST'])\ndef generate_images():\n\n incoming = json.loads(request.data.decode())\n\n wsq_incoming = base64.b64decode(incoming['wsq_image'])\n png_incoming = base64.b64decode(incoming['png_image'])\n # incoming = incoming['image']\n\n # name = fake.name()\n\n DIR = 'wsqf'\n wsqs = [name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR,name))]\n wsqs.sort()\n \n if len(wsqs) == 0:\n last_name = '00001_01_002_01'\n else:\n last_name = wsqs[-1:][0]\n last_name = last_name.split('.')[0]\n \n last_name = last_name.split('_')\n \n if int(last_name[3]) < 10:\n last_name[3] = str(int(last_name[3]) + 1)\n if len(last_name[3]) < 2 :\n last_name[3] = '0' + last_name[3]\n else:\n last_name[3] = '01'\n last_name[0] = int(last_name[0]) + 1\n if len(str(last_name[0])) < 5:\n last_name[0] = '0'* (5-len(str(last_name[0]))) + str(last_name[0])\n \n last_name = \"_\".join(last_name)\n \n \n \n make_wsq(wsq_incoming,last_name)\n # make_png(png_incoming,last_name)\n make_bmp(png_incoming,last_name)\n return Response(status=200)\n\n@app.route(\"/generate_png\",methods=['POST'])\ndef generate_png():\n incoming = json.loads(request.data.decode())\n\n incoming = base64.b64decode(incoming['image'])\n make_png(incoming)\n return Response(status=200)\n\n\n@app.route(\"/download_wsq\",methods=['GET'])\ndef download_wsq():\n make_zip('wsqf')\n try:\n return send_file('wsqf.zip',\n attachment_filename='wsq_images.zip')\n except Exception as e:\n return str(e)\n\n@app.route(\"/download_png\",methods=['GET'])\ndef download_png():\n make_zip('pngf')\n try:\n return send_file('pngf.zip',\n attachment_filename='pmg_images.zip')\n except Exception as e:\n return str(e)\n\n\n@app.route(\"/download_bmp\",methods=['GET'])\ndef download_bmp():\n make_zip('bmpf')\n try:\n return send_file('bmpf.zip',\n attachment_filename='bmp_images.zip')\n except Exception as e:\n return str(e)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"267870387","text":"from django import template\n\n\nregister = template.Library()\nt = 'common/aktiviteter/listing_item.html'\n\n\n@register.inclusion_tag(t, takes_context=True)\ndef aktivitet_search_item(context, show_images=True):\n context['show_images'] = show_images\n return context\n","sub_path":"apps/aktiviteter/templatetags/aktivitet_search_item.py","file_name":"aktivitet_search_item.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"590596183","text":"# CNN in Theano, with: mini-batch SGD, RMSprop, Nesterov Momentum, L2 Regularization\n\nimport numpy as np\nimport theano\nimport theano.tensor as T\n\nfrom theano.tensor.nnet import conv2d\nfrom theano.tensor.signal.pool import pool_2d\nfrom sklearn.utils import shuffle\n# from util import shuffle # If no sklearn installed, using this shuffle() instead.\nfrom util import init_filter, init_weight_and_bias, get_activation, classification_rate\n\n\nclass ConvPoolLayer(object):\n\tdef __init__(self, mi, mo, fw, fh, poolsz=(2, 2), activation_type=1):\n\t\t# mi = number of input feature maps\n\t\t# mo = number of output feature maps\n\t\t# fw = filter width\n\t\t# fh = filter height\n\t\tshape = (mo, mi, fw, fh)\n\t\tW = init_filter(shape, poolsz)\n\t\tb = np.zeros(mo, dtype=np.float32)\n\t\tself.W = theano.shared(W)\n\t\tself.b = theano.shared(b)\n\t\tself.poolsz = poolsz\n\t\tself.params = [self.W, self.b]\n\t\tself.activation = get_activation(activation_type)\n\n\tdef forward(self, X):\n\t\t# X.shape = (N, c, xw, xh)\n\t\t# W.shape = (mo, mi, fw, fh) # W is filters, and mi == c\n\t\t# Y.shape = (N, mo, yw, yh) # Y is conv_out\n\t\t# By default in Theano conv2d() operation:\n\t\t# yw = xw - fw + 1\n\t\t# yh = xh - fh + 1\n\t\tconv_out = conv2d(input=X, filters=self.W)\n\t\tpool_out = pool_2d(\n\t\t\tinput=conv_out,\n\t\t\tws=self.poolsz,\n\t\t\tignore_border=True\n\t\t)\n\t\t# pool_out.shape = (N, mo, outw, outh)\n\t\t# outw = int(yw / poolsz[0])\n\t\t# outh = int(yh / poolsz[1])\n\t\t# b.shape = (mo,)\n\t\t# after dimshuffle(), new_b.shape = (1, mo, 1, 1)\n\t\treturn self.activation(pool_out + self.b.dimshuffle('x', 0, 'x', 'x'))\n\n\nclass HiddenLayer(object):\n\tdef __init__(self, M1, M2, activation_type=1):\n\t\tW, b = init_weight_and_bias(M1, M2)\n\t\tself.W = theano.shared(W)\n\t\tself.b = theano.shared(b)\n\t\tself.params = [self.W, self.b]\n\t\tself.activation = get_activation(activation_type)\n\n\tdef forward(self, X):\n\t\treturn self.activation(X.dot(self.W) + self.b)\n\n\nclass CNN(object):\n\tdef __init__(self, conv_layer_sizes, hidden_layer_sizes, pool_layer_sizes=None, convpool_activation=1, hidden_activation=1):\n\t\tself.conv_layer_sizes = conv_layer_sizes\n\t\tself.hidden_layer_sizes = hidden_layer_sizes\n\t\tif pool_layer_sizes is None:\n\t\t\tpool_layer_sizes = [(2, 2) for i in range(len(conv_layer_sizes))]\n\t\tself.pool_layer_sizes = pool_layer_sizes\n\t\tassert(len(conv_layer_sizes) == len(pool_layer_sizes))\n\t\tself.convpool_activation = convpool_activation\n\t\tself.hidden_activation = hidden_activation\n\n\tdef fit(self, X, Y, epochs=1000, batch_sz=0, learning_rate=10e-6, decay=0, momentum=0, reg_l2=0, eps=10e-10, debug=False, cal_train=False, debug_points=100, valid_set=None):\n\t\t# use float32 for Theano GPU mode\n\t\tlr = np.float32(learning_rate)\n\t\tdecay = np.float32(decay)\n\t\tmu = np.float32(momentum)\n\t\treg = np.float32(reg_l2)\n\t\teps = np.float32(eps)\n\t\tone = np.float32(1)\n\n\t\t# train set pre-processing\n\t\tassert(len(X) == len(Y))\n\t\tif len(Y.shape) == 2:\n\t\t\tif Y.shape[1] == 1:\n\t\t\t\tY = np.squeeze(Y)\n\t\t\telse:\n\t\t\t\tY = np.argmax(Y, axis=1)\n\t\tX = X.astype(np.float32)\n\t\tY = Y.astype(np.int32)\n\n\t\t# for debug: pre-process validation set\n\t\tif debug:\n\t\t\tif valid_set is not None:\n\t\t\t\tif len(valid_set) < 2 or len(valid_set[0]) != len(valid_set[1]) or len(valid_set[0].shape) != 4:\n\t\t\t\t\tvalid_set = None\n\t\t\t\telse:\n\t\t\t\t\tXvalid = valid_set[0]\n\t\t\t\t\tif Xvalid.shape[1] != X.shape[1] or Xvalid.shape[2] != X.shape[2] or Xvalid.shape[3] != X.shape[3]:\n\t\t\t\t\t\tvalid_set = None\n\t\t\t\t\telse:\n\t\t\t\t\t\tYvalid = np.squeeze(valid_set[1])\n\t\t\t\t\t\tif len(Yvalid.shape) == 2:\n\t\t\t\t\t\t\tYvalid = np.argmax(Yvalid, axis=1)\n\t\t\t\t\t\tXvalid = Xvalid.astype(np.float32)\n\t\t\t\t\t\tYvalid = Yvalid.astype(np.int32)\n\t\t\tdebug = cal_train or (valid_set is not None)\n\n\t\t# initialize convpool layers\n\t\tN, c, width, height = X.shape\n\t\tmi = c\n\t\toutw = width\n\t\touth = height\n\t\tself.convpool_layers = []\n\t\tfor convsz, poolsz in zip(self.conv_layer_sizes, self.pool_layer_sizes):\n\t\t\tmo, fw, fh = convsz\n\t\t\tcp = ConvPoolLayer(mi, mo, fw, fh, poolsz, activation_type=self.convpool_activation)\n\t\t\tself.convpool_layers.append(cp)\n\t\t\toutw = int((outw - fw + 1) / poolsz[0])\n\t\t\touth = int((outh - fh + 1) / poolsz[1])\n\t\t\tmi = mo\n\n\t\t# initialize hidden layers\n\t\tK = len(set(Y))\n\t\tself.hidden_layers = []\n\t\tM1 = mi * outw * outh # Here, mi == self.conv_layer_sizes[-1][0]\n\t\tfor M2 in self.hidden_layer_sizes:\n\t\t\th = HiddenLayer(M1, M2, activation_type=self.hidden_activation)\n\t\t\tself.hidden_layers.append(h)\n\t\t\tM1 = M2\n\n\t\t# last output layer -- logistic regression layer\n\t\tW, b = init_weight_and_bias(M1, K)\n\t\tself.W = theano.shared(W)\n\t\tself.b = theano.shared(b)\n\n\t\t# collect params for later use\n\t\tself.params = [self.W, self.b]\n\t\tfor h in reversed(self.hidden_layers):\n\t\t\tself.params += h.params\n\t\tfor cp in reversed(self.convpool_layers):\n\t\t\tself.params += cp.params\n\n\t\t# for RMSprop\n\t\tcache = [theano.shared(np.zeros(p.get_value().shape, dtype=np.float32)) for p in self.params]\n\n\t\t# for momentum\n\t\tdparams = [theano.shared(np.zeros(p.get_value().shape, dtype=np.float32)) for p in self.params]\n\n\t\t# set up theano variables and functions\n\t\tthX = T.tensor4('X', dtype='float32')\n\t\tthY = T.ivector('Y') # lower case i means int32. By the way, upper case I means int64\n\n\t\tpY = self.th_forward(thX)\n\t\tself.forward_op = theano.function(inputs=[thX], outputs=pY)\n\n\t\treg_cost = reg * T.sum([(p*p).sum() for p in self.params])\n\t\tcost = -T.mean(T.log(pY[T.arange(thY.shape[0]), thY])) + reg_cost\n\n\t\tprediction = self.th_predict(thX)\n\t\tself.predict_op = theano.function(inputs=[thX], outputs=prediction)\n\n\t\tcost_predict_op = theano.function(inputs=[thX, thY], outputs=[cost, prediction])\n\n\t\t# updates with RMSprop and Momentum, optional\n\t\tupdates = []\n\t\tif decay > 0 and decay < 1:\n\t\t\tif mu > 0:\n\t\t\t\tfor c, dp, p in zip(cache, dparams, self.params):\n\t\t\t\t\tupdates += [\n\t\t\t\t\t\t(c, decay*c + (one - decay)*T.grad(cost, p)*T.grad(cost, p)),\n\t\t\t\t\t\t(p, p + mu*mu*dp - (one + mu)*lr*T.grad(cost, p)/T.sqrt(c + eps)),\n\t\t\t\t\t\t(dp, mu*mu*dp - (one + mu)*lr*T.grad(cost, p)/T.sqrt(c + eps))\n\t\t\t\t\t]\n\t\t\telse:\n\t\t\t\tfor c, p in zip(cache, self.params):\n\t\t\t\t\tupdates += [\n\t\t\t\t\t\t(c, decay*c + (one - decay)*T.grad(cost, p)*T.grad(cost, p)),\n\t\t\t\t\t\t(p, p - lr*T.grad(cost, p)/T.sqrt(c + eps))\n\t\t\t\t\t]\n\t\telse:\n\t\t\tif mu > 0:\n\t\t\t\tfor dp, p in zip(dparams, self.params):\n\t\t\t\t\tupdates += [\n\t\t\t\t\t\t(p, p + mu*mu*dp - (one + mu)*lr*T.grad(cost, p)),\n\t\t\t\t\t\t(dp, mu*mu*dp - (one + mu)*lr*T.grad(cost, p))\n\t\t\t\t\t]\n\t\t\telse:\n\t\t\t\tupdates = [(p, p - lr*T.grad(cost, p)) for p in self.params]\n\n\t\ttrain_op = theano.function(inputs=[thX, thY], updates=updates)\n\n\t\tif debug:\n\t\t\tcosts_train, costs_valid = [], []\n\t\t\tscores_train, scores_valid = [], []\n\n\t\tif batch_sz > 0 and batch_sz < N:\n\t\t\t# training: Backpropagation, using batch gradient descent\n\t\t\tn_batches = int(N / batch_sz)\n\t\t\tif debug:\n\t\t\t\tdebug_points = np.sqrt(debug_points)\n\t\t\t\tprint_epoch, print_batch = max(int(epochs / debug_points), 1), max(int(n_batches / debug_points), 1)\n\n\t\t\tfor i in range(epochs):\n\t\t\t\tX, Y = shuffle(X, Y)\n\t\t\t\tfor j in range(n_batches):\n\t\t\t\t\tXbatch = X[j*batch_sz:(j*batch_sz + batch_sz)]\n\t\t\t\t\tYbatch = Y[j*batch_sz:(j*batch_sz + batch_sz)]\n\n\t\t\t\t\ttrain_op(Xbatch, Ybatch)\n\n\t\t\t\t\t# for debug:\n\t\t\t\t\tif debug:\n\t\t\t\t\t\tif i % print_epoch == 0 and j % print_batch == 0:\n\t\t\t\t\t\t\tif cal_train:\n\t\t\t\t\t\t\t\tctrain, pYtrain = cost_predict_op(X, Y)\n\t\t\t\t\t\t\t\tstrain = classification_rate(Y, pYtrain)\n\t\t\t\t\t\t\t\tcosts_train.append(ctrain)\n\t\t\t\t\t\t\t\tscores_train.append(strain)\n\t\t\t\t\t\t\t\tprint('epoch=%d, batch=%d, n_batches=%d: cost_train=%s, score_train=%.6f%%' % (i, j, n_batches, ctrain, strain*100))\n\t\t\t\t\t\t\tif valid_set is not None:\n\t\t\t\t\t\t\t\tcvalid, pYvalid = cost_predict_op(Xvalid, Yvalid)\n\t\t\t\t\t\t\t\tsvalid = classification_rate(Yvalid, pYvalid)\n\t\t\t\t\t\t\t\tcosts_valid.append(cvalid)\n\t\t\t\t\t\t\t\tscores_valid.append(svalid)\n\t\t\t\t\t\t\t\tprint('epoch=%d, batch=%d, n_batches=%d: cost_valid=%s, score_valid=%.6f%%' % (i, j, n_batches, cvalid, svalid*100))\n\t\telse:\n\t\t\t# training: Backpropagation, using full gradient descent\n\t\t\tif debug:\n\t\t\t\tprint_epoch = max(int(epochs / debug_points), 1)\n\n\t\t\tfor i in range(epochs):\n\t\t\t\ttrain_op(X, Y)\n\n\t\t\t\t# for debug:\n\t\t\t\tif debug:\n\t\t\t\t\tif i % print_epoch == 0:\n\t\t\t\t\t\tif cal_train:\n\t\t\t\t\t\t\tctrain, pYtrain = cost_predict_op(X, Y)\n\t\t\t\t\t\t\tstrain = classification_rate(Y, pYtrain)\n\t\t\t\t\t\t\tcosts_train.append(ctrain)\n\t\t\t\t\t\t\tscores_train.append(strain)\n\t\t\t\t\t\t\tprint('epoch=%d: cost_train=%s, score_train=%.6f%%' % (i, ctrain, strain*100))\n\t\t\t\t\t\tif valid_set is not None:\n\t\t\t\t\t\t\tcvalid, pYvalid = cost_predict_op(Xvalid, Yvalid)\n\t\t\t\t\t\t\tsvalid = classification_rate(Yvalid, pYvalid)\n\t\t\t\t\t\t\tcosts_valid.append(cvalid)\n\t\t\t\t\t\t\tscores_valid.append(svalid)\n\t\t\t\t\t\t\tprint('epoch=%d: cost_valid=%s, score_valid=%.6f%%' % (i, cvalid, svalid*100))\n\n\t\tif debug:\n\t\t\tif cal_train:\n\t\t\t\tctrain, pYtrain = cost_predict_op(X, Y)\n\t\t\t\tstrain = classification_rate(Y, pYtrain)\n\t\t\t\tcosts_train.append(ctrain)\n\t\t\t\tscores_train.append(strain)\n\t\t\t\tprint('Final validation: cost_train=%s, score_train=%.6f%%, train_size=%d' % (ctrain, strain*100, len(Y)))\n\t\t\tif valid_set is not None:\n\t\t\t\tcvalid, pYvalid = cost_predict_op(Xvalid, Yvalid)\n\t\t\t\tsvalid = classification_rate(Yvalid, pYvalid)\n\t\t\t\tcosts_valid.append(cvalid)\n\t\t\t\tscores_valid.append(svalid)\n\t\t\t\tprint('Final validation: cost_valid=%s, score_valid=%.6f%%, valid_size=%d' % (cvalid, svalid*100, len(Yvalid)))\n\n\t\t\timport matplotlib.pyplot as plt\n\t\t\tif cal_train:\n\t\t\t\tplt.plot(costs_train, label='training set')\n\t\t\tif valid_set is not None:\n\t\t\t\tplt.plot(costs_valid, label='validation set')\n\t\t\tplt.title('Cross-Entropy Cost')\n\t\t\tplt.legend()\n\t\t\tplt.show()\n\t\t\tif cal_train:\n\t\t\t\tplt.plot(scores_train, label='training set')\n\t\t\tif valid_set is not None:\n\t\t\t\tplt.plot(scores_valid, label='validation set')\n\t\t\tplt.title('Classification Rate')\n\t\t\tplt.legend()\n\t\t\tplt.show()\n\n\tdef th_forward(self, X):\n\t\tZ = X\n\t\tfor cp in self.convpool_layers:\n\t\t\tZ = cp.forward(Z)\n\t\tZ = Z.flatten(ndim=2)\n\t\tfor h in self.hidden_layers:\n\t\t\tZ = h.forward(Z)\n\t\treturn T.nnet.softmax(Z.dot(self.W) + self.b)\n\n\tdef th_predict(self, X):\n\t\tpY = self.th_forward(X)\n\t\treturn T.argmax(pY, axis=1)\n\n\tdef forward(self, X):\n\t\tX = X.astype(np.float32)\n\t\treturn self.forward_op(X)\n\n\tdef predict(self, X):\n\t\tX = X.astype(np.float32)\n\t\treturn self.predict_op(X)\n\n\tdef score(self, X, Y):\n\t\tP = self.predict(X)\n\t\treturn classification_rate(Y, P)\n\n","sub_path":"cnn/cnn_theano.py","file_name":"cnn_theano.py","file_ext":"py","file_size_in_byte":10207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"128149404","text":"from django import forms\nfrom .models import BillingAddress, PhoneNumber\n\nclass BillingAddressForm(forms.ModelForm):\n \"\"\"Form for creating a new address for Sellers and/or Customers.\"\"\"\n\n def __init__(self):\n super( BillingAddressForm, self).__init__()\n\n class Meta:\n model = BillingAddress\n fields = [\n 'street_address',\n 'landmark',\n 'region',\n 'town',\n ]\n\n\nclass PhoneNumberForm(forms.ModelForm):\n\n class Meta:\n model = PhoneNumber\n fields = ('number',)\n","sub_path":"apps/address/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"309664854","text":"import json\nimport requests\nimport os\n\n#class HackerRankDataset:\n#\tdef get_all_users():\\\nurl_sol=\"https://www.hackerrank.com/rest/contests/master/challenges/mini-max-sum/hackers/{name}/download_solution\"\nurl_users=\"https://www.hackerrank.com/rest/contests/master/challenges/mini-max-sum/leaderboard/filter?offset={offset_value}&limit=100&include_practice=true&language=c&filter_kinds=language\"\n#obj=requests.get(\"https://www.hackerrank.com/rest/contests/master/challenges/simple-array-sum/leaderboard/filter?offset=0&limit=100&include_practice=true&language=c&filter_kinds=language\",auth=(\"vibhanshimodi@gmail.com\",\"#1Ambition\"))\n#users=obj.json()\n#user_details=users[\"models\"]\nparent_dir=\"mini-max\"\nif not os.path.exists(parent_dir):\n os.makedirs(parent_dir)\nfor i in range(0,20000,100):\n\tobj=requests.get(url_users.format(offset_value=i),auth=(\"vibhanshimodi@gmail.com\",\"#1Ambition\"))\n\tusers=obj.json()\n\tuser_details=users[\"models\"]\n\tfor j in range(0,100,10):\n\t\tnew_dir=parent_dir+\"/\"+ \"Correct\"\n\t\tif not os.path.exists(new_dir):\n\t\t\tos.makedirs(new_dir)\n\t\tfilename=new_dir + \"/\"+ user_details[j][\"hacker\"] + \".c\"\n\t\tfo=open(filename,\"w\")\n\t\tcode=requests.get(url_sol.format(name=user_details[j][\"hacker\"]),auth=(\"vibhanshimodi@gmail.com\",\"#1Ambition\"))\n\t\tfo.write(code.text)\t\n\t\n\n\n","sub_path":"AEPA_Dataset.py","file_name":"AEPA_Dataset.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"503120147","text":"from dataclasses import dataclass\n\n\n@dataclass\nclass Series:\n title: str\n points: list\n\n def __init__(self, points, title, **rest):\n self.points = points\n self.title = title if title is not None else ''\n if len(rest):\n for key, value in rest.items():\n self.__dict__[key] = value\n","sub_path":"crostab/series/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"242710563","text":"import re\n\nimport requests\n\n\ndef cleanhtml(raw_html):\n cleanr = re.compile('<.*?>')\n cleantext = re.sub(cleanr, '', raw_html)\n return cleantext\n\n\nclass Series:\n\n @staticmethod\n def _get_series(r):\n record_new = {\n 'imdbID': r['id'],\n 'Title': r['name'],\n 'Poster': r['image']['original'] if r['image'] else None,\n 'Genre': ', '.join(r['genres']) if r['genres'] else None,\n 'Plot': cleanhtml(r['summary']) if r['summary'] else None,\n 'Year': r['premiered'][:4] if r['premiered'] else None,\n 'Released': r['premiered'],\n }\n return record_new\n\n @classmethod\n def search(cls, value):\n resp = requests.get(f'http://api.tvmaze.com/search/shows?q={value}')\n return [cls._get_series(record['show']) for record in resp.json()]\n\n @staticmethod\n def _get_seasons(id_):\n resp = requests.get(f'http://api.tvmaze.com/shows/{id_}/episodes')\n seasons = {}\n for ep in resp.json():\n season_number = str(ep['season'])\n if season_number not in seasons:\n seasons[season_number] = {'Episodes': []}\n record = {\n 'imdbID': str(ep['id']),\n 'Episode': str(ep['number']),\n 'Title': ep['name'],\n }\n seasons[season_number]['Episodes'].append(record)\n return seasons\n\n @classmethod\n def select_seasons(cls, title):\n resp = requests.get(f'http://api.tvmaze.com/singlesearch/shows?q={title}')\n series = cls._get_series(resp.json())\n seasons = cls._get_seasons(series['imdbID'])\n return series, seasons\n\n\nif __name__ == \"__main__\":\n print('nightwish')","sub_path":"app/dao/series.py","file_name":"series.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"114214864","text":"import os\nimport copy\nimport gym\nfrom tqdm import tqdm\nimport numpy as np\n\nepisode_n = 0\n\ndef run_episode(env, agent_vector, training, record=False):\n '''\n Runs a single multi-agent rl loop until termination.\n The observations vector is of length n, where n is the number of agents\n observations[i] corresponds to the oberservation of agent i.\n :param env: OpenAI gym environment\n :param agent_vector: Vector containing the agent for each agent in the environment\n :param training: (boolean) Whether the agents will learn from the experience they recieve\n :returns: Episode trajectory (o,a,r,o')\n '''\n if record:\n global episode_n\n episode_n +=1\n video_recorder = gym.wrappers.monitoring.video_recorder.VideoRecorder(env=env, base_path=(\"/tmp/{}-episode-{}\".format(record, episode_n)), enabled=True)\n\n observations = copy.deepcopy( env.reset() )\n done = False\n trajectory = []\n timestep = 0\n\n inner_loop = True\n\n while not done:\n action_vector = copy.deepcopy( [agent.take_action(observations[i]) for i, agent in enumerate(agent_vector)] )\n succ_observations, reward_vector, done, info = copy.deepcopy( env.step(action_vector) )\n trajectory.append( copy.deepcopy( (observations, action_vector, reward_vector, succ_observations, done) ) )\n\n if inner_loop:\n if training:\n for i, agent in enumerate(agent_vector):\n agent.handle_experience( copy.deepcopy(observations[i]), copy.deepcopy(action_vector[i]), copy.deepcopy(reward_vector[i]), copy.deepcopy(succ_observations[i]), copy.deepcopy(done) )\n\n if record:\n video_recorder.capture_frame()\n\n timestep += 1\n observations = copy.deepcopy(succ_observations)\n\n\n if not(inner_loop) and training:\n for o, a, r, so, d in trajectory:\n for i, agent in enumerate(agent_vector):\n #a_dummy = agent.take_action(o[i])\n #agent.handle_experience(o[i], a_dummy, r[i], so[i], d)\n agent.handle_experience(o[i], a[i], r[i], so[i], d)\n\n if record:\n video_recorder.close()\n print(\"Video recorded :: episode {}\".format(episode_n))\n\n return trajectory\n\ndef run_episode_parallel(env, agent_vector, training, self_play=True):\n '''\n Runs a single multi-agent rl loop until termination.\n The observations vector is of length n, where n is the number of agents\n observations[i] corresponds to the oberservation of agent i.\n :param env: ParallelEnv wrapper around an OpenAI gym environment\n :param agent_vector: Vector containing the agent for each agent in the environment\n :param training: (boolean) Whether the agents will learn from the experience they recieve\n :param self_play: boolean specifying the mode in which to operate and, thus, what to return\n :returns: Trajectory (o,a,r,o') of actor 0, if self_play, trajectories for all the actor otherwise.\n '''\n nbr_actors = env.get_nbr_envs()\n observations = env.reset()\n for agent in agent_vector: \n agent.set_nbr_actor(nbr_actors)\n agent.reset_actors()\n done = [False]*nbr_actors\n previous_done = copy.deepcopy(done)\n\n per_actor_trajectories = [list() for i in range(nbr_actors)]\n trajectory = []\n while not all(done):\n action_vector = [agent.take_action(observations[i]) for i, agent in enumerate(agent_vector)]\n succ_observations, reward_vector, done, info = env.step(action_vector)\n\n if training:\n for i, agent in enumerate(agent_vector):\n agent.handle_experience(observations[i], \n action_vector[i], \n reward_vector[i], \n succ_observations[i], \n done)\n \n batch_index = -1\n batch_idx_done_actors_among_not_done = []\n for actor_index in range(nbr_actors):\n if previous_done[actor_index]:\n continue\n batch_index +=1\n \n # Bookkeeping of the actors whose episode just ended:\n if done[actor_index] and not(previous_done[actor_index]):\n batch_idx_done_actors_among_not_done.append(batch_index)\n \n pa_obs = [ observations[idx_agent][batch_index] for idx_agent, agent in enumerate(agent_vector) ]\n pa_a = [ action_vector[idx_agent][batch_index] for idx_agent, agent in enumerate(agent_vector) ]\n pa_r = [ reward_vector[idx_agent][batch_index] for idx_agent, agent in enumerate(agent_vector) ]\n pa_succ_obs = [ succ_observations[idx_agent][batch_index] for idx_agent, agent in enumerate(agent_vector) ]\n pa_done = [ done[actor_index] for idx_agent, agent in enumerate(agent_vector) ]\n per_actor_trajectories[actor_index].append((pa_obs, pa_a, pa_r, pa_succ_obs, pa_done))\n\n if actor_index == 0 :\n trajectory.append((pa_obs, pa_a, pa_r, pa_succ_obs, done[actor_index]))\n\n observations = copy.deepcopy(succ_observations)\n if len(batch_idx_done_actors_among_not_done):\n # Regularization of the agents' next observations:\n batch_idx_done_actors_among_not_done.sort(reverse=True)\n for i,agent in enumerate(agent_vector):\n for batch_idx in batch_idx_done_actors_among_not_done:\n observations[i] = np.concatenate( [observations[i][:batch_idx,...], observations[i][batch_idx+1:,...]], axis=0)\n \n previous_done = copy.deepcopy(done)\n\n if self_play:\n return trajectory\n\n return per_actor_trajectories\n","sub_path":"regym/rl_loops/multiagent_loops/simultaneous_action_rl_loop.py","file_name":"simultaneous_action_rl_loop.py","file_ext":"py","file_size_in_byte":5719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"367052351","text":"from tkinter import *\nimport AffineCipher, CaesarCipher, MultiplicativeCipher, TranspositionCipher, MyCipher\n\n\n\nclass Application(Frame):\n\n\tdef __init__(self, master):\n\t\tFrame.__init__(self, master)\n\t\t# Setting the border, padding, etc for the application\n\t\tself.grid(padx = (10, 0), pady=30)\n\n\t\t# Calling the function to create widgets\n\t\tself.create_widgets()\n\n\n\tdef create_widgets(self):\n\t\t# Local variable that will help \n\t\tcount_row = 0\n\t\tself.initialInstruction = Label(self, text = \"Enter your message:\", font=(\"Verdana\", \"12\", \"bold\"))\n\t\tself.initialInstruction.grid(row = count_row, column = 0, columnspan = 10, sticky = W,pady=10)\n\n\t\tself.resultInstruction = Label(self, text = \"Result:\", font=(\"Verdana\", \"12\", \"bold\"))\n\t\tself.resultInstruction.grid(row=count_row, column = 11, columnspan = 10, sticky = W, pady=10, padx=10)\n\n\t\tcount_row += 1\n\n\t\tself.plainText = Text(self, width = 40, height=10, wrap= WORD)\n\t\tself.plainText.grid(row=count_row, column = 0, columnspan = 10, rowspan=10, sticky=W)\n\t\t\n\t\t# Setting the result for read-only\n\t\tself.result = Text(self, width= 40, height=10, wrap=WORD, state='disabled')\n\t\t\"\"\"\n\t\tPs.: Before and after inserting, change the state, otherwise it won't update\n\n\t\tself.result.configure(state='normal')\n\t\tself.result.insert(0.0, 'Some Text')\n\t\tself.result.configure(state='disabled')\n\n\t\t\"\"\"\n\t\tself.result.grid(row=count_row, column=11, columnspan=10, sticky=W, padx=10)\n\n\t\tcount_row += 10\n\t\t\n\t\t# Creating the variable for Radiobuttons\n\t\t# and setting the Radiobuttons initially unmarked\n\t\tself.cipher = IntVar()\n\t\tself.cipher.set(0)\n\n\t\t# Cipher Radiobutton Label\n\t\tcount_row += 1\n\t\tself.cipherLabel = Label(self, text = \"Choose the encrypt algorithm:\", font=(\"Verdana\", \"12\", \"bold\"))\n\t\tself.parameters_row = count_row\n\t\tself.cipherLabel.grid(row=count_row, column = 0, columnspan = 10, rowspan=3, sticky = W+S, pady=10)\n\t\tcount_row += 3\n\n\t\t# Initializing and building Cipher Radiobutton\n\t\tRadiobutton(self, text = \"Affine Cipher\", variable = self.cipher, value=1, font=(\"Verdana\", \"10\"),\n\t\tcommand = self.update_gui).grid(row=count_row, column = 0, sticky=W)\n\t\tself.affine_row = count_row\n\t\tcount_row += 1\n\n\t\tRadiobutton(self, text = \"Caesar Cipher\", variable = self.cipher, value=2, font=(\"Verdana\", \"10\"),\n\t\tcommand = self.update_gui).grid(row=count_row, column = 0, sticky=W)\n\t\tcount_row += 1\n\n\t\tRadiobutton(self, text = \"Multiplicative Cipher\", variable = self.cipher, value=3, font=(\"Verdana\", \"10\"),\n\t\tcommand = self.update_gui).grid(row=count_row, column = 0, sticky=W)\n\t\tcount_row += 1\n\n\t\tRadiobutton(self, text = \"My Cipher\", variable = self.cipher, value=4, font=(\"Verdana\", \"10\"),\n\t\tcommand = self.update_gui).grid(row=count_row, column = 0, sticky=W)\n\t\tcount_row += 1\n\n\t\tRadiobutton(self, text = \"Transposition Cipher\", variable = self.cipher, value=5, font=(\"Verdana\", \"10\"),\n\t\tcommand = self.update_gui).grid(row=count_row, column = 0, sticky=W)\n\t\tcount_row += 1\n\n\t\t\"\"\" Declarations that we may use in the future. \"\"\"\n\t\t# Initializing the Run button\n\t\tself.runButton = Button(self, text=\"Run\", command=self.run_algorithm)\n\t\tself.warning = Label(self, text=\"This key can't be used with this alphabet.\\nPlease enter another key.\", \n\t\t\tfont=(\"Verdana\", \"10\", \"italic\"), fg=\"red\", wraplength=0)\n\n\t\t# Initializing the rules\n\t\t# Order:\n # valid percent substitutions (from the Tk entry man page)\n # %d = Type of action (1=insert, 0=delete, -1 for others)\n # %i = index of char string to be inserted/deleted, or -1\n # %P = value of the entry if the edit is allowed\n # %s = value of entry prior to editing\n # %S = the text string being inserted or deleted, if any\n # %v = the type of validation that is currently set\n # %V = the type of validation that triggered the callback\n # (key, focusin, focusout, forced)\n # %W = the tk name of the widget\n\t\tvkcmd = (self.register(self.validateKey), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')\n\t\tvacmd = (self.register(self.validateAlphabet), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')\n\n\t\t# Initializing the variables\n\t\tself.defineParameters = Label(self, text = \"Define the parameters:\", font=(\"Verdana\", \"12\", \"bold\"))\n\t\tself.keyLabel = Label(self, text=\"Enter your Key: \", font=(\"Verdana\", \"10\", \"bold\"))\n\t\tself.keyEntry = Entry(self, validate='key', validatecommand=vkcmd)\n\t\tself.alphabetLabel = Label(self, text=\"Which alphabet do you want to use?\", font=(\"Verdana\", \"10\", \"bold\"))\n\t\tself.alphabetEntry = Entry(self, validate='key', validatecommand=vacmd)\n\t\tself.alphabetButton = IntVar()\n\t\tself.customAlphabetLabel = Label(self, text=\"Enter your custom alphabet:\", font=(\"Verdana\", \"10\", \"bold\"))\n\n\t\t# Initializing the parameters\n\t\tself.key = 0\n\t\tself.alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789,.!?;:()\"\n\n\t\t# Initializing the RadioButtons for alphabet\n\t\tself.defaultAlphabet = Radiobutton(self, text = \"Default alphabet\", variable = self.alphabetButton,\n\t\t\tvalue=1, font=(\"Verdana\", \"10\"),\n\t\tcommand = self.update_alphabet)\n\t\tself.customAlphabet = Radiobutton(self, text = \"Custom alphabet\", variable = self.alphabetButton, \n\t\t\tvalue=2, font=(\"Verdana\", \"10\"),\n\t\tcommand = self.update_alphabet)\n\n\n\tdef validateAlphabet(self, action, index, value_if_allowed, prior_value, text, validation_type, trigger_type, widget_name):\n\t\t# Check if there's no repeated characters in the alphabet\n\t\tfor letter in str(value_if_allowed):\n\t\t\tif str(value_if_allowed).count(letter) > 1:\n\t\t\t\treturn False\n\t\treturn True\n\n\n\tdef validateKey(self, action, index, value_if_allowed, prior_value, text, validation_type, trigger_type, widget_name):\n\t\t# Check if there's only numbers in the key\n\t\tif len(str(value_if_allowed)) == 0:\n\t\t\treturn True\n\t\tif text in '0123456789':\n\t\t\ttry:\n\t\t\t\tint(value_if_allowed)\n\t\t\t\treturn True\n\t\t\texcept ValueError:\n\t\t\t\treturn False\n\t\treturn False\n\n\n\tdef update_gui(self):\n\t\t# Clear the view for another input variable.\n\t\tself.alphabetButton.set(0)\n\t\tself.customAlphabetLabel.grid_forget()\n\t\tself.alphabetEntry.grid_forget()\n\n\t\t# Construct defineParameters\n\t\tself.defineParameters.grid(row=self.parameters_row, column = 11, columnspan = 10, sticky = W, pady=10, padx=10)\n\t\t\n\t\t# Construct keyLabel\n\t\tself.keyLabel.grid(row=self.affine_row, column = 11, columnspan=1,sticky=W, padx=10)\n\n\t\t# Construct keyEntry\n\t\tself.keyEntry.grid(row = self.affine_row, column = 12, sticky=W)\n\t\t\n\t\t# Construct alphabetLabel\n\t\tself.alphabetLabel.grid(row=self.affine_row+1, column = 11, columnspan=3, sticky=W, padx=10)\n\n\t\t# Construct the Radiobuttons\n\t\tself.defaultAlphabet.grid(row=self.affine_row+2, column = 11, sticky=W, padx=10)\n\t\tself.customAlphabet.grid(row=self.affine_row+2, column = 12, sticky=W)\n\n\t\t# Construct the Run button\n\t\tself.runButton.grid(row=self.affine_row+4, column = 11, sticky=W, padx=10)\n\n\t\t# Check if the cipher is the Transposition Cipher\n\t\t# Then, we don't need the alphabet input\n\t\tif self.cipher.get() == 5:\n\t\t\tself.alphabetLabel.grid_forget()\n\t\t\tself.defaultAlphabet.grid_forget()\n\t\t\tself.customAlphabet.grid_forget()\n\n\n\tdef update_alphabet(self):\n\t\tcase = self.alphabetButton.get()\n\n\t\t# Setting the default alphabet\n\t\tself.setDefaultAlphabet()\n\n\t\t# Delete other entry\n\t\tself.customAlphabetLabel.grid_forget()\n\t\tself.alphabetEntry.grid_forget()\n\n\t\t# Check if the user wants to select a Custom Alphabet\n\t\tif case == 2:\n\t\t\tself.customAlphabetLabel.grid(row=self.affine_row+3, column=11, columnspan=3, sticky=W, padx=10)\n\t\t\tself.alphabetEntry.grid(row=self.affine_row+3, column = 13, sticky=W)\n\n\tdef run_algorithm(self):\n\t\t# Cleaning the warning messages\t\t\n\t\tself.warning.grid_forget()\n\t\tself.result.configure(state='normal')\n\t\tself.result.delete(0.0, END)\n\t\tself.result.configure(state='disabled')\n\n\t\t# Getting the cipher\n\t\tcipher = self.cipher.get()\n\n\t\t# Getting the alphabet\n\t\tself.setDefaultAlphabet()\n\t\tif self.alphabetButton.get() == 2 and cipher != 5:\n\t\t\tself.alphabet = self.alphabetEntry.get()\n\t\t\tif len(self.alphabet) == 0:\n\t\t\t\t# Warning message\n\t\t\t\tself.warning[\"text\"] = \"Your custom alphabet cannot be empty.\\nTip: you should consider enter a large alphabet.\"\n\t\t\t\tself.warning.grid(row=self.affine_row+6, column=11, sticky=W+W, padx=10, columnspan=2, rowspan=2)\n\t\t\t\treturn\n\n\t\t# Getting the key\n\t\tif len(self.keyEntry.get()) == 0:\n\t\t\t# Warning message\n\t\t\tself.warning[\"text\"] = \"Please enter a valid key (numbers only).\"\n\t\t\tself.warning.grid(row=self.affine_row+6, column=11, sticky=W+W, padx=10, columnspan=2, rowspan=2)\n\t\t\treturn\n\t\tself.key = int(self.keyEntry.get())\n\t\t\n\t\t# Getting the message\n\t\t# Put end-1c for avoid getting '\\n' at the end of the input.\n\t\tmessage = self.plainText.get(\"1.0\", 'end-1c')\n\t\tif len(message) == 0:\n\t\t\t# Warning message\n\t\t\tself.warning[\"text\"] = \"I think you forgot to enter your message...\"\n\t\t\tself.warning.grid(row=self.affine_row+6, column=11, sticky=W+W, padx=10, columnspan=2, rowspan=2)\n\t\t\treturn\n\n\t\t# Configuring the result\n\t\tself.result.configure(state='normal')\n\t\t\n\t\t# Encrypt according to the selected cipher\n\t\tif cipher == 1: # Affine Cipher\n\t\t\tvalid = AffineCipher.validateKey(self.key, len(self.alphabet))\n\t\t\tif valid is True:\n\t\t\t\t# Continue the algorithm\n\t\t\t\tself.result.insert(0.0, AffineCipher.encryptMessage(message, self.key, self.alphabet))\n\t\t\telse:\n\t\t\t\t# Show a warning message\n\t\t\t\tself.warning[\"text\"] = \"This key can't be used with this alphabet.\\nPlease enter another key.\"\n\t\t\t\tself.warning.grid(row=self.affine_row+6, column=11, sticky=W+W, padx=10, columnspan=2, rowspan=2)\n\t\t\t\n\t\telif cipher == 2: # Caesar Cipher\n\t\t\tself.result.insert(0.0, CaesarCipher.encryptMessage(message, self.key, self.alphabet))\n\n\t\telif cipher == 3: # Multiplicative Cipher\n\t\t\tvalid = MultiplicativeCipher.validateKey(self.key, len(self.alphabet))\n\t\t\tif valid is True:\n\t\t\t\t# Continue the algorithm\n\t\t\t\tself.result.insert(0.0, MultiplicativeCipher.encryptMessage(message, self.key, self.alphabet))\n\t\t\telse:\n\t\t\t\t# Show a warning message\n\t\t\t\tself.warning[\"text\"] = \"This key can't be used with this alphabet.\\nPlease enter another key.\"\n\t\t\t\tself.warning.grid(row=self.affine_row+6, column=11, sticky=W+W, padx=10, columnspan=2, rowspan=2)\n\n\t\telif cipher == 4: # My Cipher\n\t\t\tvalid = MyCipher.validateKey(self.key, len(self.alphabet))\n\t\t\tif valid is True:\n\t\t\t\t# Continue the algorithm\n\t\t\t\tself.result.insert(0.0, MyCipher.encryptMessage(message, self.key, self.alphabet))\n\t\t\telse:\n\t\t\t\t# Show a warning message\n\t\t\t\tself.warning[\"text\"] = \"This key can't be used with this alphabet.\\nPlease enter another key.\"\n\t\t\t\tself.warning.grid(row=self.affine_row+6, column=11, sticky=W+W, padx=10, columnspan=2, rowspan=2)\n\n\t\telif cipher == 5: # Transposition Cipher\n\t\t\tself.result.insert(0.0, TranspositionCipher.encryptMessage(message, self.key))\n\n\t\t# Setting result for read-only again\n\t\tself.result.configure(state='disabled')\n\n\n\tdef setDefaultAlphabet(self):\n\t\tself.alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789,.!?;:()\"\n\n\n\ndef main():\n\t# Creating empty window with a Title\n\troot = Tk()\n\troot.title(\"Hide your messages!\")\n\t\n\t# Getting the screen infos\n\twidth = root.winfo_screenwidth()\n\t#height = root.winfo_screenheight()\n\n\t# I'm going to use this fixed height because it looks better in my screen\n\theight = 450 #Value for better render\n\n\t# Setting the geometry for the application\n\troot.geometry(str(int(width/2)) + \"x\" + str(int(height)))\n\n\t# Initializing the application\n\tapp = Application(root)\n\troot.mainloop()\n\nif __name__ == '__main__':\n\tmain()","sub_path":"encrpytGUI.py","file_name":"encrpytGUI.py","file_ext":"py","file_size_in_byte":11459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"24761436","text":"from decimal import Decimal\n\nfrom django.test import TestCase\nfrom django.contrib.auth.models import User\n\nfrom currencies.models import Currency\nfrom places.models import City, State, Country\nfrom records.models import Industry, Company, Employee, ProductType, Product\nfrom transactions.models import Invoice, InvoiceLineItem, TransactionType\n\ndef attachCommonTestData(cls):\n cls.country = Country(name=\"USA\")\n cls.state = State(name=\"IL\", country=cls.country)\n cls.city = City(name=\"Chicago\", state=cls.state)\n\n cls.country.save()\n cls.state.save()\n cls.city.save()\n \n cls.usd = Currency(country=cls.country, name=\"US Dollar\", code=\"USD\", symbol=\"$\")\n cls.peso = Currency(country=cls.country, name=\"Peso\", code=\"MXP\", symbol=\"Ps\")\n\n cls.usd.save()\n cls.peso.save()\n \n cls.industry = Industry(name=\"Gizmos\")\n cls.distributor = Company(industry=cls.industry, corporateName=\"Acme\", street=\"Wabash\", streetNumber=\"230\", city=cls.city, zipCode=\"60611\", cnpj=\"12.345.678/0001-00\")\n cls.retailer = Company(industry=cls.industry, corporateName=\"Smith's\", street=\"Monroe\", streetNumber=\"112\", city=cls.city, zipCode=\"60620\", cnpj=\"12.345.678/0001-00\")\n cls.manufacturer = Company(industry=cls.industry, corporateName=\"Zhejiang\", street=\"Adams\", streetNumber=\"52\", city=cls.city, zipCode=\"60612\", cnpj=\"12.345.678/0001-00\")\n\n cls.industry.save()\n cls.distributor.save()\n cls.retailer.save()\n cls.manufacturer.save()\n \n cls.user = User.objects.create_user(username=\"ted\", email=\"ted@ted.com\", password=\"secret\")\n cls.employee = Employee(user=cls.user, company=cls.distributor)\n\n cls.user.save()\n cls.employee.save()\n \n cls.sale = TransactionType(name=\"sale\")\n cls.sale.save()\n\n cls.purchase = TransactionType(name=\"purchase\")\n cls.purchase.save()\n \n cls.productType = ProductType(name=\"Gizmo\")\n cls.widget = Product(code=\"AAA\", name=\"Widget\")\n cls.frob = Product(code=\"FRB\", name=\"Frob\")\n cls.bar = Product(code=\"BAR\", name=\"Bar\")\n\n cls.productType.save()\n cls.widget.save()\n cls.frob.save()\n cls.bar.save()\n \nclass InvoiceTests(TestCase):\n @classmethod\n def setUpTestData(cls):\n attachCommonTestData(cls)\n\n def test_simple_total(self):\n invoice = Invoice(owner=self.employee, transactionType=self.sale, seller=self.distributor, buyer=self.retailer)\n invoice.save()\n\n lineItemA = InvoiceLineItem(quantity=100, product=self.widget, invoice=invoice, currency=self.usd, price=Decimal(\"0.20\"))\n lineItemA.save()\n\n total = invoice.total()\n self.assertEquals(total[self.usd], Decimal(\"20.0\"))\n\n def test_simple_discount(self):\n invoice = Invoice(owner=self.employee, transactionType=self.sale, seller=self.distributor, buyer=self.retailer, discount=Decimal('0.3'))\n invoice.save()\n\n lineItemA = InvoiceLineItem(quantity=1, product=self.frob, invoice=invoice, currency=self.usd, price=Decimal(\"0.66\"))\n lineItemA.save()\n\n total = invoice.total()\n self.assertEquals(total[self.usd], Decimal(\"0.462\"))\n\n def test_multiple_currencies_with_discount(self):\n invoice = Invoice(owner=self.employee, transactionType=self.sale, seller=self.distributor, buyer=self.retailer, discount=Decimal('0.15'))\n invoice.save()\n\n lineItemA = InvoiceLineItem(quantity=15, product=self.frob, invoice=invoice, currency=self.usd, price=Decimal(\"0.66\"))\n lineItemA.save()\n\n lineItemB = InvoiceLineItem(quantity=12, product=self.widget, invoice=invoice, currency=self.peso, price=Decimal(\"3.22\"))\n lineItemB.save()\n\n total = invoice.total()\n self.assertEquals(total[self.usd], Decimal(\"8.415\"))\n self.assertEquals(total[self.peso], Decimal(\"32.844\"))\n\nclass ProductTests(TestCase):\n @classmethod\n def setUpTestData(cls):\n attachCommonTestData(cls)\n\n def test_product_stock(self):\n purchaseInvoice = Invoice(owner=self.employee, transactionType=self.purchase, seller=self.manufacturer, buyer=self.distributor)\n purchaseInvoice.save()\n \n lineItemP = InvoiceLineItem(quantity=100, product=self.widget, invoice=purchaseInvoice, currency=self.usd, price=Decimal(\"0.1\"))\n lineItemP.save()\n\n lineItemP2 = InvoiceLineItem(quantity=500, product=self.widget, invoice=purchaseInvoice, currency=self.usd, price=Decimal(\"0.08\"))\n lineItemP2.save()\n\n saleInvoice = Invoice(owner=self.employee, transactionType=self.sale, seller=self.distributor, buyer=self.retailer)\n saleInvoice.save()\n \n lineItemS = InvoiceLineItem(quantity=20, product=self.widget, invoice=saleInvoice, currency=self.usd, price=Decimal(\"0.1\"))\n lineItemS.save()\n\n lineItemS2 = InvoiceLineItem(quantity=15, product=self.widget, invoice=saleInvoice, currency=self.usd, price=Decimal(\"0.09\"))\n lineItemS2.save()\n\n self.assertEquals(self.widget.stock(self.distributor.id), 100 + 500 - 20 - 15)\n","sub_path":"lares/testarea/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"494260525","text":"# Understanding Heapq\n# Remember that Dijkstra’s Algorithm works like the following:\n\n# Instantiate a dictionary that will eventually map vertices to their distance from their start vertex\n# Assign the start vertex a distance of 0 in a min heap\n# Assign every other vertex a distance of infinity in a min heap\n# Remove the vertex with the smallest distance from the min heap and set that to the current vertex\n# For the current vertex, consider all of it’s adjacent vertices and calculate the distance to them by \n# (distance to the current vertex) + (edge weight of current vertex to adjacent vertex). If this new distance\n# is less than its current distance, replace the distance.\n# \n# Repeat 4 and 5 until the heap is empty\n# After the heap is empty, return the distances\n####################################################################################################################\n# In order to keep track of all the distances for Dijkstra’s Algorithm, we will be using a heap! Using a heap \n# will allow removing the minimum from the heap to be efficient. In python, there is a library called heapq \n# which we will use to do all of our dirty work for us!\n#\n# The heapq method has two critical methods we will use in Dijkstra’s Algorithm: heappush and heappop.\n#\n# heappush will add a value to the heap and adjust the heap accordingly\n# heappop will remove and return the smallest value from the heap\n####################################################################################################################\n# Define the function with a start vertex and a graph.\n# \n# Instantiate a distances dictionary that will eventually map vertices to their distance from their start vertex.\n# Assign the start vertex a distance of 0.\n# Assign every other vertex a distance of infinity.\n# Set up a vertices_to_explore min-heap list that keeps track of neighboring vertices left to explore.\n#\n# First, we’ll traverse the vertices_to_explore heap until it is empty, popping off the vertex \n# with the minimum distance from start. Inside our while loop, we’ll iterate over the neighboring \n# vertices of current_vertex and add each neighbor (and its distance from start) to the vertices_to_explore min-heap.\n#\n# In each neighbor iteration, we will do the following:\n#\n# Identify neighbor‘s distance from start.\n# Make sure the new distance found for neighbor is less than the distance currently set for distances[neighbor].\n# Update distances[neighbor] if the new distance is smaller than the currently recorded distance.\n# Add neighbor and its distance to the vertices_to_explore min-heap.\n####################################################################################################################\n# Pseudo Code:\n#\n# create dictionary to map vertices to their distance from start vertex\n#\n# assign start vertex a distance of 0 in min heap\n#\n# assign every other vertex a distance of infinity in min heap\n#\n# remove the vertex with the minimum distance from the min heap and set it to the current vertex\n#\n# while min heap is not empty:\n# for each current vertex:\n# for each neighbor in neighbors:\n# new distance = (distance to current vertex) + (edge weight of current vertex to neighbor)\n#\n# if new distance is less than its current distance:\n# current distance = new distance\n#\n# return distances\n###################################################################################################################\n\nfrom heapq import heappop, heappush\nfrom math import inf\n\ngraph = {\n 'A': [('B', 10), ('C', 3)],\n 'C': [('D', 2)],\n 'D': [('E', 10)],\n 'E': [('A', 7)],\n 'B': [('C', 3), ('D', 2)]\n }\n\n\ndef dijkstras(graph, start):\n distances = {}\n \n for vertex in graph:\n distances[vertex] = inf\n \n distances[start] = 0\n vertices_to_explore = [(0, start)]\n \n while vertices_to_explore:\n current_distance, current_vertex = heappop(vertices_to_explore)\n \n for neighbor, edge_weight in graph[current_vertex]:\n new_distance = current_distance + edge_weight\n \n if new_distance < distances[neighbor]:\n distances[neighbor] = new_distance\n heappush(vertices_to_explore, (new_distance, neighbor))\n \n return distances\n \ndistances_from_d = dijkstras(graph, 'D')\nprint(\"\\n\\nShortest Distances: {0}\".format(distances_from_d))\n","sub_path":"dijkstras_algorithm.py","file_name":"dijkstras_algorithm.py","file_ext":"py","file_size_in_byte":4366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"141080831","text":"# Hint: You may not need all of these. Remove the unused functions.\nfrom hashtables import (HashTable,\n hash_table_insert,\n hash_table_remove,\n hash_table_retrieve,\n hash_table_resize)\n\n\nclass Ticket:\n def __init__(self, source, destination):\n self.source = source\n self.destination = destination\n\n\ndef reconstruct_trip(tickets, length):\n hashtable = HashTable(length)\n route = [None] * length\n\n # Build hash table by inserting the source as key and destination as value\n for i in range(length):\n start = tickets[i].source\n end = tickets[i].destination\n hash_table_insert(hashtable, start, end)\n\n # create initial element of route list by grabbing the ticket with NONE key/source\n route[0] = hash_table_retrieve(hashtable, 'NONE')\n # loop and add tickets to the route by using the destination/value of prior ticket as\n # the key/source for the current ticket\n for i in range(1, length):\n route[i] = hash_table_retrieve(hashtable, route[i-1])\n\n return route\n","sub_path":"hashtables/ex2/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"606729049","text":"import numpy as np\n\nfrom utility.undersample_split import resize_under_sample\nfrom utility.utility import file_exists, load\n\n\ndef check_mini_load(dataset, dataset_mode, dimensionCount):\n feature_file_name = dataset_mode + \"/\" + dataset.get_name() + '_features_' + str(dimensionCount)\n if file_exists(dataset.get_name() + \"_saved_labels\") and file_exists(feature_file_name):\n print('Using mini loading')\n labels = load(dataset.get_name() + \"_saved_labels\")\n if dataset_mode == \"2000\":\n emails, labels = resize_under_sample(labels, labels)\n labels = np.asarray(labels)\n return True, labels\n return False, None\n","sub_path":"src/utility/minimal_loader.py","file_name":"minimal_loader.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"459209317","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 03 14:03:46 2016\n\n@author: Gaoxiang\n\"\"\"\nimport re\nimport numpy as np\np_r = open(\"C:/Users/Gaoxiang/Desktop/232E/PROJ2/project_2_data/prlist.txt\",\"r\")\nf = open(\"C:/Users/Gaoxiang/Desktop/232E/PROJ2/project_2_data/processedAct.txt\",\"r\")\ng = open(\"C:/Users/Gaoxiang/Desktop/232E/PROJ2/project_2_data/movie_genre.txt\",\"r\")\ndi = open(\"C:/Users/Gaoxiang/Desktop/232E/PROJ2/project_2_data/director_movies.txt\",\"r\")\ntop = open(\"C:/Users/Gaoxiang/Desktop/232E/PROJ2/project_2_data/top100.txt\",\"r\")\nfeature_pr = open(\"C:/Users/Gaoxiang/Desktop/232E/PROJ2/project_2_data/feature_pagerank.txt\",\"w\")\nr = open(\"C:/Users/Gaoxiang/Desktop/232E/PROJ2/project_2_data/movie_rating.txt\",\"r\")\ntarget_rating = open(\"C:/Users/Gaoxiang/Desktop/232E/PROJ2/project_2_data/target_rating.txt\",\"w\")\ntest_feature= open(\"C:/Users/Gaoxiang/Desktop/232E/PROJ2/project_2_data/test_feature.txt\",\"w\")\nprint(\"open all the files successfully ...\")\n\nactorDict={}\nmovieDict={}\n\n\n#building movie dictionary, key=movie name\nmId=0\nfor line in g.readlines():\n\ttokens = line.split(\"\\t\\t\")\n\tmovieDict[tokens[0]]=[mId]\n\tmId+=1\n \nprint (\"movie:%d\"%(mId))\n\n#building actor dictionary, key=actor name\nactId=0\nfor line in f.readlines():\n tokens = line.split(\"\\t\\t\")\n actName = tokens[0]\n tokens[0] = actId\n \n for i in range(1, len(tokens)):\n movie = tokens[i]\n year = re.search(r'\\(\\d\\d\\d\\d\\)|\\(\\?\\?\\?\\?\\)',movie)\n if year:\n end=movie.find(year.group())\n tokens[i]=movie[:end+6]\n if movieDict.has_key(tokens[i]):\n movieDict[tokens[i]].append(actName)\n else:\n movieDict[tokens[i]]=[len(movieDict)]\n movieDict[tokens[i]].append(actName)\n actorDict[actName] = tokens[0]\n actId = actId + 1\nprint (\"actor:%d\"%(actId))\n\n#building top 100 dictionary, key=movie name\ntopDict={}\n#countTop={}\ncount=0\nfor lines in top.readlines():\n tokens=lines.split(\"\\t\")\n topDict[tokens[0]]=tokens[1] \n# countTop[count]=tokens[0]\n count=count+1\n\n#building director dictionary, key=movie ID\ndirectorDict={}\ntopdirList=[]\nmovieList=[]\nfor lines in di.readlines():\n tokens=lines.split(\"\\t\\t\")\n for i in range(1,len(tokens)):\n if (tokens[i] in movieDict):\n directorDict[movieDict[tokens[i]][0]]=tokens[0]\n if (tokens[i] in topDict):\n topdirList.append(tokens[0])\n movieList.append(tokens[i])\n#build top 100 list\nfor i in range(0,100):\n if countTop[i] not in movieList:\n print(countTop[i])\nprint (\"director:%d\"%(len(topdirList)))\n\n#building rating dictionary, key=movie ID\nratingDict={}\nfor line in r.readlines():\n tokens = line.split(\"\\t\\t\")\n movie = tokens[0]\n if (movie in movieDict) and(len(movieDict[movie])>5):\n ratingDict[movieDict[movie][0]]=tokens[1]\n\n#building pagerank dictionary, key=actor ID\npagerank_dict={}\ncount=0\nfor line in p_r.readlines():\n count=count+1\n tokens = line.split(\"\\t\\t\")\n pagerank_dict[int(tokens[0])]=float(tokens[1])\n if count%5000==0:\n print(\"construct pagerank_dict: %d\"%(count))\n\ntestID=[894353,779750,763762]\ntestFeature=np.zeros([3,9])\nct=0;\n\n#extract the feature\nfor movie in movieDict:\n ID=movieDict[movie][0]\n if (ID in testID):\n print(\"ID:%d\"%ID)\n testFeature[ct][0]=ID\n testpr=[]\n print(len(movieDict[movie]))\n for i in range(1,len(movieDict[movie])):\n actor=movieDict[movie][i]\n actorID=actorDict[actor]\n testpr.append(pagerank_dict[actorID])\n testpr=sorted(testpr,reverse=True)\n print(testpr)\n flag=0\n if(ID in directorDict and directorDict[ID] in topdirList):\n flag=1\n testFeature[ct][8]=flag\n testFeature[ct][6]=sum(testpr)\n testFeature[ct][7]=sum(testpr[:10])/10\n for j in range(1,6):\n testFeature[ct][j]=testpr[j-1]\n ct=ct+1\n pagerank=[]\n if(len(movieDict[movie])>5 and ID in ratingDict):\n for i in range(1,len(movieDict[movie])):\n actor=movieDict[movie][i]\n actorID=actorDict[actor]\n pagerank.append(pagerank_dict[actorID])\n pagerank=sorted(pagerank,reverse=True)\n average=sum(pagerank[:10])/10\n sumPage=sum(pagerank)\n flag=0\n if(ID in directorDict and directorDict[ID] in topdirList):\n flag=1\n s = '%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n'%(str(ID),str(pagerank[0]),str(pagerank[1]),str(pagerank[2]),str(pagerank[3]),str(pagerank[4]),str(sumPage),str(average),str(flag))\n feature_pr.write(s)\n d = '%s\\t%s'%(str(ID),ratingDict[ID])\n target_rating.write(d)\nnp.save('test_feature',testFeature)\n\np_r.close()\nf.close()\ng.close()\nfeature_pr.close()\ntarget_rating.close()\ntop.close()\ndi.close()\ntest_feature.close()","sub_path":"project2/P8_feature_extraction.py","file_name":"P8_feature_extraction.py","file_ext":"py","file_size_in_byte":4828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"586848214","text":"from __future__ import print_function\nimport tensorflow as tf\nimport keras.backend as K\nfrom keras.layers import RepeatVector\nimport sys\nfrom music21 import *\nimport numpy as np\nfrom grammar import *\nfrom preprocess import *\nfrom qa import *\n\n\ndef data_processing(corpus, values_indices, m = 60, Tx = 30):\n \n Tx = Tx \n N_values = len(set(corpus))\n np.random.seed(0)\n X = np.zeros((m, Tx, N_values), dtype=np.bool)\n Y = np.zeros((m, Tx, N_values), dtype=np.bool)\n for i in range(m):\n\n random_idx = np.random.choice(len(corpus) - Tx)\n corp_data = corpus[random_idx:(random_idx + Tx)]\n for j in range(Tx):\n idx = values_indices[corp_data[j]]\n if j != 0:\n X[i, j, idx] = 1\n Y[i, j-1, idx] = 1\n \n Y = np.swapaxes(Y,0,1)\n Y = Y.tolist()\n return np.asarray(X), np.asarray(Y), N_values \n\ndef next_value_processing(model, next_value, x, predict_and_sample, indices_values, abstract_grammars, duration, max_tries = 1000, temperature = 0.5):\n\n if (duration < 0.00001):\n tries = 0\n while (next_value.split(',')[0] == 'R' or \n len(next_value.split(',')) != 2):\n \n if tries >= max_tries:\n \n rand = np.random.randint(0, len(abstract_grammars))\n next_value = abstract_grammars[rand].split(' ')[0]\n else:\n next_value = predict_and_sample(model, x, indices_values, temperature)\n\n tries += 1\n \n return next_value\n\n\ndef sequence_to_matrix(sequence, values_indices):\n\n sequence_len = len(sequence)\n x = np.zeros((1, sequence_len, len(values_indices)))\n for t, value in enumerate(sequence):\n if (not value in values_indices): print(value)\n x[0, t, values_indices[value]] = 1.\n return x\n\ndef one_hot(x):\n x = K.argmax(x)\n x = tf.one_hot(x, 78) \n x = RepeatVector(1)(x)\n return x","sub_path":"music_utils.py","file_name":"music_utils.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"470083243","text":"from Generic.video import WriteVideo, WriteVideoFFMPEG\nfrom ParticleTrackingSimple.annotation import annotation_methods as am\nfrom ParticleTrackingSimple.general import dataframes\nfrom ParticleTrackingSimple.general.parameters import get_method_name\nfrom tqdm import tqdm\n\n\nclass TrackingAnnotator:\n\n def __init__(self, parameters=None, vidobject=None, data_filename=None, bitrate='HIGH1080', framerate=50):\n self.parameters = parameters\n self.cap = vidobject\n self.data_filename=data_filename\n self.output_filename = self.cap.filename[:-4] + '_annotate.mp4'\n frame_size = (self.cap.height, self.cap.width, 3)\n if parameters['videowriter'] == 'opencv':\n self.out = WriteVideo(filename=self.output_filename, frame_size=frame_size)\n elif parameters['videowriter'] == 'ffmpeg':\n self.out = WriteVideoFFMPEG(self.output_filename, bitrate=bitrate, framerate=framerate)\n\n def annotate(self, f_index=None):\n with dataframes.DataStore(self.data_filename, load=True) as data:\n if f_index is None:\n if self.parameters['subsection'] is None:\n start=0\n stop=self.cap.num_frames\n else:\n start = self.parameters['subsection'][0]\n stop = self.parameters['subsection'][1]\n\n else:\n start=f_index\n stop=f_index+1\n self.cap.set_frame(start)\n\n for f in tqdm(range(start, stop, 1), 'Annotating'):\n frame = self.cap.read_next_frame()\n for method in self.parameters['annotate_method']:\n method_name, call_num = get_method_name(method)\n frame = getattr(am, method_name)(frame, data, f, self.parameters, call_num=call_num)\n if f_index is None:\n self.out.add_frame(frame)\n if f_index is None:\n self.out.close()\n else:\n return frame\n\n\n\n","sub_path":"annotation/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"538665846","text":"# Copyright 2020 GRNET SA\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 charms.reactive as reactive\n\nimport charms_openstack.bus\nimport charms_openstack.charm as charm\n\ncharms_openstack.bus.discover()\n\n# Use the charms.openstack defaults for common states and hooks\ncharm.use_defaults(\n 'charm.installed',\n 'config.changed',\n 'update-status',\n 'upgrade-charm')\n\n\n@reactive.when('dashboard.available')\ndef dashboard_available():\n \"\"\"Relation to OpenStack Dashboard principal charm complete.\n \"\"\"\n with charm.provide_charm_instance() as watcher_dashboard_charm:\n dashboard_relation = reactive.endpoint_from_flag('dashboard.available')\n dashboard_relation.publish_plugin_info(\n \"\", None,\n conflicting_packages=watcher_dashboard_charm.purge_packages,\n install_packages=watcher_dashboard_charm.packages)\n watcher_dashboard_charm.assess_status()\n","sub_path":"src/reactive/watcher_dashboard_handlers.py","file_name":"watcher_dashboard_handlers.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"482029473","text":"\"\"\"project URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom mainapp.views import AgentViewRetrieveUpdate,AgentViewCreate, AgentViewDestroy\n\n\n\napp_name = 'mainapp'\nurlpatterns = [\n # path('api-auth/', include('rest_framework.urls')),\n path('admin/', admin.site.urls),\n path('api/agent/', AgentViewRetrieveUpdate.as_view(), name='test'),\n path('api/agent', AgentViewRetrieveUpdate.as_view(), name='test'),\n path('api/test', AgentViewCreate.as_view(), name='test'),\n path('api/test/', AgentViewDestroy.as_view(), name='test')\n]\n","sub_path":"project/project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"536096289","text":"import meganimal\nimport database\nimport urllib2\n\npath_file = 'C:\\\\Users\\\\793221\\\\Desktop\\\\Mega5.html'\nsite = open(path_file, \"r\").read()\n\n#main_site = \"https://www.meganimal.pt/pt/\" \n#main_site = urllib2.urlopen(main_site, timeout = 10)\n\n#sites = meganimal.get_href(main_site)\ndatabase.clear(\"produtos\",\"meganimal\")\ndatabase.create(\"produtos\",\"meganimal\")\n\n#for site in sites:\ndata = meganimal.get_data(site)\ndatabase.update(\"produtos\",\"meganimal\",data)\n\nimport sqlite3\nconnection = sqlite3.connect(\"produtos.db\")\n\ncursor = connection.cursor()\n\ncursor.execute(\"SELECT * FROM meganimal\") \nresult = cursor.fetchall() \nfor r in result:\n print(r)\n","sub_path":"meganimal_compiler.py","file_name":"meganimal_compiler.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"275212947","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import loader\nfrom Search.models import User, Vehicle, Store, Order\nfrom django.shortcuts import get_object_or_404\nimport datetime\n\n\ndef Rent(request, id):\n if request.method == 'GET':\n return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))\n\n DateStart = request.POST.get('pickupdate')\n DateEnd = request.POST.get('returndate')\n EndLocation = request.POST.get('endlocation')\n\n\n Locations = ['Coffs Harbour', 'Darlinghurst', 'Goulburn', 'Melbourne', 'Gold Coast', 'Springwood']\n\n\n if DateStart == \"\" or DateEnd == \"\" or EndLocation == \"0\":\n return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))\n Reservable = True\n name = -1\n userid = -1\n auth = -1\n\n if request.session.has_key('email'):\n uservar = User.objects.get(username=request.session['email'])\n name = uservar.name\n userid = uservar.userid\n auth = uservar.authenticationlevel\n\n else:\n return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))\n\n today = datetime.datetime.today().strftime('%Y%m%d')\n if int(DateStart[0:4]+DateStart[5:7]+DateStart[8:11]) < int(today) or int(DateEnd[0:4]+DateEnd[5:7]+DateEnd[8:11]) < int(today):\n return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))\n\n EndLocation = Locations[int(EndLocation) - 1]\n car = get_object_or_404(Vehicle, carid=id)\n\n\n\n #Complete list of orders between the two dates\n orderlist = Order.objects.filter(pickupdate__range=(int(DateStart[0:4]+DateStart[5:7]+DateStart[8:11]), int(DateEnd[0:4]+DateEnd[5:7]+DateEnd[8:11]))\n , returndate__range=(int(DateStart[0:4]+DateStart[5:7]+DateStart[8:11]), int(DateEnd[0:4]+DateEnd[5:7]+DateEnd[8:11])))\n\n\n for i in orderlist:\n if str(car.carid) == str(i.carid):\n Reservable = False\n\n orderlocation = Store.objects.get(storeid=str(car.storeid)).city\n\n template = loader.get_template('RentedPage.html')\n context = {\n 'name': name,\n 'userid': userid,\n 'authlevel': auth,\n 'session': request.session.has_key('email'),\n 'carmake': car.carmake,\n 'Model': car.model,\n 'Year': car.year,\n 'Fuelsystem': car.fuelsystem,\n 'Transmission': car.standardtransmission,\n 'Seating': car.seatingcapacity,\n 'Carpower': car.carpower,\n 'Location': orderlocation,\n 'DatePickUp': datetime.datetime.strptime(DateStart, \"%Y-%m-%d\").strftime(\"%B %d, %Y\"),\n 'DateDropOff': datetime.datetime.strptime(DateEnd, \"%Y-%m-%d\").strftime(\"%B %d, %Y\"),\n 'LocationDrop': EndLocation,\n 'Price': int(car.price)*0.001,\n 'datestart':DateStart,\n 'dateend':DateEnd,\n 'endlocation':EndLocation,\n 'Reservable':Reservable,\n }\n return HttpResponse(template.render(context, request))\n\n\n\ndef BeginRent(request, id):\n name = -1\n userid = -1\n auth = -1\n\n if request.session.has_key('email'):\n uservar = User.objects.get(username=request.session['email'])\n name = uservar.name\n userid = uservar.userid\n auth = uservar.authenticationlevel\n\n else:\n return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))\n\n DesiredLocation = request.POST.get('endlocation')\n DateStart = datetime.datetime.strptime(request.POST.get('pickupdate'), \"%Y-%m-%d\").strftime(\"%Y%m%d\")\n DateEnd = datetime.datetime.strptime(request.POST.get('returndate'), \"%Y-%m-%d\").strftime(\"%Y%m%d\")\n\n car = Vehicle.objects.get(carid=id)\n\n\n orderlocation = Store.objects.get(storeid=str(car.storeid))\n dropofflocation = Store.objects.get(city__contains=DesiredLocation)\n Today = datetime.datetime.today().strftime('%Y%m%d')\n\n Order.objects.create(userid=uservar, carid=car, createdate=Today, pickupdate=DateStart, pickupstore=orderlocation, returndate=DateEnd, returnstore=dropofflocation)\n return HttpResponseRedirect('/../.')\n\n\n","sub_path":"Backup of Server/RentedPage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"648031967","text":"from django.shortcuts import render, HttpResponseRedirect, reverse\nfrom django.contrib.auth import login, logout, authenticate\nfrom recipe.models import RecipeItem, Author\nfrom recipe.forms import AddAuthor, AddRecipeItem, LoginForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.contrib.auth.models import User\n\n\ndef index(request):\n html = \"index.html\"\n\n recipes = RecipeItem.objects.all()\n\n return render(request, html, {'data': recipes})\n\n\ndef recipe_view(request, id):\n recipe_html = \"recipe.html\"\n recipe = RecipeItem.objects.filter(id=id)\n\n return render(request, recipe_html, {'data': recipe})\n\n\ndef author_view(request, id):\n author_html = \"author.html\"\n author = Author.objects.filter(id=id)\n recipe = RecipeItem.objects.filter(author=id)\n\n return render(request, author_html, {'data': author, 'recipe': recipe})\n\n\n@login_required\ndef addauthorview(request):\n html = 'generic_form.html'\n if request.user.is_staff:\n if request.method == 'POST':\n form = AddAuthor(request.POST)\n if form.is_valid():\n data = form.cleaned_data\n u = User.objects.create_user(\n username=data['name'],\n password=data['password']\n )\n Author.objects.create(\n user=u,\n name=data['name'],\n bio=data['bio'],\n )\n return HttpResponseRedirect(reverse('homepage'))\n form = AddAuthor()\n return render(request, html, {'form': form})\n\n\n\n@login_required\ndef addrecipeview(request):\n html = 'generic_form.html'\n\n if request.method == \"POST\":\n form = AddRecipeItem(request.POST)\n form.save()\n return HttpResponseRedirect(reverse('homepage'))\n\n form = AddRecipeItem()\n\n return render(request, html, {'form': form})\n\n\ndef login_view(request):\n html = 'generic_form.html'\n\n if request.method == \"POST\":\n breakpoint()\n form = LoginForm(request.POST)\n\n if form.is_valid():\n data = form.cleaned_data\n user = authenticate(\n username=data['username'],\n password=data['password']\n )\n if user:\n login(request, user)\n return HttpResponseRedirect(request.GET.get('next', reverse('homepage')))\n\n form = LoginForm()\n\n return render(request, html, {'form': form})\n\n\ndef logout_view(request):\n logout(request)\n return HttpResponseRedirect(reverse('homepage'))","sub_path":"recipe/recipe/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"197619965","text":"\"\"\"\nhttps://www.hackerrank.com/contests/projecteuler/challenges/euler022\n\"\"\"\n\nnumNames = int(input())\nnames = [input().upper() for _ in range(numNames)]\nnames = sorted(names)\n\nnumWords = int(input())\nfor _ in range(numWords):\n word = input()\n position = names.index(word) + 1\n score = 0\n for ch in word:\n score += ord(ch) - ord('A') + 1\n print(score * position)\n","sub_path":"hackerrank/euler/euler022/euler022.py","file_name":"euler022.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"52860297","text":"#!/usr/bin/env python\n\n\ndef main(args):\n\n import argparse\n import gc\n import pathlib\n from sklearn.externals import joblib\n import numpy as np\n from peakachu import scoreUtils, utils\n\n np.seterr(divide='ignore', invalid='ignore')\n\n pathlib.Path(args.output).mkdir(parents=True, exist_ok=True)\n\n model = joblib.load(args.model)\n\n # more robust to check if a file is .hic\n hic_info = utils.read_hic_header(args.path)\n if hic_info is None:\n hic = False\n import cooler\n Lib = cooler.Cooler(args.path)\n chromosomes = Lib.chromnames[:]\n #nam = args.path.split('.cool')[0]\n else:\n hic = True\n chromosomes = utils.get_hic_chromosomes(args.path, args.resolution)\n #nam = args.path.split('.hic')[0]\n #nam = nam.split('/')[-1]\n\n for key in chromosomes:\n if key.startswith('chr'):\n cname = key\n else:\n cname = 'chr'+key\n if not hic:\n X = scoreUtils.Chromosome(Lib.matrix(balance=args.balance, sparse=True).fetch(key).tocsr(),\n model=model,\n cname=cname, lower=args.lower,\n upper=args.upper, res=args.resolution,\n width=args.width)\n else:\n if args.balance:\n X = scoreUtils.Chromosome(utils.csr_contact_matrix('KR', args.path, key, key, 'BP', args.resolution),\n model=model,\n cname=cname, lower=args.lower,\n upper=args.upper, res=args.resolution,\n width=args.width)\n else:\n X = scoreUtils.Chromosome(utils.csr_contact_matrix('NONE', args.path, key, key, 'BP', args.resolution),\n model=model,\n cname=cname, lower=args.lower,\n upper=args.upper, res=args.resolution,\n width=args.width)\n\n result, R = X.score(thre=args.minimum_prob)\n X.writeBed(args.output, result, R)\n","sub_path":"peakachu/score_genome.py","file_name":"score_genome.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"66447079","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom email.mime.text import MIMEText\nimport smtplib\nfrom email.utils import formataddr, parseaddr\nfrom email.header import Header\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\nfrom email import encoders\n\n# 二十一、电子邮件\n# 一封电子邮件的旅程就是:\n# 发件人 -> MUA -> MTA -> MTA -> 若干个MTA -> MDA <- MUA <- 收件人\n# MUA:邮件用户代理 MTA:邮件传输代理 MDA:邮件投递代理\n# SMTP:发送邮件,MUA和MTA使用的协议,以及MTA和MTA之间。Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。\n# IMAP、POP3:MUA和MDA\n\n# 1.SMTP发送邮件\nmsg = MIMEText('

Hello

' +\n '

send by Python...

' +\n '', 'html','utf-8') \n# 输入Email地址和口令:\nfrom_addr = input('From: ')\npassword = input('Password: ')\n# 输入收件人地址:\nto_addr = input('To: ')\n# 输入SMTP服务器地址:\nsmtp_server = input('SMTP server: ')\n\n# 通过此函数格式化MIME信息,使得显示发件人、收件人、主题等,否则可能被outlook列为垃圾邮件\ndef _format_addr(s):\n name, addr = parseaddr(s)\n return formataddr((Header(name, 'utf-8').encode(), addr))\n\nmsg['From'] = _format_addr('Python爱好者 <%s>' % from_addr)\nmsg['To'] = _format_addr('管理员 <%s>' % to_addr)\nmsg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()\n\n# 添加附件:构造一个MIMEMultipart对象代表邮件本身,然后往里面加上一个MIMEText作为邮件正文,再继续往里面加上表示附件的MIMEBase对象\nmsg1 = MIMEMultipart()\n\n# msg1.attach(MIMEText('Hello,attach'+\n # '

','html','utf-8')) \n\nmsg1.attach(MIMEText('

Hello

' +\n '

' +\n '', 'html', 'utf-8'))\n\nmsg1['From'] = _format_addr('Python爱好者 <%s>' % from_addr)\nmsg1['To'] = _format_addr('管理员 <%s>' % to_addr)\nmsg1['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()\n\n# 添加附件就是加上一个MIMEBase,从本地读取一个图片:\nwith open('/Users/herry/Documents/python/test.jpg', 'rb') as f: # 如果要将图片嵌入正文,在MIMEText中添加img标签,然后img里添加src=\"cid:0\"\n # 设置附件的MIME和文件名,这里是png类型:\n mime = MIMEBase('image', 'jpeg', filename='test.jpg')\n # 加上必要的头信息:\n mime.add_header('Content-Disposition', 'attachment', filename='test.jpg')\n mime.add_header('Content-ID', '<0>')\n mime.add_header('X-Attachment-Id', '0')\n # 把附件的内容读进来:\n mime.set_payload(f.read())\n # 用Base64编码:\n encoders.encode_base64(mime)\n # 添加到MIMEMultipart:\n msg1.attach(mime)\n\nserver = smtplib.SMTP(smtp_server, 587) # SMTP协议默认端口是25,加密ssl的端口是587,smtp.qq.com的话是587、465\nserver.starttls() # 加密连接要加这句\nserver.set_debuglevel(1) # set_debuglevel(1)打印出和SMTP服务器交互的所有信息\nserver.login(from_addr, password) # 登录smtp服务器\nserver.sendmail(from_addr, [to_addr], msg1.as_string()) # 发送邮件,as_string()将MIME转为str\nserver.quit()","sub_path":"test_4.py","file_name":"test_4.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"164914049","text":"import torch, os\nimport numpy as np\nfrom PIL import Image\nfrom torchvision import transforms\nfrom torch.utils.data import Dataset, DataLoader\n\n\ndef _TRAIN_TRANSFORM(h, w): \n return transforms.Compose([transforms.RandomResizedCrop((h, w), (0.8, 1.0)),\n transforms.RandomGrayscale(p=0.05),\n transforms.ColorJitter(brightness=0.4, contrast=0.3, saturation=0.3, hue=0.3),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], \n std=[0.229, 0.224, 0.225])])\ndef _TEST_TRANSFORM(h, w):\n return transforms.Compose([transforms.Resize((h, w)),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], \n std=[0.229, 0.224, 0.225])])\n\n\nclass ImageRegression(Dataset):\n def __init__(self, images, targets, transform=None):\n self._images = images.copy()\n self._targets = targets.astype(np.float32).copy()\n self._transform = transform\n \n def __len__(self):\n return int(self._images.shape[0])\n \n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n assert 0 <= idx < len(self)\n np.random.seed(None)\n\n img = Image.fromarray(self._images[idx])\n img = self._transform(img) if self._transform else img\n target = self._targets[idx]\n return img, target\n\n\nclass ImageStateRegression(ImageRegression):\n def __init__(self, images, state, targets, transform=None):\n super().__init__(images, targets, transform)\n self._state = state.copy().astype(np.float32)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n img, target = super().__getitem__(idx)\n state = self._state[idx]\n return img, state, target\n\n\nclass SnippetDataset(Dataset):\n def __init__(self, images, states, targets, starts, H=10, transform=None):\n super().__init__()\n self._H, self._transform = H, transform\n self._images, self._states = images, states\n self._targets = targets\n\n self._starts, end = [], self._images.shape[1] - H\n for i, start in enumerate(starts):\n self._starts.extend([(i, s) for s in range(start, end + 1)])\n \n def __len__(self):\n return len(self._starts)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n \n b, t = self._starts[idx]\n states = self._states[b,t:t+self._H]\n targets = self._targets[b,t:t+self._H]\n images = self._images[b,t:t+self._H]\n if self._transform is not None:\n images = [self._transform(Image.fromarray(i))[None] for i in images]\n images = torch.cat(images, 0)\n return images, states, targets\n\n\nclass GoalCondBC(ImageStateRegression):\n def __init__(self, images, goals, states, actions, transform=None):\n super().__init__(images, states, actions, transform)\n self._goal = goals.copy()\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n img, state, actions = super().__getitem__(idx)\n goal = Image.fromarray(self._goal[idx])\n goal = self._transform(goal) if self._transform else goal\n return img, goal, state, actions\n\n\ndef pretext_dataset(fname, batch_size):\n data = np.load(fname)\n\n # load dataset\n train_imgs = data['train_imgs']\n h, w = train_imgs.shape[1:3]\n train_data = DataLoader(ImageRegression(train_imgs, data['train_pos'], _TRAIN_TRANSFORM(h, w)), \n batch_size=batch_size, shuffle=True, num_workers=5)\n test_data = DataLoader(ImageRegression(data['test_imgs'], data['test_pos'], _TEST_TRANSFORM(h, w)), \n batch_size=256)\n return train_data, test_data, data['mean_train_pos']\n\n\ndef state_action_dataset(fname, batch_size):\n data = np.load(fname)\n def _flat_traj(key, starts):\n d, d_flat = data[key], []\n for i, s in enumerate(starts):\n d_flat.append(d[i, s:])\n d_flat = np.concatenate(d_flat, 0)\n return d_flat\n\n # load dataset\n imgs, states, actions = [_flat_traj(k, data['train_start']) for k in \n ('train_images', 'train_states', 'train_actions')]\n h, w = imgs.shape[1:3]\n train_mean, train_std = np.mean(actions, axis=0), np.std(actions, axis=0)\n train_data = DataLoader(ImageStateRegression(imgs, states, actions, _TRAIN_TRANSFORM(h, w)),\n batch_size=batch_size, shuffle=True, num_workers=5)\n imgs, states, actions = [_flat_traj(k, data['test_start']) for k in \n ('test_images', 'test_states', 'test_actions')]\n test_data = DataLoader(ImageStateRegression(imgs, states, actions, _TEST_TRANSFORM(h, w)), \n batch_size=256)\n return train_data, test_data, (train_mean, train_std)\n\n\ndef snippet_dataset(fname, batch_size, H):\n data = np.load(fname)\n images, states, actions = data['train_images'], data['train_states'], data['train_actions']\n starts = data['train_start']\n h, w = images.shape[2:4]\n train_data = DataLoader(SnippetDataset(images, states, actions, starts, H, _TRAIN_TRANSFORM(h, w)),\n batch_size=batch_size, shuffle=True, num_workers=10)\n images, states, actions = data['test_images'], data['test_states'], data['test_actions']\n starts = data['test_start']\n test_data = DataLoader(SnippetDataset(images, states, actions, starts, H, _TEST_TRANSFORM(h, w)),\n batch_size=20)\n return train_data, test_data\n\n\ndef image_goal_dataset(fname, batch_size, H=30):\n data = np.load(fname)\n def _flat_traj(split):\n imgs = data['{}_images'.format(split)]\n states = data['{}_states'.format(split)]\n actions = data['{}_actions'.format(split)]\n\n B, T, A = actions.shape\n i, g, s, a = [], [], [], []\n for t in range(T - H):\n i.append(imgs[:,t])\n g.append(imgs[:,-1])\n s.append(states[:,t])\n a.append(actions[:,t:t+H])\n i, g, s, a = [np.concatenate(arr, 0) for arr in (i, g, s, a)]\n return i, g, s, a\n\n # load dataset\n imgs, goals, states, actions = _flat_traj('train')\n h, w = imgs.shape[2:4]\n train_data = DataLoader(GoalCondBC(imgs, goals, states, actions, _TRAIN_TRANSFORM(h, w)),\n batch_size=batch_size, shuffle=True, num_workers=5)\n imgs, goals, states, actions = _flat_traj('test')\n test_data = DataLoader(GoalCondBC(imgs, goals, states, actions, _TEST_TRANSFORM(h, w)), \n batch_size=256)\n return train_data, test_data\n\n\ndef traj_dataset(fname, batch_size):\n data = np.load(fname)\n \n # load dataset\n imgs, states, actions = data['train_images'][:,0], data['train_states'][:,0], \\\n data['train_actions']\n h, w = imgs.shape[1:3]\n train_data = DataLoader(ImageStateRegression(imgs, states, actions, _TRAIN_TRANSFORM(h, w)),\n batch_size=batch_size, shuffle=True, num_workers=5)\n imgs, states, actions = data['test_images'][:,0], data['test_states'][:,0], \\\n data['test_actions']\n test_data = DataLoader(ImageStateRegression(imgs, states, actions, _TEST_TRANSFORM(h,w)), \n batch_size=256)\n return train_data, test_data\n\n","sub_path":"baselines/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":7687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"610698553","text":"from django.views import generic\nfrom django.shortcuts import render, get_object_or_404\n\nfrom . import models\n\n\nclass ProductListView(generic.ListView):\n queryset = models.Product.objects.all()\n template_name = 'product/list.html'\n\n\nclass ProductFeaturedListView(generic.ListView):\n template_name = 'product/list.html'\n\n def get_queryset(self, *args, **kwargs):\n request = self.request\n return models.Product.objects.featured()\n\n\nclass ProductDetailView(generic.DetailView):\n queryset = models.Product.objects.all()\n template_name = 'product/detail.html'\n\n def get_context_data(self, *args, **kwargs):\n return super(ProductDetailView, self).get_context_data(*args, **kwargs)\n\n\nclass ProductFeaturedDetailView(generic.DetailView):\n template_name = 'product/detail.html'\n\n def get_queryset(self, *args, **kwargs):\n request = self.request\n return models.Product.objects.featured()\n","sub_path":"apps/product/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"445908706","text":"#!/usr/bin/env python3\nimport collections as cl\nimport sys\n\n\ndef II():\n return int(sys.stdin.readline())\n\n\ndef MI():\n return map(int, sys.stdin.readline().split())\n\n\ndef LI():\n return list(map(int, sys.stdin.readline().split()))\n\n\ndef main():\n n, m = MI()\n connected = []\n for i in range(m):\n row = LI()\n swithes = row[1:]\n connected.append(swithes)\n p = LI()\n ans = 0\n for i in range(2 ** n):\n i_str = format(i, f\"0{n}b\")\n is_ok = True\n for m_idx in range(m):\n sum_1 = 0\n for swith in connected[m_idx]:\n if i_str[swith - 1] == \"1\":\n sum_1 += 1\n\n if sum_1 % 2 != p[m_idx]:\n is_ok = False\n break\n\n if is_ok:\n ans += 1\n\n print(ans)\n\n\nmain()\n","sub_path":"Python_codes/p03031/s442747731.py","file_name":"s442747731.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"143733726","text":"import math\nimport time\nimport resource\nimport warnings\nimport datetime\nimport sys\nimport itertools\n\nimport dolfin as df\nimport numpy as np\n\nfrom pathlib import Path\nfrom scipy import signal\nfrom math import pi\nfrom multiprocessing import Pool\n\nfrom postfields import (\n Field,\n PointField,\n)\n\nfrom typing import (\n Union,\n Dict,\n Sequence,\n Tuple,\n)\n\nfrom extension_modules import load_module\n\nfrom post import Saver\nfrom coupled_brainmodel import CoupledBrainModel\nfrom coupled_splittingsolver import BidomainSplittingSolver\n\nfrom postutils import (\n interpolate_ic,\n store_sourcefiles,\n simulation_directory,\n circle_points,\n)\n\nfrom xalbrain.cellmodels import (\n Cressman,\n FitzHughNagumoManual,\n Noble\n)\n\nfrom coupled_utils import (\n CellTags,\n InterfaceTags,\n CoupledSplittingSolverParameters,\n CoupledODESolverParameters,\n CoupledBidomainParameters,\n get_mesh,\n)\n\nfrom postspec import (\n FieldSpec,\n SaverSpec,\n)\n\n\ndef assign_ic_subdomain(\n *,\n brain: CoupledBrainModel,\n vs_prev: df.Function,\n value: float,\n subdomain_id: int,\n subfunction_index: int\n) -> None:\n \"\"\"\n Compute a function with `value` in the subdomain corresponding to `subdomain_id`.\n Assign this function to subfunction `subfunction_index` of vs_prev.\n \"\"\"\n mesh = brain._mesh\n cell_function = brain._cell_function\n\n dX = df.Measure(\"dx\", domain=mesh, subdomain_data=cell_function)\n\n V = df.FunctionSpace(mesh, \"DG\", 0)\n u = df.TrialFunction(V)\n v = df.TestFunction(V)\n sol = df.Function(V)\n sol.vector().zero() # Make sure it is initialised to zero\n\n F = -u*v*dX(subdomain_id) + df.Constant(value)*v*dX(subdomain_id)\n a = df.lhs(F)\n L = df.rhs(F)\n\n A = df.assemble(a, keep_diagonal=True)\n A.ident_zeros()\n b = df.assemble(L)\n solver = df.KrylovSolver(\"cg\", \"petsc_amg\")\n solver.set_operator(A)\n solver.solve(sol.vector(), b)\n\n VCG = df.FunctionSpace(mesh, \"CG\", 1)\n v_new = df.Function(VCG)\n v_new.interpolate(sol)\n\n Vp = vs_prev.function_space().sub(subfunction_index)\n merger = df.FunctionAssigner(Vp, VCG)\n merger.assign(vs_prev.sub(subfunction_index), v_new)\n\n\ndef assign_initial_condition(brain, vs_prev: df.Function, cell_model_dict: Dict[int, Sequence[float]]):\n\n for index in range(max(map(len, cell_model_dict.values()))):\n tmp_dict = {}\n for k, values in cell_model_dict.items():\n tmp_dict[k] = 0 if index >= len(values) else values[index]\n\n assign_ic_subdomain(\n brain=brain,\n vs_prev=vs_prev,\n value_dict=tmp_dict,\n subfunction_index=index\n )\n\n\ndef get_brain(case_id, conductivity) -> CoupledBrainModel:\n time_constant = df.Constant(0)\n mesh, cell_function, interface_function = get_mesh(\"squiggly_meshes\", \"flower\")\n\n cell_tags = CellTags(CSF=3, GM=2, WM=1, Kinf=4)\n interface_tags = InterfaceTags(skull=None, CSF_GM=None, GM_WM=None, CSF=None, GM=None, WM=None)\n\n test_cell_function = df.MeshFunction(\"size_t\", mesh, mesh.geometric_dimension())\n test_cell_function.set_all(0)\n\n df.CompiledSubDomain(\"x[1] >= -pi/16*x[0]\").mark(test_cell_function, 4)\n if case_id == 1:\n df.CompiledSubDomain(\"x[1] >= 25*pi/16*x[0]\").mark(test_cell_function, 2)\n elif case_id == 2:\n df.CompiledSubDomain(\"x[1] >= 7*pi/32*x[0]\").mark(test_cell_function, 2)\n\n cell_function.array()[(cell_function.array() == 2) & (test_cell_function.array() == 4)] = 4\n\n Chi = 1.26e3 # 1/cm -- Dougherty 2015\n Cm = 1.0 # muF/cm^2 -- Dougherty 2015\n\n Mi_dict = {\n 3: df.Constant(1e-12), # Set to zero? 1e-12\n 1: df.Constant(conductivity), # Dlougherty isotropic WM intracellular conductivity 1.0 [mS/cm]\n 2: df.Constant(conductivity), # Dlougherty isotropic GM intracellular conductivity 1.0 [mS/cm]\n 4: df.Constant(conductivity), # Dlougherty isotropic GM intracellular conductivity 1.0 [mS/cm]\n }\n\n Me_dict = {\n 3: df.Constant(16.54), # Dougherty isotropic CSF conductivity 16.54 [mS/cm] 16.54\n 1: df.Constant(1.26), # 1.26 # Dougherty isotropic WM extracellular conductivity 1.26 [mS/cm]\n 2: df.Constant(2.76), # 2.76 # Dougherty isotropic GM extracellular conductivity 2.76 [mS/cm]\n 4: df.Constant(2.76), # 2.76 # Dougherty isotropic GM extracellular conductivity 2.76 [mS/cm]\n }\n\n brain = CoupledBrainModel(\n time=time_constant,\n mesh=mesh,\n cell_model=Cressman(),\n cell_function=cell_function,\n cell_tags=cell_tags,\n interface_function=interface_function,\n interface_tags=interface_tags,\n intracellular_conductivity=Mi_dict,\n other_conductivity=Me_dict, # Either lmbda or extracellular\n surface_to_volume_factor=Chi,\n membrane_capacitance=Cm\n )\n return brain\n\n\ndef get_solver(brain, Ks, Ku) -> BidomainSplittingSolver:\n\n odesolver_module = load_module(\"LatticeODESolver\")\n odemap = odesolver_module.ODEMap()\n # odemap.add_ode(1, odesolver_module.Fitzhugh())\n odemap.add_ode(2, odesolver_module.Cressman(Ks))\n odemap.add_ode(4, odesolver_module.Cressman(Ku))\n print(\"f1\")\n\n parameters = CoupledSplittingSolverParameters()\n ode_parameters = CoupledODESolverParameters(\n valid_cell_tags=(1, 2,),\n # valid_cell_tags=(1, 2, 4),\n reload_extension_modules=False,\n parameter_map=odemap\n )\n print(\"f2\")\n\n pde_parameters = CoupledBidomainParameters(linear_solver_type=\"direct\")\n\n solver = BidomainSplittingSolver(\n brain=brain,\n parameters=parameters,\n ode_parameters=ode_parameters,\n pde_parameters=pde_parameters\n )\n print(\"f3\")\n\n vs_prev, *_ = solver.solution_fields()\n\n cressman_values = list(Cressman.default_initial_conditions().values())\n fitzhugh_values = list(FitzHughNagumoManual.default_initial_conditions().values())\n\n fitzhugh_full_values = [0]*len(cressman_values)\n fitzhugh_full_values[len(fitzhugh_values)] = fitzhugh_values\n print(\"f4\")\n\n csf_values = [0]*len(cressman_values)\n\n _, cell_function, _ = get_mesh(\"squiggly_meshes\", \"flower\")\n\n cell_model_dict = {\n 1: cressman_values,\n 3: csf_values,\n 2: cressman_values,\n 4: cressman_values,\n }\n print(\"f5\")\n odesolver_module.assign_vector(\n vs_prev.vector(),\n cell_model_dict,\n cell_function,\n vs_prev.function_space()._cpp_object\n )\n print(\"f6\")\n\n return solver\n\n\ndef get_saver(\n brain: CoupledBrainModel,\n outpath: Union[str, Path],\n case_index: int\n) -> Saver:\n sourcefiles = [\n \"coupled_bidomain.py\",\n \"coupled_brainmodel.py\",\n \"coupled_odesolver.py\",\n \"coupled_splittingsolver.py\",\n \"coupled_utils.py\",\n \"run_idealised.py\",\n ]\n store_sourcefiles(map(Path, sourcefiles), outpath)\n\n saver_parameters = SaverSpec(casedir=outpath, overwrite_casedir=True)\n saver = Saver(saver_parameters)\n saver.store_mesh(brain.mesh)\n\n field_spec_checkpoint = FieldSpec(save_as=(\"xdmf\", \"hdf5\"), stride_timestep=20)\n saver.add_field(Field(\"v\", field_spec_checkpoint))\n saver.add_field(Field(\"u\", field_spec_checkpoint))\n\n field_spec_checkpoint = FieldSpec(save_as=(\"hdf5\"), stride_timestep=20*1000)\n saver.add_field(Field(\"vs\", field_spec_checkpoint))\n\n trace_names = []\n r = np.linspace(-9, 9, )\n points = np.zeros(shape=(r.size, 2))\n for sub_index in range(7):\n point_field_spec = FieldSpec(stride_timestep=4, sub_field_index=sub_index)\n for theta in [1, 5, 9, 13]:\n points[:, 0] = r*np.cos(theta)\n points[:, 1] = r*np.sin(theta)\n name = \"trace{}_{}\".format(sub_index, theta)\n saver.add_field(PointField(name, point_field_spec, points))\n trace_names.append(name)\n\n angular_offset = pi/8\n points[:, 0] = r*np.cos(theta + angular_offset)\n points[:, 1] = r*np.sin(theta + angular_offset)\n name = \"trace_offset{}_{}\".format(sub_index, theta)\n saver.add_field(PointField(name, point_field_spec, points))\n trace_names.append(name)\n\n return saver, trace_names\n\n\nif __name__ == \"__main__\":\n warnings.simplefilter(\"ignore\", UserWarning)\n\n\n def run(args):\n conductivity, case_id, Ks, Ku = args\n T = 10e3 # 10 seconds\n dt = 0.05\n print(1)\n\n brain = get_brain(case_id, conductivity)\n print(2)\n solver = get_solver(brain, Ks, Ku)\n print(3)\n\n identifier = simulation_directory(\n home=Path(\".\"),\n parameters={\n \"time\": datetime.datetime.now(),\n \"case_id\": case_id,\n \"conductivity\": conductivity,\n \"Ks\": Ks,\n \"Ku\": Ku\n },\n directory_name=\"squiggly/K_{}_{}\".format(Ks, Ku)\n )\n print(4)\n\n saver, trace_name_list = get_saver(brain, identifier, case_id)\n print(5)\n\n resource_usage = resource.getrusage(resource.RUSAGE_SELF)\n tick = time.perf_counter()\n print(5)\n\n for i, solution_struct in enumerate(solver.solve(0, T, dt)):\n norm = solution_struct.vur.vector().norm('l2')\n if math.isnan(norm):\n assert False, \"nan nan nan\"\n print(f\"{i} -- {brain.time(0):.5f} -- {norm:.6e}\")\n\n update_dict = dict()\n if saver.update_this_timestep(field_names=[\"u\", \"v\"], timestep=i, time=brain.time(0)):\n v, u, *_ = solution_struct.vur.split(deepcopy=True)\n update_dict.update({\"v\": v, \"u\": u})\n\n if saver.update_this_timestep(field_names=trace_name_list, timestep=i, time=brain.time(0)):\n update_dict.update({k: solution_struct.vs for k in trace_name_list})\n\n if saver.update_this_timestep(field_names=[\"vs\"], timestep=i, time=brain.time(0)):\n update_dict.update({\"vs\": solution_struct.vs})\n\n if len(update_dict) != 0:\n saver.update(brain.time, i, update_dict)\n\n saver.close()\n tock = time.perf_counter()\n max_memory_usage = resource_usage.ru_maxrss/1e6 # Kb to Gb\n print(\"Max memory usage: {:3.1f} Gb\".format(max_memory_usage))\n print(\"Execution time: {:.2f} s\".format(tock - tick))\n\n run((1, 1, 4, 8))\n # conductivities = [2**(2*n) for n in range(-3, 2)]\n # lengths = list(range(3))\n\n # Ks = float(sys.argv[1])\n # Ku = float(sys.argv[2])\n\n # parameter_list = list(itertools.product(conductivities, lengths, [Ks], [Ku]))\n\n # pool = Pool(processes=len(parameter_list))\n # pool.map(run, parameter_list)\n","sub_path":"paper_simulations/squiggly_experiment/run_idealised.py","file_name":"run_idealised.py","file_ext":"py","file_size_in_byte":10877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"227558292","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport warnings\n\nimport numpy as np\nfrom numpy.testing import assert_allclose\nimport pytest\nfrom astropy.utils.exceptions import AstropyDeprecationWarning\n\nfrom .. import ShepardIDWInterpolator as idw\nfrom .. import interpolate_masked_data, mask_to_mirrored_num\n\ntry:\n import scipy # noqa\n HAS_SCIPY = True\nexcept ImportError:\n HAS_SCIPY = False\n\n\nSHAPE = (5, 5)\nDATA = np.ones(SHAPE) * 2.0\nMASK = np.zeros_like(DATA, dtype=bool)\nMASK[2, 2] = True\nERROR = np.ones(SHAPE)\nBACKGROUND = np.ones(SHAPE)\nWRONG_SHAPE = np.ones((2, 2))\n\n\n@pytest.mark.skipif('not HAS_SCIPY')\nclass TestShepardIDWInterpolator(object):\n def setup_class(self):\n np.random.seed(123)\n self.x = np.random.random(100)\n self.y = np.sin(self.x)\n self.f = idw(self.x, self.y)\n\n @pytest.mark.parametrize('positions', [0.4, np.arange(2, 5)*0.1])\n def test_idw_1d(self, positions):\n f = idw(self.x, self.y)\n assert_allclose(f(positions), np.sin(positions), atol=1e-2)\n\n def test_idw_weights(self):\n weights = self.y * 0.1\n f = idw(self.x, self.y, weights=weights)\n pos = 0.4\n assert_allclose(f(pos), np.sin(pos), atol=1e-2)\n\n def test_idw_2d(self):\n pos = np.random.rand(1000, 2)\n val = np.sin(pos[:, 0] + pos[:, 1])\n f = idw(pos, val)\n x = 0.5\n y = 0.6\n assert_allclose(f([x, y]), np.sin(x + y), atol=1e-2)\n\n def test_idw_3d(self):\n val = np.ones((3, 3, 3))\n pos = np.indices(val.shape)\n f = idw(pos, val)\n assert_allclose(f([0.5, 0.5, 0.5]), 1.0)\n\n def test_no_coordinates(self):\n with pytest.raises(ValueError):\n idw([], 0)\n\n def test_values_invalid_shape(self):\n with pytest.raises(ValueError):\n idw(self.x, 0)\n\n def test_weights_invalid_shape(self):\n with pytest.raises(ValueError):\n idw(self.x, self.y, weights=10)\n\n def test_weights_negative(self):\n with pytest.raises(ValueError):\n idw(self.x, self.y, weights=-self.y)\n\n def test_n_neighbors_one(self):\n assert_allclose(self.f(0.5, n_neighbors=1), 0.48103656)\n\n def test_n_neighbors_negative(self):\n with pytest.raises(ValueError):\n self.f(0.5, n_neighbors=-1)\n\n def test_conf_dist_negative(self):\n assert_allclose(self.f(0.5, conf_dist=-1),\n self.f(0.5, conf_dist=None))\n\n def test_dtype_none(self):\n result = self.f(0.5, dtype=None)\n assert result.dtype.type == np.float64\n\n def test_positions_0d_nomatch(self):\n \"\"\"test when position ndim doesn't match coordinates ndim\"\"\"\n pos = np.random.rand(10, 2)\n val = np.sin(pos[:, 0] + pos[:, 1])\n f = idw(pos, val)\n with pytest.raises(ValueError):\n f(0.5)\n\n def test_positions_1d_nomatch(self):\n \"\"\"test when position ndim doesn't match coordinates ndim\"\"\"\n pos = np.random.rand(10, 2)\n val = np.sin(pos[:, 0] + pos[:, 1])\n f = idw(pos, val)\n with pytest.raises(ValueError):\n f([0.5])\n\n def test_positions_3d(self):\n with pytest.raises(ValueError):\n self.f(np.ones((3, 3, 3)))\n\n\nclass TestInterpolateMaskedData(object):\n def setup_class(cls):\n \"\"\"Ignore all deprecation warnings here.\"\"\"\n warnings.simplefilter('ignore', AstropyDeprecationWarning)\n\n def teardown_class(cls):\n warnings.resetwarnings()\n\n def test_mask_shape(self):\n with pytest.raises(ValueError):\n interpolate_masked_data(DATA, WRONG_SHAPE)\n\n def test_error_shape(self):\n with pytest.raises(ValueError):\n interpolate_masked_data(DATA, MASK, error=WRONG_SHAPE)\n\n def test_background_shape(self):\n with pytest.raises(ValueError):\n interpolate_masked_data(DATA, MASK, background=WRONG_SHAPE)\n\n def test_interpolation(self):\n data2 = DATA.copy()\n data2[2, 2] = 100.\n error2 = ERROR.copy()\n error2[2, 2] = 100.\n background2 = BACKGROUND.copy()\n background2[2, 2] = 100.\n data, error, background = interpolate_masked_data(\n data2, MASK, error=error2, background=background2)\n assert_allclose(data, DATA)\n assert_allclose(error, ERROR)\n assert_allclose(background, BACKGROUND)\n\n def test_interpolation_larger_mask(self):\n data2 = DATA.copy()\n data2[2, 2] = 100.\n error2 = ERROR.copy()\n error2[2, 2] = 100.\n background2 = BACKGROUND.copy()\n background2[2, 2] = 100.\n mask2 = MASK.copy()\n mask2[1:4, 1:4] = True\n data, error, background = interpolate_masked_data(\n data2, MASK, error=error2, background=background2)\n assert_allclose(data, DATA)\n assert_allclose(error, ERROR)\n assert_allclose(background, BACKGROUND)\n\n\nclass TestMaskToMirroredNum(object):\n def test_mask_to_mirrored_num(self):\n \"\"\"\n Test mask_to_mirrored_num.\n \"\"\"\n center = (1.5, 1.5)\n data = np.arange(16).reshape(4, 4)\n mask = np.zeros_like(data, dtype=bool)\n mask[0, 0] = True\n mask[1, 1] = True\n data_ref = data.copy()\n data_ref[0, 0] = data[3, 3]\n data_ref[1, 1] = data[2, 2]\n mirror_data = mask_to_mirrored_num(data, mask, center)\n assert_allclose(mirror_data, data_ref, rtol=0, atol=1.e-6)\n\n def test_mask_to_mirrored_num_range(self):\n \"\"\"\n Test mask_to_mirrored_num when mirrored pixels are outside of the\n image.\n \"\"\"\n center = (2.5, 2.5)\n data = np.arange(16).reshape(4, 4)\n mask = np.zeros_like(data, dtype=bool)\n mask[0, 0] = True\n mask[1, 1] = True\n data_ref = data.copy()\n data_ref[0, 0] = 0.\n data_ref[1, 1] = 0.\n mirror_data = mask_to_mirrored_num(data, mask, center)\n assert_allclose(mirror_data, data_ref, rtol=0, atol=1.e-6)\n\n def test_mask_to_mirrored_num_masked(self):\n \"\"\"\n Test mask_to_mirrored_num when mirrored pixels are also masked.\n \"\"\"\n center = (0.5, 0.5)\n data = np.arange(16).reshape(4, 4)\n data[0, 0] = 100\n mask = np.zeros_like(data, dtype=bool)\n mask[0, 0] = True\n mask[1, 1] = True\n data_ref = data.copy()\n data_ref[0, 0] = 0.\n data_ref[1, 1] = 0.\n mirror_data = mask_to_mirrored_num(data, mask, center)\n assert_allclose(mirror_data, data_ref, rtol=0, atol=1.e-6)\n\n def test_mask_to_mirrored_num_bbox(self):\n \"\"\"\n Test mask_to_mirrored_num with a bounding box.\n \"\"\"\n center = (1.5, 1.5)\n data = np.arange(16).reshape(4, 4)\n data[0, 0] = 100\n mask = np.zeros_like(data, dtype=bool)\n mask[0, 0] = True\n mask[1, 1] = True\n data_ref = data.copy()\n data_ref[1, 1] = data[2, 2]\n bbox = (1, 2, 1, 2)\n mirror_data = mask_to_mirrored_num(data, mask, center, bbox=bbox)\n assert_allclose(mirror_data, data_ref, rtol=0, atol=1.e-6)\n","sub_path":"photutils/utils/tests/test_interpolation.py","file_name":"test_interpolation.py","file_ext":"py","file_size_in_byte":7245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"21882567","text":"from unittest import mock\n\nimport numpy as np\nimport pytest\nimport tensorflow as tf\n\nfrom kerod.core import box_ops\nfrom kerod.dataset.augmentation import random_horizontal_flip\n\n\n@pytest.mark.parametrize(\"flip\", [True, False])\n@mock.patch('kerod.dataset.augmentation.tf.random.uniform', spec=True)\ndef test_random_horizontal_flip(mock, flip):\n # Above 0.5 perform a flip\n if flip:\n mock.return_value = 0.6\n else:\n mock.return_value = 0.3\n\n image = np.random.randn(3, 3, 3)\n\n boxes = tf.constant([[0.4, 0.3, 0.6, 0.6], [0.5, 0.6, 0.9, 0.65]])\n\n image_out, boxes_out = random_horizontal_flip(image, boxes)\n\n if flip:\n expected_boxes = np.array([[0.4, 0.4, 0.6, 0.7], [0.5, 0.35, 0.9, 0.4]], np.float32)\n image = tf.image.flip_left_right(image)\n else:\n expected_boxes = boxes\n\n np.testing.assert_allclose(boxes_out, expected_boxes)\n np.testing.assert_array_equal(image_out, image)\n","sub_path":"tests/dataset/test_augmentation.py","file_name":"test_augmentation.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"278528481","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.shortcuts import render\nfrom django.http import JsonResponse, HttpResponse\nimport docker\nimport os\nimport time\nimport re\nimport json\n\n\n# Create your views here.\ndef index(request):\n if request.method == 'GET':\n return render(request, '../templates/index.html')\n if request.method == 'POST':\n lang = request.POST['lang']\n code = request.POST['code']\n res = {'lang': lang, 'code': code, 'run': 'none'}\n return HttpResponse(\"Hello\")\n\n\n# @name = save_file\n# @Description: This function is used to generate temporary files like code, input and executable file\n# @Parameter:\n# - code : file content\n# - lang : file type, for example, '.c', '.txt', '.cpp', '.py'\n# - directory : absolute path of the directory where file is saved\n# - filename : filename to be generated, but PROBABLY NOT THE FINAL NAME of the file\n# due to existed name created by other user\n# @Return: filename : the final filename\n\n\ndef save_file(code, lang, directory, filename):\n path = directory + filename\n\n while os.path.exists(path+lang):\n time_suffix = str(time.time()).replace('.', '')\n path = path + time_suffix\n filename = filename + time_suffix\n\n path = path + lang\n filename = filename + lang\n\n file_handler = open(path, 'w', encoding='utf-8')\n file_handler.write(code)\n file_handler.close()\n return filename\n\n\ndef result(request):\n if request.method == 'POST':\n post_data = json.loads(request.body.decode())\n \n lang = post_data['lang']\n code = post_data['code']\n data_input = post_data['input']\n time_limit = post_data['time_limit']\n memory_limit = post_data['memory_limit']\n\n # TODO: Change the parameters as you want\n # RUN_DIR - directory in the host to save code as temporary file posted from web,\n # now the directory is set as current directory.\n # when you change the RUN_DIR, DO REMEMBER TO GIVE PERMISSION TO THE DIRECTORY\n # TIME_LIMIT - time limit for the program, unit (s)\n RUN_DIR = os.getcwd().replace('\\\\', '/') + '/.temp/'\n # replace aimed to change windows style into linux style\n TIME_LIMIT_C = str(int(time_limit) * 0.001) + 's'\n TIME_LIMIT_PY = str(int(time_limit) * 0.001) + 's'\n \n # dummy memory limit\n MEMORY_LIMIT = str(memory_limit) + 'KB'\n\n message_dict = {\n 0: 'Run Success',\n 1: 'Time Limit Exceed',\n 2: 'Compile Error',\n 3: 'Runtime Error',\n 4: 'System Error'\n }\n\n # create a docker container and bind current directory to the container\n try:\n client = docker.from_env()\n container = client.containers.run('ubuntugccpy:v2.0', '/bin/bash -c \"tail -f /dev/null\"', name=str(time.time()).replace('.', ''),\n detach=True, volumes={RUN_DIR: {'bind': '/home/code', 'mode': 'rw'}},\n )\n except RuntimeError:\n error_code = 4\n\n # filename is generated current time\n # For Example\n # >>> time.time()\n # 1596857839.850112\n # >>> '-' + str(time.time()).replace('.', '')\n # 1596857839850112\n code_filename = str(time.time()).replace('.', '')\n input_filename = code_filename + '_input'\n input_filename = save_file(data_input, '.txt', RUN_DIR, input_filename)\n\n if lang == 'c':\n code_filename = save_file(code, '.c', RUN_DIR, code_filename)\n exec_filename = code_filename[:-2]\n compile_command = 'gcc ' + code_filename + ' -o ' + exec_filename + ' -w'\n run_command = 'timeout ' + TIME_LIMIT_C + ' ./' + exec_filename + ' < ' + input_filename\n # compile with gcc\n exit_code, out = container.exec_run(compile_command)\n if exit_code == 0:\n os.remove(RUN_DIR + code_filename)\n exit_code, out = container.exec_run(run_command)\n if exit_code == 124:\n # Time Limit Exceed\n error_code = 1\n elif exit_code != 0:\n # Runtime Error\n error_code = 3\n else:\n # No problem\n error_code = 0\n output = out.decode()\n os.remove(RUN_DIR + exec_filename)\n else:\n # Compile Error\n error_code = 2\n print(out.decode())\n os.remove(RUN_DIR + code_filename)\n\n elif lang == 'cpp':\n code_filename = save_file(code, '.cpp', RUN_DIR, code_filename)\n exec_filename = code_filename[:-2]\n compile_command = 'g++ ' + code_filename + ' -o ' + exec_filename + ' -w'\n run_command = 'timeout ' + TIME_LIMIT_C + ' ./' + exec_filename + ' < ' + input_filename\n # compile with g++\n exit_code, out = container.exec_run(compile_command)\n if exit_code == 0:\n os.remove(RUN_DIR + code_filename)\n exit_code, out = container.exec_run(run_command)\n # TODO: 如何判断程序超时被停止\n if exit_code == 124:\n # Time Limit Exceed\n error_code = 1\n elif exit_code != 0:\n # Runtime Error\n error_code = 3\n else:\n # No problem\n error_code = 0\n output = out.decode()\n os.remove(RUN_DIR + exec_filename)\n else:\n os.remove(RUN_DIR + code_filename)\n # Compile Error\n error_code = 2\n\n else:\n code_filename = save_file(code, '.py', RUN_DIR, code_filename)\n run_command = 'timeout ' + TIME_LIMIT_PY + ' python3 ' + code_filename + ' < ' + input_filename\n exit_code, out = container.exec_run(run_command)\n out = out.decode()\n if exit_code == 0:\n # no problem\n error_code = 0\n output = out\n elif exit_code == 124:\n # Time Limit Exceed\n error_code = 1\n else:\n # Complie Error\n error_code = 2\n\n os.remove(RUN_DIR + code_filename)\n\n os.remove(RUN_DIR + input_filename)\n\n container.stop()\n container.remove()\n\n if error_code == 0:\n result = output\n else:\n result = 'Error'\n res = {'result': result, 'message': message_dict[error_code]}\n return JsonResponse(res)\n","sub_path":"Interface/myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"257773036","text":"ll = lambda:list(map(int, input().split()))\ntestcases = 1\n[testcases] = ll()\n\t# ll terms = n/m;\n # ll sum = (m%mod)*(((terms%mod)*(terms+1)%mod)%mod)%mod;\n # sum = (sum+n)%mod;\n # cout << sum << endl;\nfor _ in range(testcases):\n\t[n,m] = ll()\n\tterms = n//m\n\ts = m*terms*(terms+1)\n\ts+=n\n\tmod = 10**9+7\n\tprint(s%mod)\n\n","sub_path":"boy/program/py.py","file_name":"py.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"593607929","text":"import cgi\n\nimport webapp2\nfrom google.appengine.ext import webapp, db\nfrom google.appengine.ext.webapp import util, template\nfrom google.appengine.api import urlfetch, memcache, users, mail\nfrom google.appengine.ext import deferred\n\nimport logging, urllib, os, random\nfrom datetime import datetime, timedelta\n\nfrom models import Issue, Choice, Vote\n\n\nclass MainPage(webapp.RequestHandler):\n def get(self):\n user = users.get_current_user()\n if user:\n logout_url = users.create_logout_url('/')\n issues = Issue.all().order('-creation_date').filter('visibility',\"public\").fetch(30)\n success_type = self.request.get('success')\n success_msg = None\n if success_type == 'vote':\n success_msg = 'Your vote was successfully cast!'\n if success_type == 'updated':\n success_msg = 'Your vote was successfully updated!'\n #created_by = Issue.issues_created_by(member=user,limit=20)\n #voted_on = Issue.issues_voted_on(member=user,limit=20)\n #recent_results = [issue for issue in voted_on if issue.has_results]\n #recent_voted = [issue for issue in voted_on if issue.is_active()]\n #recent_results = Issue.recent_results(limit=20)\n self.response.out.write(template.render('templates/overview.html', locals()))\n else:\n self.redirect(users.create_login_url('/'))\n \n \nclass NewHandler(webapp.RequestHandler):\n def get(self):\n user = users.get_current_user()\n if user:\n logout_url = users.create_logout_url('/')\n else:\n self.redirect(users.create_login_url(self.request.uri))\n return\n option_one = \"Yes\"\n option_two = \"No\"\n self.response.out.write(template.render('templates/new.html', locals()))\n\n def post(self):\n user = users.get_current_user()\n if not user:\n self.redirect(users.create_login_url(self.request.uri))\n return\n \n duration_amount = int(self.request.get('duration_amount'))\n multiplier = int(self.request.get('duration_multiplier'))\n visibility = self.request.get('visibility')\n hashcode = random_string()\n title = cgi.escape(self.request.get('title'))\n description = cgi.escape(self.request.get('description'))\n\n if self.request.get('purchase'):\n title = \"Purchase: \"+cgi.escape(self.request.get('title'))\n description = \"\"+cgi.escape(self.request.get('url'))+\"
\"+ \\\n \"
Price: $\"+cgi.escape(self.request.get('price'))+\"
\"+ \\\n \"Qty: \"+cgi.escape(self.request.get('qty'))+\"
\"+ \\\n \"Total: $\"+cgi.escape(self.request.get('total'))+\"
\"+ \\\n \"
\"+cgi.escape(self.request.get('description'))\n\n issue = Issue(\n visibility = visibility,\n title = title,\n description = description,\n duration = duration_amount * multiplier,\n urlcode = hashcode)\n issue.put()\n if self.request.get('option1'):\n issue.add_choice(cgi.escape(self.request.get('option1')))\n if self.request.get('option2'):\n issue.add_choice(cgi.escape(self.request.get('option2')))\n if self.request.get('option3'):\n issue.add_choice(cgi.escape(self.request.get('option3')))\n if self.request.get('option4'):\n issue.add_choice(cgi.escape(self.request.get('option4')))\n if self.request.get('option5'):\n issue.add_choice(cgi.escape(self.request.get('option5')))\n\n if self.request.get('purchase'):\n details = cgi.escape(self.request.get('url'))+\"\\n\\n\"+ \\\n \"Price: $\"+cgi.escape(self.request.get('price'))+\"\\n\"+ \\\n \"Qty: \"+cgi.escape(self.request.get('qty'))+\"\\n\"+ \\\n \"Total: $\"+cgi.escape(self.request.get('total'))+\"\\n\\n\"+ \\\n cgi.escape(self.request.get('description'))\n notify_purchase(details,issue)\n k = issue.key()\n deferred.defer(later_results, k, _countdown=(duration_amount * multiplier*60*60)+30)\n\n self.redirect('/redirect/%s?success=new' % issue.urlcode)\n\nclass PurchaseHandler(webapp.RequestHandler):\n def get(self):\n user = users.get_current_user()\n if user:\n logout_url = users.create_logout_url('/')\n else:\n self.redirect(users.create_login_url(self.request.uri))\n return\n option_one = \"Yes, approve purchase\"\n option_two = \"No, do not approve purchase\"\n self.response.out.write(template.render('templates/purchase.html', locals()))\n\nclass EditHandler(webapp.RequestHandler):\n def get(self,urlcode):\n user = users.get_current_user()\n if user:\n logout_url = users.create_logout_url('/')\n else:\n self.redirect(users.create_login_url(self.request.uri))\n return\n issue = Issue.get_issue_by_urlcode(urlcode)\n choices = issue.choices\n self.response.out.write(template.render('templates/edit.html', locals()))\n\n def post(self,urlcode):\n user = users.get_current_user()\n if user:\n logout_url = users.create_logout_url('/')\n else:\n self.redirect(users.create_login_url(self.request.uri))\n return\n issue = Issue.get_issue_by_urlcode(urlcode)\n\n if self.request.get('extend'):#if extending vote\n choices = issue.choices\n extend_amount = int(self.request.get('extend_amount')) * int(self.request.get('extend_multiplier'))\n issue.extend_duration(extend_amount)\n self.redirect('/redirect/%s?success=extended' % issue.urlcode)\n \n else:#otherwise we are saving changes\n if issue.vote_count():\n raise Exception('Unable to change issue text once votes have been cast')\n\n duration_amount = int(self.request.get('duration_amount'))\n multiplier = int(self.request.get('duration_multiplier'))\n issue.duration = duration_amount * multiplier\n if self.request.get('title'):\n issue.title = cgi.escape(self.request.get('title'))\n if self.request.get('description'):\n issue.description = cgi.escape(self.request.get('description'))\n if self.request.get('option1') and self.request.get('option2'):\n choices = issue.choices\n db.delete(choices)\n issue.add_choice(cgi.escape(self.request.get('option1')))\n issue.add_choice(cgi.escape(self.request.get('option2')))\n if self.request.get('option3'):\n issue.add_choice(cgi.escape(self.request.get('option3')))\n if self.request.get('option4'):\n issue.add_choice(cgi.escape(self.request.get('option4')))\n if self.request.get('option5'):\n issue.add_choice(cgi.escape(self.request.get('option5')))\n issue.put()\n #choices = issue.choices\n self.redirect('/redirect/%s' % issue.urlcode)\n #self.response.out.write(template.render('templates/edit.html', locals()))\n \n\nclass RedirectHandler(webapp.RequestHandler):\n def get(self,issueurl):\n success_type = self.request.get('success')\n success_msg = None\n if success_type == 'extended':\n success_msg = 'Poll duration has been extended!'\n if success_type == 'new':\n success_msg = 'Your poll has been created!'\n if success_type == 'voted':\n success_msg = 'Your vote was successfully cast!'\n if success_type == 'updated':\n success_msg = 'Your vote was successfully updated!'\n user = users.get_current_user()\n host = os.environ['HTTP_HOST']\n self.response.out.write(template.render('templates/redirect.html', locals()))\n\n#class ResultHandler(webapp.RequestHandler):\n# def get(self,urlcode):\n# issue = Issue.get_issue_by_urlcode(urlcode)\n# issue.update_status()\n# yes = 0\n# no = 0\n# for choice in issue.choices:\n# if \"Yes\" in choice.name:\n# yes = choice.vote_count()\n# if \"No\" in choice.name:\n# no = choice.vote_count()\n#\n# passed = \"Not approved\"\n# if yes > no:\n# passed = \"Purchase Approved\"\n#\n# issueUrl = self.request.uri\n# self.response.out.write(\" Status=\"+str(issue.status))\n# self.response.out.write(\" Yes=\"+str(yes))\n# self.response.out.write(\" No=\"+str(no))\n# self.response.out.write(\" Passed=\"+str(passed))\n# if \"done\" in issue.status:\n# notify_results(passed,yes,no,issue)\n \nclass IssueHandler(webapp.RequestHandler):\n def get(self,urlcode):\n user = users.get_current_user()\n if user:\n logout_url = users.create_logout_url('/')\n else:\n self.redirect(users.create_login_url(self.request.uri))\n return\n \n issue = Issue.get_issue_by_urlcode(urlcode)\n issue.update_status()\n \n #vote = issue.vote_for_member(user)\n\n issueUrl = self.request.uri\n self.response.out.write(template.render('templates/issue.html', locals()))\n \n \n def post(self,urlcode):\n user = users.get_current_user()\n if user:\n logout_url = users.create_logout_url('/')\n else:\n self.redirect(users.create_login_url(self.request.uri))\n \n issue = Issue.get_issue_by_urlcode(urlcode)\n #vote = issue.vote_for_member()\n \n new_choice = Choice.get_by_id(int(self.request.get('choice')))\n was_updated = issue.register_vote(new_choice)\n self.response.out.write(template.render('templates/issue.html', locals()))\n if was_updated:\n self.redirect('/redirect/%s?success=updated' % issue.urlcode)\n else:\n self.redirect('/redirect/%s?success=voted' % issue.urlcode)\n\n\ndef later_results(k):\n issue = Issue.get(k)\n issue.update_status()\n yes = 0\n no = 0\n for choice in issue.choices:\n if \"Yes\" in choice.name:\n yes = choice.vote_count()\n if \"No\" in choice.name:\n no = choice.vote_count()\n\n passed = \"Not approved\"\n if yes > no:\n passed = \"Purchase Approved\"\n\n notify_results(passed,yes,no,issue)\n\n\ndef notify_results(passed,yes,no,issue):\n body = \"\"\"\nVoting Results: %s\n\nYes: %s votes\nNo: %s votes\n\nhttps://%s/issue/%s\n\n\"\"\" % (\n passed,\n yes,\n no,\n os.environ.get('HTTP_HOST'),\n issue.urlcode)\n\n deferred.defer(mail.send_mail, sender='Voting Robot ', to=\"government@hackerdojo.com\", cc=issue.creator.nickname()+\"@hackerdojo.com\",\n subject=issue.title,\n body=body, _queue=\"emailthrottle\")\n \ndef notify_purchase(details,issue):\n user = users.get_current_user()\n body = \"\"\"\n%s has proposed the following purchase request. \n\n********************************************************************\n\n%s\n%s\n\n********************************************************************\n\nVOTING LINK: https://%s/issue/%s\n\n********************************************************************\n\nOr, discuss the issue on this thread. Any modifications will\nrequire a new purchase proposal.\n\nhttps://vote.hackerdojo.com/purchase\n\n\"\"\" % (\n user.nickname(),\n issue.title, \n details,\n os.environ.get('HTTP_HOST'),\n issue.urlcode)\n\n deferred.defer(mail.send_mail, sender='Voting Robot ', to=\"government@hackerdojo.com\", cc=user.nickname()+\"@hackerdojo.com\",\n subject=issue.title,\n body=body, _queue=\"emailthrottle\")\n\ndef random_string():\n hashbase = '1234567890abcdefghijklmnopqrstuvwxyz'\n return ''.join(random.sample(hashbase,len(hashbase)))\n\napp = webapp2.WSGIApplication([\n ('/',MainPage),\n ('/new',NewHandler),\n ('/purchase',PurchaseHandler),\n ('/redirect/(\\w+).*',RedirectHandler),\n ('/issue/(\\w+).*',IssueHandler),\n# ('/result/(\\w+).*',ResultHandler),\n ('/edit/(\\w+).*',EditHandler)],\n debug=True)\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"644152412","text":"from selenium import webdriver\nimport time\nimport os\n\ncurrent_dir = os.path.abspath(os.path.dirname(__file__)) # получаем путь к директории текущего исполняемого ф��йла \nfile_path = os.path.join(current_dir, 'bio.txt') # добавляем к этому пути имя файла \n\ntry: \n link = \"http://suninjuly.github.io/file_input.html\"\n browser = webdriver.Chrome()\n browser.get(link)\n\n input = browser.find_element_by_css_selector(\"[placeholder='Enter first name']\")\n input.send_keys(\"Vasily\") \n \n input = browser.find_element_by_css_selector(\"[placeholder='Enter last name']\")\n input.send_keys(\"Pupkin\") \n\n input = browser.find_element_by_css_selector(\"[placeholder='Enter email']\")\n input.send_keys(\"vasily.pupkin@mail.ru\") \n\n input = browser.find_element_by_css_selector(\"#file\")\n input.send_keys(file_path) \n \n button = browser.find_element_by_tag_name(\"button\")\n browser.execute_script(\"return arguments[0].scrollIntoView(true);\", button)\n button.click()\n \nfinally:\n # ожидание чтобы визуально оценить результаты прохождения скрипта\n time.sleep(10)\n # закрываем браузер после всех манипуляций\n browser.quit()","sub_path":"lesson2step8.py","file_name":"lesson2step8.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"575662572","text":"import ipaddress\nimport sys\n\n\ndef subnetCalculator(requiredIP):\n\n try:\n ip = ipaddress.IPv4Network(requiredIP, strict=False)\n initial = int(str(ip).split('.')[0])\n ipclass = ''\n\n if initial == 0:\n return print('This is the source IP')\n elif initial >= 1 and initial <= 126:\n ipclass = \"CLASS A - IP range 1-126\"\n elif initial == 127:\n return print('This is a Loopback Address range')\n elif initial >= 126 and initial <= 191:\n ipclass = \"CLASS B - IP range 128-191\"\n elif initial >= 192 and initial <= 223:\n ipclass = \"CLASS C - IP range 192-223\"\n elif initial >= 224 and initial <= 239:\n return print('Class D - Multicast Address range')\n else:\n return print('Class E - Experimental Address range')\n except ipaddress.AddressValueError:\n return print('This is not a valid IP address')\n except ipaddress.NetmaskValueError:\n return print('Invalid Subnet mask')\n\n\n if ip.is_private:\n print('This is a private range')\n\n print('The Network ID is {}'.format(ip.with_netmask))\n print('The First IP assignable for an host is {}'.format(ip.network_address + 1))\n print('The Last IP assignable fo an host is {}'.format(ip.broadcast_address - 1))\n print('The Broadcast address is {}'.format(ip.broadcast_address))\n print('The Number of Assignable IP is {}'.format(ip.num_addresses))\n\ndef main():\n subnetCalculator('196.128.4.6/24')\n\nif __name__ == ('__main__'):\n main()","sub_path":"subnet.py","file_name":"subnet.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"312676334","text":"from scrapy.spider import BaseSpider\nfrom scrapy.selector import HtmlXPathSelector\n\nfrom chinadaily.items import WebsiteLoader\n\n\nclass DmozSpider(BaseSpider):\n download_delay = 0.2\n name = \"dmoz\"\n allowed_domains = [\"searchen.chinadaily.com.cn\"]\n start_urls = [\n \"http://searchen.chinadaily.com.cn/search?sortBy=-publishtime&view=allsitesppublished&classify=en&navigation=&drillDown=&drillUp=&query=weibo&offset=%d\" % n for n in range(1,1643)\n ]\n\n\n def parse(self, response):\n \"\"\"\n The lines below is a spider contract. For more info see:\n http://doc.scrapy.org/en/latest/topics/contracts.html\n\n @url http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/\n @scrapes name\n \"\"\"\n hxs = HtmlXPathSelector(response)\n sites = hxs.select('//ul[@class=\"cs_sear_list\"]/li')\n\n for site in sites:\n il = WebsiteLoader(response=response, selector=site)\n il.add_xpath('title', 'div[@class=\"cs_sear_list_tit\"]/a/text()')\n il.add_xpath('source', 'div[@class=\"cs_sear_list_con\"]/div/span[@class=\"source\"]/text()')\n il.add_xpath('time', 'div[@class=\"cs_sear_list_con\"]/div/span[@class=\"time\"]/text()')\n il.add_xpath('content', 'div[@class=\"cs_sear_list_con\"]/p')\n yield il.load_item()\n","sub_path":"scrapy/chinadaily-mysql/chinadaily/spiders/dmoz.py","file_name":"dmoz.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"498091572","text":"import random\nimport copy\nfrom optparse import OptionParser\nimport util\n\nclass SolveEightQueens:\n def __init__(self, numberOfRuns, verbose, lectureExample):\n \"\"\"\n Value 1 indicates the position of queen\n \"\"\"\n self.numberOfRuns = numberOfRuns\n self.verbose = verbose\n self.lectureCase = [[]]\n if lectureExample:\n self.lectureCase = [\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0, 0],\n [1, 0, 0, 0, 1, 0, 0, 0],\n [0, 1, 0, 0, 0, 1, 0, 1],\n [0, 0, 1, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n ]\n def solve(self):\n solutionCounter = 0\n for i in range(self.numberOfRuns):\n if self.search(Board(self.lectureCase), self.verbose).getNumberOfAttacks() == 0:\n solutionCounter += 1\n print(\"Solved: %d/%d\" % (solutionCounter, self.numberOfRuns))\n\n def search(self, board, verbose):\n \"\"\"\n Hint: Modify the stop criterion in this function\n \"\"\"\n newBoard = board\n i = 0 \n while True:\n if verbose:\n print(\"iteration %d\" % i)\n print(newBoard.toString())\n print(\"# attacks: %s\" % str(newBoard.getNumberOfAttacks()))\n print(newBoard.getCostBoard().toString(True))\n currentNumberOfAttacks = newBoard.getNumberOfAttacks()\n (newBoard, newNumberOfAttacks, newRow, newCol) = newBoard.getBetterBoard()\n i += 1\n if(newNumberOfAttacks == 0):\n break\n if(i > 100):\n if currentNumberOfAttacks <= newNumberOfAttacks:\n break\n return newBoard\n\nclass Board:\n def __init__(self, squareArray = [[]]):\n if squareArray == [[]]:\n self.squareArray = self.initBoardWithRandomQueens()\n else:\n self.squareArray = squareArray\n\n @staticmethod\n def initBoardWithRandomQueens():\n tmpSquareArray = [[ 0 for i in range(8)] for j in range(8)]\n for i in range(8):\n tmpSquareArray[random.randint(0,7)][i] = 1\n return tmpSquareArray\n \n def toString(self, isCostBoard=False):\n \"\"\"\n Transform the Array in Board or cost Board to printable string\n \"\"\"\n s = \"\"\n for i in range(8):\n for j in range(8):\n if isCostBoard: # Cost board\n cost = self.squareArray[i][j]\n s = (s + \"%3d\" % cost) if cost < 9999 else (s + \" q\")\n else: # Board\n s = (s + \". \") if self.squareArray[i][j] == 0 else (s + \"q \")\n s += \"\\n\"\n return s \n\n def getCostBoard(self):\n \"\"\"\n First Initalize all the cost as 9999. \n After filling, the position with 9999 cost indicating the position of queen.\n \"\"\"\n costBoard = Board([[ 9999 for i in range(8)] for j in range(8)])\n for r in range(8):\n for c in range(8):\n if self.squareArray[r][c] == 1:\n for rr in range(8):\n if rr != r:\n testboard = copy.deepcopy(self)\n testboard.squareArray[r][c] = 0\n testboard.squareArray[rr][c] = 1\n costBoard.squareArray[rr][c] = testboard.getNumberOfAttacks()\n return costBoard\n\n def getBetterBoard(self):\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n This function should return a tuple containing containing four values\n the new Board object, the new number of attacks, \n the Column and Row of the new queen \n For exmaple: \n return (betterBoard, minNumOfAttack, newRow, newCol)\n The datatype of minNumOfAttack, newRow and newCol should be int\n \"\"\"\n\n noAttacks=self.getNumberOfAttacks()\n newAttack=[]\n\n if noAttacks==0:\n return (self,noAttacks,0,0)\n else:\n for i in range(0,8):\n for j in range(0,8):\n newAttack.append(self.getCostBoard().squareArray[i][j])\n minNumOfAttack=min(newAttack)\n newList=[]\n for i in range(0,8):\n for j in range(0,8):\n if self.getCostBoard().squareArray[i][j]==minNumOfAttack:\n newList.append((i,j))\n newrow,newcol=random.choice(newList)\n for k in range(0,8):\n if self.squareArray[k][newcol]==1:\n oldrow=k\n betterboard=copy.deepcopy(self)\n betterboard.squareArray[newrow][newcol]=1\n betterboard.squareArray[oldrow][newcol]=0\n return (betterboard,minNumOfAttack,newrow,newcol)\n\n def getNumberOfAttacks(self):\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n This function should return the number of attacks of the current board\n The datatype of the return value should be int\n \"\"\"\n counter = 0\n for i in range(8):\n temp_row = temp_diag = temp_diag2 = row_queens = 0\n for j in range(8):\n if(self.squareArray[i][j] == 1):\n row_queens = row_queens + 1\n if(row_queens > 1):\n temp_row = temp_row + (row_queens-1)\n diag_queens1 = 0\n for k in range(max(i,j), 8):\n if(i>=j):\n y = j + k - i\n x = k\n else:\n y = k\n x = i + k - j\n if(self.squareArray[x][y] == 1):\n diag_queens1 = diag_queens1 + 1\n if(diag_queens1 > 1):\n temp_diag = temp_diag + 1\n diag_queens2 = 0\n if((i+j)<7):\n temp = i\n for k in range(i, -1, -1):\n y = j + i - k\n x = k\n if(y <= 7 and self.squareArray[x][y] == 1):\n diag_queens2 = diag_queens2 + 1\n if(diag_queens2 > 1):\n temp_diag2 = temp_diag2 + 1\n counter = counter + temp_row + temp_diag + temp_diag2\n return(counter)\n\nif __name__ == \"__main__\":\n #Enable the following line to generate the same random numbers (useful for debugging)\n random.seed(1)\n parser = OptionParser()\n parser.add_option(\"-q\", dest=\"verbose\", action=\"store_false\", default=True)\n parser.add_option(\"-l\", dest=\"lectureExample\", action=\"store_true\", default=False)\n parser.add_option(\"-n\", dest=\"numberOfRuns\", default=1, type=\"int\")\n (options, args) = parser.parse_args()\n EightQueensAgent = SolveEightQueens(verbose=options.verbose, numberOfRuns=options.numberOfRuns, lectureExample=options.lectureExample)\n EightQueensAgent.solve()\n","sub_path":"Assignment 1/solveEightQueens.py","file_name":"solveEightQueens.py","file_ext":"py","file_size_in_byte":7144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"196281664","text":"from .notegroups import _NoteGroup, InvalidDegreeError\n\n\nclass Chord(_NoteGroup):\n def __init__(self, qualified_name):\n \"\"\"\n MAJOR, MINOR, DIMINISHED, and AUGMENTED qualities are triads. Anything with a\n number (e.g. MAJOR 7) produces a four-or-more-note chord.\n \"\"\"\n super().__init__('CHORD', qualified_name)\n\n def __getitem__(self, element):\n degree_names = {'BASS': 0, 'THIRD': 1, 'FIFTH': 2, 'SEVENTH': 3, 'NINTH': 4, 'ELEVENTH': 5, 'THIRTEENTH': 6}\n try:\n element = element.upper()\n chord_degree = degree_names[element]\n return self.notes[chord_degree]\n except IndexError:\n return None\n except KeyError:\n raise InvalidDegreeError(\"Invalid degree name: %s\" % element) from None\n\n def _validate_root(self, unpacked_name):\n valid_roots = ['A', 'B', 'C', 'D', 'E', 'F', 'G']\n valid_qualifiers = ['', '#', '##', 'b', 'bb']\n valid_qualified_roots = [root + qualifier for root in valid_roots for qualifier in valid_qualifiers]\n if unpacked_name['ROOT'] not in valid_qualified_roots:\n raise InvalidBassError(\"Invalid bass note: %s\" % unpacked_name['ROOT'])\n\n\nclass InvalidBassError(Exception):\n pass\n","sub_path":"musictheorpy/chords.py","file_name":"chords.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"140304965","text":"from __future__ import division\nimport math\nimport time\nimport tqdm\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torchvision.ops import boxes as box_ops\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n\n\ndef to_cpu(tensor):\n return tensor.detach().cpu()\n\n\ndef load_classes(path):\n \"\"\"\n Loads class labels at 'path'\n \"\"\"\n fp = open(path, \"r\")\n names = fp.read().split(\"\\n\")[:-1]\n return names\n\n\ndef weights_init_normal(m):\n classname = m.__class__.__name__\n if classname.find(\"Conv\") != -1:\n torch.nn.init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find(\"BatchNorm2d\") != -1:\n torch.nn.init.normal_(m.weight.data, 1.0, 0.02)\n torch.nn.init.constant_(m.bias.data, 0.0)\n elif classname.find(\"Linear\") != -1:\n nn.init.kaiming_normal_(m.weight.data)\n # print(m.__class__)\n\n\ndef rescale_boxes(boxes, current_dim, original_shape):\n \"\"\" Rescales bounding boxes to the original shape \"\"\"\n orig_h, orig_w = original_shape\n # The amount of padding that was added\n pad_x = max(orig_h - orig_w, 0) * (current_dim / max(original_shape))\n pad_y = max(orig_w - orig_h, 0) * (current_dim / max(original_shape))\n # Image height and width after padding is removed\n unpad_h = current_dim - pad_y\n unpad_w = current_dim - pad_x\n # Rescale bounding boxes to dimension of original image\n boxes[:, 0] = ((boxes[:, 0] - pad_x // 2) / unpad_w) * orig_w\n boxes[:, 1] = ((boxes[:, 1] - pad_y // 2) / unpad_h) * orig_h\n boxes[:, 2] = ((boxes[:, 2] - pad_x // 2) / unpad_w) * orig_w\n boxes[:, 3] = ((boxes[:, 3] - pad_y // 2) / unpad_h) * orig_h\n return boxes\n\n\ndef xyxy2xywh(x):\n # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right\n y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)\n y[..., 0] = (x[..., 0] + x[..., 2]) / 2 # x center\n y[..., 1] = (x[..., 1] + x[..., 3]) / 2 # y center\n y[..., 2] = x[..., 2] - x[..., 0] # width\n y[..., 3] = x[..., 3] - x[..., 1] # height\n return y \n\n\ndef xywh2xyxy(x):\n y = x.new(x.shape)\n y[..., 0] = x[..., 0] - x[..., 2] / 2\n y[..., 1] = x[..., 1] - x[..., 3] / 2\n y[..., 2] = x[..., 0] + x[..., 2] / 2\n y[..., 3] = x[..., 1] + x[..., 3] / 2\n return y\n\n\ndef ap_per_class(tp, conf, pred_cls, target_cls):\n \"\"\" Compute the average precision, given the recall and precision curves. \n Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. \n\n # Arguments \n tp: True positives (list), e.g. array([0., 1., 1.]), 3 predicted bboxs\n conf: Objectness value from 0-1 (list), e.g. tensor([0.8247, 0.3907, 0.6466]) \n pred_cls: Predicted object classes (list), e.g. tensor([1., 0., 18.]) \n target_cls: True object classes (list), e.g. tensor([1., 2., 18.]) \n # Returns \n The average precision as computed in py-faster-rcnn.\n \"\"\"\n\n # Sort by objectness\n i = np.argsort(-conf)\n tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]\n\n # Find unique classes\n unique_classes = np.unique(target_cls)\n\n # Create Precision-Recall curve and compute AP for each class\n ap, p, r = [], [], []\n for c in tqdm.tqdm(unique_classes, desc=\"Computing AP\"):\n i = (pred_cls == c) # only keep class c for predicted bboxs\n n_p = i.sum() # Number of predicted objects\n n_gt = (target_cls == c).sum() # Number of ground truth objects\n\n if n_p == 0 and n_gt == 0:\n continue\n elif n_p == 0 or n_gt == 0:\n ap.append(0)\n r.append(0)\n p.append(0)\n else:\n # Accumulate FPs and TPs\n fpc = (1 - tp[i]).cumsum()\n tpc = (tp[i]).cumsum()\n\n # Recall\n recall_curve = tpc / (n_gt + 1e-16)\n r.append(recall_curve[-1])\n\n # Precision\n precision_curve = tpc / (tpc + fpc)\n p.append(precision_curve[-1])\n\n # AP from recall-precision curve\n ap.append(compute_ap(recall_curve, precision_curve))\n\n # Compute F1 score (harmonic mean of precision and recall)\n p, r, ap = np.array(p), np.array(r), np.array(ap)\n f1 = 2 * p * r / (p + r + 1e-16)\n\n\n # pr-curve for all classes added together\n filtering = []\n for i in range(len(tp)):\n if pred_cls[i] in unique_classes:\n filtering.append(True)\n else:\n filtering.append(False)\n tp, pred_cls = tp[filtering], pred_cls[filtering]\n\n n_p = len(tp) \n n_gt = len(target_cls)\n\n if n_p == 0 or n_gt == 0:\n precision_curve, recall_curve = 0, 0\n else:\n # Accumulate FPs and TPs\n fpc = (1 - tp).cumsum()\n tpc = (tp).cumsum()\n\n # Recall and Precision\n recall_curve = tpc / (n_gt + 1e-16)\n precision_curve = tpc / (tpc + fpc)\n\n return p, r, ap, f1, unique_classes.astype(\"int32\"), (precision_curve,recall_curve)\n\n\ndef compute_ap(recall, precision):\n \"\"\" Compute the average precision, given the recall and precision curves.\n Code originally from https://github.com/rbgirshick/py-faster-rcnn.\n\n # Arguments\n recall: The recall curve (list).\n precision: The precision curve (list).\n # Returns\n The average precision as computed in py-faster-rcnn.\n \"\"\"\n # correct AP calculation\n # first append sentinel values at the end\n mrec = np.concatenate(([0.0], recall, [1.0]))\n mpre = np.concatenate(([0.0], precision, [0.0]))\n\n # compute the precision envelope\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (\\Delta recall) * prec\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n\ndef get_batch_statistics(outputs, targets, iou_threshold):\n \"\"\" \n Compute true positives, predicted scores and predicted labels per sample \n \n Argus:\n ---\n -outputs: list[tensor[n, 7]], len(outputs) = batch_size\n [x1, y1, x2, y2, obj_conf, obj_score, class_pred] \n (x1, y1, x2, y2) is scaled to img_size \n\n -targets: tensor with size (m, 6) \n [image_i, class, x_center, y_center, w, h] \n (x_center, y_center, w, h) is scaled to img_size\n \"\"\"\n batch_metrics = []\n \n # iter for each image, image_i is the idx of the image in a batch\n for image_i in range(len(outputs)):\n\n if outputs[image_i] is None:\n continue\n\n output = outputs[image_i]\n pred_boxes = output[:, :4]\n pred_scores = output[:, 4]\n pred_labels = output[:, -1]\n\n true_positives = np.zeros(pred_boxes.shape[0])\n\n annotations = targets[targets[:, 0] == image_i][:, 1:] # filter for image_i\n target_labels = annotations[:, 0] if len(annotations) else []\n if len(annotations):\n detected_boxes = []\n target_boxes = annotations[:, 1:]\n\n # iter for every detected box\n for pred_i, (pred_box, pred_label) in enumerate(zip(pred_boxes, pred_labels)):\n\n # If all targets are found, break\n if len(detected_boxes) == len(annotations):\n break\n\n # Ignore if label is not one of the target labels\n if pred_label not in target_labels:\n continue\n \n iou, box_index = bbox_iou(pred_box.unsqueeze(0), target_boxes).max(0)\n if iou >= iou_threshold and box_index not in detected_boxes:# and pred_label==target_labels[box_index]:\n true_positives[pred_i] = 1\n detected_boxes += [box_index]\n batch_metrics.append([true_positives, pred_scores, pred_labels])\n return batch_metrics\n\n\ndef bbox_wh_iou(wh1, wh2):\n wh2 = wh2.t()\n w1, h1 = wh1[0], wh1[1]\n w2, h2 = wh2[0], wh2[1]\n inter_area = torch.min(w1, w2) * torch.min(h1, h2)\n union_area = (w1 * h1 + 1e-16) + w2 * h2 - inter_area\n return inter_area / union_area\n\n\ndef bbox_iou(box1, box2, x1y1x2y2=True):\n \"\"\"\n Returns the IoU of box1 (shape 1*4) with several box2 (shape n*4)\n \"\"\"\n if not x1y1x2y2:\n # Transform from center and width to exact coordinates\n b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2\n b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2\n b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2\n b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2\n else:\n # Get the coordinates of bounding boxes\n b1_x1, b1_y1, b1_x2, b1_y2 = box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3]\n b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3]\n\n # get the corrdinates of the intersection rectangle\n inter_rect_x1 = torch.max(b1_x1, b2_x1) # broadcast here\n inter_rect_y1 = torch.max(b1_y1, b2_y1)\n inter_rect_x2 = torch.min(b1_x2, b2_x2)\n inter_rect_y2 = torch.min(b1_y2, b2_y2)\n # Intersection area\n inter_area = torch.clamp(inter_rect_x2 - inter_rect_x1 + 1, min=0) * torch.clamp(\n inter_rect_y2 - inter_rect_y1 + 1, min=0\n )\n # Union Area\n b1_area = (b1_x2 - b1_x1 + 1) * (b1_y2 - b1_y1 + 1)\n b2_area = (b2_x2 - b2_x1 + 1) * (b2_y2 - b2_y1 + 1)\n\n iou = inter_area / (b1_area + b2_area - inter_area + 1e-16)\n\n return iou\n\n\ndef non_max_suppression(prediction, conf_thresh=0.01, nms_thresh=0.5):\n \"\"\"\n CPU single-process version of NMS\n Removes detections with lower object confidence score than 'conf_thresh' and \n performs Non-Maximum Suppression to further filter detections. \n\n Parameters\n ---\n prediction: take yolov3 tiny for example, it is a tensor(batch_size, 2535, 85)\n\n Returns\n ---\n list[tensor(n, 7)], where n is the number of bboxes after NMS in an image\n 7 for (x1, y1, x2, y2, object_conf, class_score, class_pred)\n Here (x1, y1, x2, y2) is scale to image size\n \"\"\"\n\n # From (center x, center y, width, height) to (x1, y1, x2, y2)\n prediction[..., :4] = xywh2xyxy(prediction[..., :4])\n output = [None for _ in range(len(prediction))]\n\n for image_i, image_pred in enumerate(prediction):\n # Filter out confidence scores below threshold\n image_pred = image_pred[image_pred[:, 4] >= conf_thresh]\n # If none are remaining => process next image\n if not image_pred.size(0):\n continue\n\n # Object confidence times class confidence\n score = image_pred[:, 4] # *image_pred[:, 5:].max(1)[0] is optional: could drop mAP ~0.1\n # Sort by it\n image_pred = image_pred[(-score).argsort()]\n class_confs, class_preds = image_pred[:, 5:].max(1, keepdim=True)\n detections = torch.cat((image_pred[:, :5], class_confs.float(), class_preds.float()), 1)\n \n # Perform non-maximum suppression\n keep_boxes = []\n while detections.size(0):\n # detections[0, :4] is the bbox with highest score\n large_overlap = bbox_iou(detections[0, :4].unsqueeze(0), detections[:, :4]) > nms_thresh\n label_match = detections[0, -1] == detections[:, -1]\n invalid = large_overlap & label_match\n\n # Merge overlapping bboxes by order of confidence: could increase mAP ~0.4\n # weights = detections[invalid, 4:5]\n # detections[0, :4] = (weights * detections[invalid, :4]).sum(0) / weights.sum()\n \n # filter boxes\n keep_boxes += [detections[0]]\n detections = detections[~invalid]\n if keep_boxes:\n output[image_i] = torch.stack(keep_boxes)\n\n return output\n\n\ndef non_max_suppression_cpp(prediction, conf_thresh, nms_thresh=0.5, detections_per_img=200):\n \"\"\"\n This function can run on both CPU and GPU, depending on the prediction.device \n Removes detections with lower object confidence score than 'conf_thresh' and performs\n Non-Maximum Suppression to further filter detections. \n\n Parameters\n ---\n prediction: take yolov3-tiny (COCO) for example, it is a tensor(batch_size, 2535, 85)\n\n Returns\n ---\n list[tensor(n, 7+c)], where n is the number of bboxes after NMS in an image\n 7+c for (x1, y1, x2, y2, object_conf, class_score, class_pred, scores_of_c_classes)\n Here (x1, y1, x2, y2) is scale to image size\n \"\"\"\n # From (center x, center y, width, height) to (x1, y1, x2, y2)\n prediction[..., :4] = xywh2xyxy(prediction[..., :4])\n output = [None for _ in range(len(prediction))]\n\n for image_i, image_pred in enumerate(prediction):\n # Filter out low confidence boxes\n image_pred = image_pred[image_pred[:, 4] >= conf_thresh]\n # If none are remaining => process next image\n if not image_pred.size(0):\n continue\n \n # obtain class of each bbox\n class_confs, class_preds = image_pred[:, 5:].max(1, keepdim=True)\n detections = torch.cat((image_pred[:, :5], class_confs.float(), class_preds.float(), image_pred[:, 5:]), 1)\n\n boxes = detections[:, :4] # tensor[n,4]\n scores = detections[:, 4] # tensor[n], detections[:, 4]*class_confs.squeeze() is optional: could drop mAP ~0.1\n labels = detections[:, 6] # tensor[n]\n\n keep = box_ops.batched_nms(boxes, scores, labels, nms_thresh)\n keep = keep[:detections_per_img]\n\n if len(keep) > 0:\n output[image_i] = detections[keep]\n\n return output\n\n\ndef build_targets(pred_boxes, pred_cls, target, anchors, ignore_thres):\n \"\"\" \n pred_boxes: shape (batch_size, num_anchors, num_grids, num_grids, 4), e.g. (32,3,13,13,4) \n pred_cls: shape (batch_size, num_anchors, num_grids, num_grids, num_classes), e.g.(32,3,13,13,12) \n target: shape (num_bboxes_in_a_batch, 6) \n anchors: e.g. tensor([[ 2.5312, 2.5625], [4.2188, 5.2812], [10.7500, 9.9688]], device='cuda:0')\n \"\"\"\n ByteTensor = torch.cuda.ByteTensor if pred_boxes.is_cuda else torch.ByteTensor\n FloatTensor = torch.cuda.FloatTensor if pred_boxes.is_cuda else torch.FloatTensor\n\n nB = pred_boxes.size(0) # batch size\n nA = pred_boxes.size(1) # num of anchors in a grid, 3 in yolo-tiny\n nC = pred_cls.size(-1) # number of classes\n nG = pred_boxes.size(2) # number of grids\n\n # Output tensors\n obj_mask = ByteTensor(nB, nA, nG, nG).fill_(0)\n noobj_mask = ByteTensor(nB, nA, nG, nG).fill_(1)\n class_mask = FloatTensor(nB, nA, nG, nG).fill_(0)\n iou_scores = FloatTensor(nB, nA, nG, nG).fill_(0)\n tx = FloatTensor(nB, nA, nG, nG).fill_(0)\n ty = FloatTensor(nB, nA, nG, nG).fill_(0)\n tw = FloatTensor(nB, nA, nG, nG).fill_(0)\n th = FloatTensor(nB, nA, nG, nG).fill_(0)\n tcls = FloatTensor(nB, nA, nG, nG, nC).fill_(0)\n\n # Convert to position relative to box\n target_boxes = target[:, 2:6] * nG\n gxy = target_boxes[:, :2]\n gwh = target_boxes[:, 2:]\n # Get anchors with best iou, here it only chooses the shape of anchor\n ious = torch.stack([bbox_wh_iou(anchor, gwh) for anchor in anchors])\n best_ious, best_n = ious.max(0)\n # Separate target values\n b, target_labels = target[:, :2].long().t()\n gx, gy = gxy.t()\n gw, gh = gwh.t()\n gi, gj = gxy.long().t()\n # Set masks\n obj_mask[b, best_n, gj, gi] = 1\n noobj_mask[b, best_n, gj, gi] = 0\n\n # Set noobj mask to zero where iou exceeds ignore threshold\n for i, anchor_ious in enumerate(ious.t()):\n noobj_mask[b[i], anchor_ious > ignore_thres, gj[i], gi[i]] = 0\n\n # Coordinates\n tx[b, best_n, gj, gi] = gx - gx.floor()\n ty[b, best_n, gj, gi] = gy - gy.floor()\n # Width and height\n tw[b, best_n, gj, gi] = torch.log(gw / anchors[best_n][:, 0] + 1e-16)\n th[b, best_n, gj, gi] = torch.log(gh / anchors[best_n][:, 1] + 1e-16)\n # One-hot encoding of label\n tcls[b, best_n, gj, gi, target_labels] = 1\n # Compute label correctness and iou at best anchor\n class_mask[b, best_n, gj, gi] = (pred_cls[b, best_n, gj, gi].argmax(-1) == target_labels).float()\n iou_scores[b, best_n, gj, gi] = bbox_iou(pred_boxes[b, best_n, gj, gi], target_boxes, x1y1x2y2=False)\n\n tconf = obj_mask.float()\n return iou_scores, class_mask, obj_mask, noobj_mask, tx, ty, tw, th, tcls, tconf\n","sub_path":"module3_our_dataset/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":16475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"211335106","text":"from looptsp_env import LoopTSPEnvrionment, CostMatrix, Voyage\nimport sys\n\nif __name__ == \"__main__\":\n cost_file = sys.argv[1]\n start_port = sys.argv[2]\n tsp_env = LoopTSPEnvrionment(cost_file)\n voyage = Voyage(tsp_env,start_port)\n\n while True:\n print('elpased date: {}'.format(voyage.elpased_time))\n print('Candidate ports')\n candidate_ports = voyage.get_candidate_arrival_ports()\n print(candidate_ports)\n for port in candidate_ports:\n print('{}: {} (Ideal : {})'.format(port, voyage.calc_actual_cost_of_current_status(port), voyage.get_ideal_cost_of_current_status(port)))\n print('Please input arrival port')\n arrival_port = input()\n if(arrival_port in candidate_ports):\n voyage.sail_to_next_port(arrival_port)\n if voyage.is_finished():\n print('Total date is {}'.format(voyage.elpased_time))\n break\n else:\n print('Illegal input')\n","sub_path":"looptsp/looptsp_cui.py","file_name":"looptsp_cui.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"422299632","text":"\"\"\"\nopdracht 11 - Sterke wachtwoorden\nhttps://dodona.ugent.be/nl/exercises/417422714/\n\"\"\"\n\n# Variables\nwachtwoordArray = []\nglobal aantalVoorwaarden\n\ndef main():\n # User input\n aantalWachtwoorden = float(input(\"Hoeveel wachtwoorden wil je gebruiken: \"))\n\n # Create array\n getAantalWachtwoordenArray(aantalWachtwoorden)\n\n # Check elk wachtwoord op zijn sterkte\n for wachtwoord in wachtwoordArray:\n aantalVoorwaarden = 0\n # Check aantal karakters\n aantalVoorwaarden = aantalKarakters(aantalVoorwaarden, wachtwoord)\n # Check hoofdletter\n aantalVoorwaarden = heeftHoofdletter(aantalVoorwaarden, wachtwoord)\n # Check kleine letter\n aantalVoorwaarden = heeftKleineletter(aantalVoorwaarden, wachtwoord)\n # Check cijfer\n aantalVoorwaarden = heeftCijfer(aantalVoorwaarden, wachtwoord)\n # Check speciale karakter\n aantalVoorwaarden = heeftSpeciaalKarakter(aantalVoorwaarden, wachtwoord)\n # Check sterkte\n wwSterkte = wachtwoordSterkte(aantalVoorwaarden)\n print(wwSterkte)\n\n\ndef getAantalWachtwoordenArray(aantalWachtwoorden) -> wachtwoordArray:\n i = 0\n if aantalWachtwoorden >= 1 and aantalWachtwoorden <= 100:\n while i < aantalWachtwoorden:\n # User input\n ww = input(\"Wachtwoord: \")\n\n # Zet wachtwoord in array\n wachtwoordArray.append(ww)\n i = i + 1\n else:\n print(\"error\")\n\ndef aantalKarakters(aantalVoorwaarden, wachtwoord):\n if len(wachtwoord) >= 8:\n aantalVoorwaarden = aantalVoorwaarden + 1\n return aantalVoorwaarden\n else:\n return aantalVoorwaarden\n\ndef heeftHoofdletter(aantalVoorwaarden, wachtwoord):\n for karakter in wachtwoord:\n if karakter.isupper():\n aantalVoorwaarden = aantalVoorwaarden + 1\n return aantalVoorwaarden\n else:\n return aantalVoorwaarden\n\ndef heeftKleineletter(aantalVoorwaarden, wachtwoord):\n for karakter in wachtwoord:\n if karakter.islower():\n aantalVoorwaarden = aantalVoorwaarden + 1\n return aantalVoorwaarden\n else:\n return aantalVoorwaarden\n\ndef heeftCijfer(aantalVoorwaarden, wachtwoord):\n for karakter in wachtwoord:\n if karakter.isdigit():\n aantalVoorwaarden = aantalVoorwaarden + 1\n return aantalVoorwaarden\n else:\n return aantalVoorwaarden\n\ndef heeftSpeciaalKarakter(aantalVoorwaarden, wachtwoord):\n valid = set('!@#$%^&*()_-+=,./?;:{[}]')\n for karakter in wachtwoord:\n if karakter in valid:\n aantalVoorwaarden = aantalVoorwaarden + 1\n return aantalVoorwaarden\n else:\n return aantalVoorwaarden\n\ndef wachtwoordSterkte(aantalVoorwaarden):\n if aantalVoorwaarden < 3:\n wachtwoordSterkte = \"zwak\"\n elif aantalVoorwaarden == 3 or aantalVoorwaarden == 4:\n wachtwoordSterkte = \"matig\"\n else:\n wachtwoordSterkte = \"sterk\"\n return wachtwoordSterkte\n\nif __name__ == \"__main__\":\n main()","sub_path":"week02/Sterke wachtwoorden.py","file_name":"Sterke wachtwoorden.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"382852350","text":"from django.db import models\n\nclass ProfileManager(models.Manager):\n def get_by_natural_key(self, token):\n return self.get(token=token)\n\nclass Profile(models.Model):\n \"\"\" a Profile is a named view for an alternative representation of a resource. \n \n Definitions support \"content negotiation by profile\" according to https://www.w3.org/TR/dx-prof-conneg/ \n \n Profiles may be defined in a non-cyclic specialisation graph (a single profile may be a profile of one or more other profiles, and be returned as a valid response if the more general profile is requested.\n \"\"\"\n readonly_fields = ('profilesTransitive',)\n profilesTransitive = ()\n \n class Meta:\n app_label = 'uriredirect'\n ordering = ['token']\n verbose_name = 'Profile (View)'\n verbose_name_plural = 'Profiles (Views)'\n\n \n objects = ProfileManager()\n \n def natural_key(self):\n return(self.token,)\n \n token = models.CharField(\n max_length=100, blank=False, null=False,\n unique = True, help_text='A comma separated list of short tokens this profile may be invoked by'\n )\n \n mediaprofs = models.CharField(\n max_length=1000, blank=True, null = True, \n unique = False, help_text='a comma separated list of media-types with profiles such as \"application/gml+xml; version=3.2\" that match this profile. This is an extension point not fpor documentation, but not yet used in validation - accept mappings must be provided.' \n )\n \n uri = models.URLField(\n max_length=1000, \n blank=False, null=False, verbose_name = 'Canonical URI',\n help_text = 'The canonical URI of the profile - this is what an external system needs to check to determine what a token means'\n )\n \n label = models.CharField(\n max_length=100, \n blank=True, null=True, verbose_name = 'Display Label',\n help_text = 'Display label for profile'\n )\n \n comment = models.TextField(\n max_length=1000, \n blank=True, null=True, verbose_name = 'Description',\n help_text = 'The canonical URI of the profile - this is what an external system needs to check to determine what a token means'\n )\n \n profiles = models.ManyToManyField( \"Profile\", blank=True,\n help_text= 'Profiles may be defined in a non-cyclic specialisation graph (a single profile may be a profile of one or more other profiles, and be returned as a valid response if the more general profile is requested.'\n )\n \n profilesTransitive = models.ManyToManyField( \"Profile\", blank=True, related_name='ancestors',\n help_text= 'Calculated list of all profiles that are ancestors of this one'\n )\n \n def getTokenURI(self):\n \"\"\" Get a tuple of token and URI \n \"\"\"\n return ( self.token, self.uri) \n \n def __unicode__(self):\n return self.token\n \n def __str__(self):\n return str(self.token)\n \n\n\n \n\n \n ","sub_path":"uriredirect/models/Profile.py","file_name":"Profile.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"18178394","text":"# !/usr/bin/python3\n# coding: utf-8 \n# @Author : wenbin\n# @Time : 2019/12/29 下午5:38\n# @Software: PyCharm\n# @File : client.py\nimport zmq\n# 创建zmq Context上下文类的实例\ncontext = zmq.Context()\n# 调用socket方法创建创建socket\nsocket = context.socket(zmq.REQ)\n# 使用socket连接到服务端\nsocket.connect('tcp://localhost:12306')\nprint('zmq client start....')\nsocket.send_string('我准备好了,请给我发消息吧!')\nmessage = socket.recv()\nprint('已经收到server端响应的信息: ', message.decode('utf-8'))\n","sub_path":"python_basis/pyzmq/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"372172008","text":"\"\"\"\nDjango settings for dumbo project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n# a setting to determine whether we are running on OpenShift\nON_OPENSHIFT = False\nif 'OPENSHIFT_REPO_DIR' in os.environ:\n ON_OPENSHIFT = True\n\nPROJECT_DIR = os.path.dirname(os.path.realpath(__file__))\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'l6=*m!_snnmr-b)(^&@2spfe%n^+8%xb(^g*8*rc@900m+yu@w'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nif ON_OPENSHIFT:\n DEBUG = bool(os.environ.get('DEBUG', False))\n if DEBUG:\n print(\"WARNING: The DEBUG environment is set to True.\")\nelse:\n DEBUG = True\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = ['dumbo-acarmisc.rhcloud.com']\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'rest_framework',\n 'core',\n 'products',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'dumbo.urls'\n\nWSGI_APPLICATION = 'dumbo.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\nif ON_OPENSHIFT:\n # os.environ['OPENSHIFT_MYSQL_DB_*'] variables can be used with databases created\n # with rhc cartridge add (see /README in this git repo)\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': os.path.join(os.environ['OPENSHIFT_DATA_DIR'], 'sqlite3.db'), # Or path to database file if using sqlite3.\n 'USER': '', # Not used with sqlite3.\n 'PASSWORD': '', # Not used with sqlite3.\n 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.\n 'PORT': '', # Set to empty string for default. Not used with sqlite3.\n }\n }\nelse:\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': os.path.join(PROJECT_DIR, 'sqlite3.db'), # Or path to database file if using sqlite3.\n 'USER': '', # Not used with sqlite3.\n 'PASSWORD': '', # Not used with sqlite3.\n 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.\n 'PORT': '', # Set to empty string for default. Not used with sqlite3.\n }\n }\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\nSTATIC_ROOT = os.path.join(PROJECT_DIR, '..', 'static')\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\nSTATIC_URL = '/static/'\n\nADMIN_MEDIA_PREFIX = '/static/admin/'\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n #'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n","sub_path":"wsgi/dumbo/dumbo/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"460333014","text":"#=======================================================\n# 스핀 위젯\n#=======================================================\nimport sys\n\nfrom PyQt5.QtCore import Qt, QDate\nfrom PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget, QVBoxLayout, QLabel, QSpinBox, QDoubleSpinBox\nfrom PyQt5.QtGui import QIcon\n\n\nclass MyApp(QWidget):\n\n #================================\n # 초기화 동작 수행\n #================================\n def __init__(self):\n super().__init__()\n self.initUI() # 기본 UI 초기화\n\n #=================================\n # 윈도우를 화면 가운데 위치 시키기\n #=================================\n def center(self):\n qr = self.frameGeometry() # 창의 위치와 크기 정보를 가져\n cp = QDesktopWidget().availableGeometry().center() # 사용하는 모니터 화면의 가운데 위치를 파악\n qr.moveCenter(cp) # 창의 직사각형 위치를 화면의 중심의 위치로 이동합니다.\n self.move(qr.topLeft())\n\n # ================================\n # 화면 기본 설정\n # ================================\n def initUI(self):\n\n # 스핀 박스\n self.lbl1 = QLabel('QSpinBox')\n self.spinbox = QSpinBox()\n self.spinbox.setMinimum(-10)\n self.spinbox.setMaximum(30)\n # self.spinbox.setRange(-10, 30)\n self.spinbox.setSingleStep(2)\n self.lbl2 = QLabel('0')\n\n self.spinbox.valueChanged.connect(self.valueUpDown)\n\n # 더블 스핀 박스\n self.lblDS1 = QLabel('QDoubleSpinBox')\n self.dspinbox = QDoubleSpinBox()\n self.dspinbox.setRange(0, 100)\n self.dspinbox.setSingleStep(2.5)\n self.dspinbox.setPrefix('$ ')\n self.dspinbox.setDecimals(1)\n self.lblDS2 = QLabel('0.0')\n\n self.dspinbox.valueChanged.connect(self.dValueUpDown)\n\n # 레이아웃 설정\n vBox = QVBoxLayout()\n vBox.addWidget(self.lbl1)\n vBox.addWidget(self.spinbox)\n vBox.addWidget(self.lbl2)\n vBox.addStretch(1)\n vBox.addWidget(self.lblDS1)\n vBox.addWidget(self.dspinbox)\n vBox.addWidget(self.lblDS2)\n vBox.addStretch(2)\n\n self.setLayout(vBox)\n\n self.setWindowTitle(\"스핀 위젯\") # 타이틀\n self.setWindowIcon(QIcon('../../Utils/Images/web.png')) # 아이콘 추가\n self.resize(500, 350) # 크기 설정\n self.center()\n self.show() # 보이기\n\n def valueUpDown(self):\n self.lbl2.setText(str(self.spinbox.value()))\n\n def dValueUpDown(self):\n self.lblDS2.setText(str(self.dspinbox.value()))\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n ex = MyApp()\n sys.exit(app.exec())","sub_path":"GUI/Widget/스핀_위젯.py","file_name":"스핀_위젯.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"500303927","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# ylgongPw @ 2020-02-13 10:53:31\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def reverseList(self, head: ListNode) -> ListNode:\n pre = None\n curr = head\n\n while curr:\n tmp = curr.next\n curr.next = pre\n pre = curr\n curr = tmp\n\n return pre\n\n\n\nif __name__ == '__main__':\n head = ListNode(1)\n prev = head\n\n nums = [2,3,4,5]\n for num in nums:\n node = ListNode(num)\n prev.next = node\n prev = node\n\n head = Solution().reverseList(head)\n\n node = head\n while node:\n print (node.val)\n node = node.next\n\n","sub_path":"206/206-my.py","file_name":"206-my.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"87948523","text":"import random\n\nclass ElectricCat:\n \"\"\"\n Class for the Electric Cat Progmon\n \"\"\"\n def __init__(self):\n \"\"\"\n Creates variables associated with ElectricCat\n Args:\n self (object) - ElectricCat\n Returns:\n None\n \"\"\"\n self.name = \"Electric Cat\"\n self.hp = 250\n self.currentHealth = 250\n self.alive = True\n self.bag = [\"healthPotion\"]\n\n def doDamage(self, damageDone):\n \"\"\"\n Deals damage to the enemy's health; set alive to False if health goes below 1\n Args:\n self (object) - ElectricCat\n damageDone (int) - amount of damage to do\n Returns:\n None\n \"\"\"\n self.currentHealth = self.currentHealth - damageDone\n if(self.currentHealth <= 0):\n self.alive = False\n\n def checkAlive(self):\n \"\"\"\n Checks if ElectricCat is alive\n Args:\n self (object) - ElectricCat\n Returns:\n (bool) - True if ElectricCat is alive, otherwise False\n \"\"\"\n if(self.alive == True):\n return True\n else:\n return False\n\n def getCurrentHealth(self):\n \"\"\"\n Gets the currentHealth of ElectricCat\n Args:\n self (object) - ElectricCat\n Returns:\n ElectricCat's currentHealth\n \"\"\"\n return self.currentHealth\n\n def LightningBoltAttack(self, enemyPlayer): # 90 damage, 45 accuracy\n \"\"\"\n Attacks enemy Progmon with Lightning Bolt\n Args:\n self (object) - ElectricCat\n enemyPlayer (object) - enemy Progmon\n Returns:\n None\n \"\"\"\n chanceToHit = random.randint(1, 101)\n if(chanceToHit <= 45):\n enemyPlayer.doDamage(90)\n print(\"Lightning Bolt did 90 damage!\\n\")\n return True\n else:\n print(\"Lightning Bolt missed!\\n\")\n return False\n\n def ElectricScratchAttack(self, enemyPlayer): # 40 damage, 90 accuracy\n \"\"\"\n Attacks enemy Progmon with Electric Scratch\n Args:\n self (object) - ElectricCat\n enemyPlayer (object) - enemy Progmon\n Returns:\n None\n \"\"\"\n chanceToHit = random.randint(1, 101)\n if(chanceToHit <= 90):\n enemyPlayer.doDamage(40)\n print(\"Electric Scratch did 40 damage!\\n\")\n return True\n else:\n print(\"Electric Scratch missed!\\n\")\n return False\n\n def EnergyBeamAttack(self, enemyPlayer): # 110 damage, 40 accuracy\n \"\"\"\n Attacks enemy Progmon with Energy Beam\n Args:\n self (object) - ElectricCat\n enemyPlayer (object) - enemy Progmon\n Returns:\n None\n \"\"\"\n chanceToHit = random.randint(1, 101)\n if(chanceToHit <= 40):\n enemyPlayer.doDamage(110)\n print(\"Energy Beam did 110 damage!\\n\")\n return True\n else:\n print(\"Energy Beam missed!\\n\")\n return False\n\n def BiteAttack(self, enemyPlayer): # 20 damage, 100 accuracy\n \"\"\"\n Attacks enemy Progmon with Bite\n Args:\n self (object) - ElectricCat\n enemyPlayer (object) - enemy Progmon\n Returns:\n None\n \"\"\"\n enemyPlayer.doDamage(20)\n print(\"Bite did 20 damage!\\n\")\n return True\n\n def AIAttack(self, enemyPlayer):\n \"\"\"\n Attacks enemy Progmon with a randomly chosen attack\n Args:\n self (object) - ElectricCat\n enemyPlayer (object) - enemy Progmon\n Returns:\n (string) - the attack that was used by the AI\n (bool) - True if the attack hit, otherwise False\n \"\"\"\n #randomly choose one of ElectricCat's attacks and then use it\n #returns a string of which attack was used so that user can know what AI did/if it was successful\n attackToUse = random.randint(1, 5)\n tempHealth = enemyPlayer.getCurrentHealth()\n if(attackToUse == 1):\n self.LightningBoltAttack(enemyPlayer)\n if(tempHealth != enemyPlayer.getCurrentHealth()):\n return \"LightningBolt\", True\n else:\n return \"LightningBolt\", False\n if(attackToUse == 2):\n self.ElectricScratchAttack(enemyPlayer)\n if(tempHealth != enemyPlayer.getCurrentHealth()):\n return \"ElectricScratch\", True\n else:\n return \"ElectricScratch\", False\n if(attackToUse == 3):\n self.EnergyBeamAttack(enemyPlayer)\n if(tempHealth != enemyPlayer.getCurrentHealth()):\n return \"EnergyBeam\", True\n else:\n return \"EnergyBeam\", False\n if(attackToUse == 4):\n self.BiteAttack(enemyPlayer)\n if(tempHealth != enemyPlayer.getCurrentHealth()):\n return \"Bite\", True\n else:\n return \"Bite\", False\n\n def useHealthPotion(self):\n \"\"\"\n Uses a healthPotion to heal 30 points of health\n Args:\n self (object) - ElectricCat\n Returns:\n None\n \"\"\"\n self.currentHealth = self.currentHealth + 30\n self.bag.remove(\"healthPotion\")\n\n def bagEmpty(self):\n \"\"\"\n Checks if the Bag is empty\n Args:\n self (object) - ElectricCat\n Returns:\n (bool) - True if Bag is empty, otherwise False\n \"\"\"\n if(self.bag):\n return False\n else:\n return True\n","sub_path":"electricCat.py","file_name":"electricCat.py","file_ext":"py","file_size_in_byte":5656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"506199389","text":"import math\nimport os\nfrom subprocess import call\n\nimport numpy\nimport scipy.stats\n\nfrom options import merge\nfrom options.constants import Constants\nfrom options.merge import MergeType\nfrom result.resultset import ResultSet\n\n\nclass JGraph(Constants):\n\n JGRAPH_EXEC = \"/usr/bin/jgraph\"\n\n FONTSIZE = 16\n INITIAL_PADDING = 0.5\n BAR_PADDING = 0.1\n BENCH_PADDING = 1.0\n\n # Larger values mean lighter shade\n SHADE_START = 0.9\n SHADE_END = 0.4\n\n MAJOR_STRIDE_THICKNESS = 1.0\n MINOR_STRIDE_THICKNESS = 0.0\n X_TEXT_ANGLE = 35.0\n\n SUMMARY_PADDING = 0.5\n SUMMARY_MERGE_TYPE = MergeType.MERGE_GEOMEAN\n\n DRAW_ERROR_BARS = False # Not important for architectural simulations\n\n def __init__(self, options, outputPath, htmFile, key, rs, norm):\n self.options = options\n self.outputPath = outputPath\n self.htmFile = htmFile\n self.key = key\n self.rs = rs\n self.name = self.key + \".jgr\"\n self.normalize = norm\n\n self.xInches = 10\n self.xMax = 0.0\n self.xMin = 0.0\n self.xLabel = \"simulator configurations\"\n self.xMajorStride = 0.0\n self.xMinorStride = 0.0\n\n self.yInches = 5\n self.yMax = 1000.0\n self.yMin = 0.0\n self.yLabel = key\n self.yNumMajorStrides = 10\n self.yMajorStride = 0\n self.yMinorStride = 0.0\n\n self.li_OverflownYValues = []\n\n if options.trials == 1:\n JGraph.DRAW_ERROR_BARS = False\n\n def convertToEPS(self):\n cwd = os.getcwd()\n os.chdir(self.outputPath)\n\n str_cmdLine = \"jgraph \" + self.name + \" > \" + self.key + \".eps\"\n call(str_cmdLine, shell=True)\n\n os.chdir(cwd)\n\n def convertToPNG(self):\n cwd = os.getcwd()\n os.chdir(self.outputPath)\n\n str_cmdLine = (\n \"convert -density 300 \" + self.key + \".eps\" + \" -resize 1024x1024 \" + self.key + \".png\")\n call(str_cmdLine, shell=True)\n\n os.chdir(cwd)\n\n # http://stackoverflow.com/questions/20261517/inheritance-of-private-and-protected-methods-in-python\n def _createGraph(self):\n f = open(self.name, \"w\")\n return f\n\n def _startGraph(self, f):\n f.write(\"newgraph\\n\")\n str_line = \"title : Compare \"\n if self.normalize:\n str_line += \" normalized \"\n else:\n str_line += \" absolute \"\n str_line += \" values of \" + self.key + \" \\n\\n\"\n f.write(str_line)\n\n def _merge(self, lrs, key):\n \"\"\"Merge result set over all trials with the given key. This method takes care of\n benchmarks and configurations/tools.\n \"\"\"\n li_union = []\n # Limit based on benchmarks and tools\n for bench in self.options.getBenchTuple():\n for tool in self.options.getSimulatorsTuple():\n di_known = {}\n di_known[\"bench\"] = bench\n di_known[\"tool\"] = tool\n rs = ResultSet.limitResultSetWithDict(lrs, di_known)\n if not rs:\n continue\n\n di_ms = merge.merge(rs, key)\n # Union the two dictionaries\n di_known = dict(di_known, **di_ms)\n li_union.append(di_known)\n return li_union\n\n def _computeAxes(self, li_di_thisKey):\n \"\"\"Compute the max dimension for the axes.\"\"\"\n self.xMax = self.BENCH_PADDING * len(self.options.getBenchTuple())\n self.xMax += self.SUMMARY_PADDING + self.BENCH_PADDING\n\n if self.normalize:\n self.yMax = 2.01\n self.yMajorStride = 0.2\n else:\n li_values = []\n for di_tmp in li_di_thisKey:\n li_values.append(di_tmp.get(self.key))\n\n if not li_values:\n print(li_values)\n print(self.key)\n print(li_di_thisKey)\n\n _dec, _in = math.modf(max(li_values))\n self.yMax = _in\n\n if self.yMax == 0.0:\n self.yMax = 1.01\n self.yMajorStride = 0.1\n elif self.yMax > 10.0:\n self.yMajorStride = int(self.yMax / 10)\n elif self.yMax > 1.0:\n self.yMajorStride = 1.0\n else:\n self.yMajorStride = self.yMax / 10\n\n def _generateAxes(self, f):\n self.__generateAxis(f, True)\n self.__generateAxis(f, False)\n f.write(\"hash_labels fontsize \" + str(self.FONTSIZE) + \"\\n\\n\")\n self.__drawHorizontalLines(f)\n\n def __drawHorizontalLines(self, f):\n in_yVal = 0.0\n while True:\n f.write(\"newline poly linethickness \" + str(JGraph.MAJOR_STRIDE_THICKNESS) + \"\\n\")\n f.write(\" pts \" + str(self.xMin) + \" \" + str(in_yVal) + \" \" + str(self.xMax) + \" \" +\n str(in_yVal) + \"\\n\")\n in_yVal += self.yMajorStride\n if in_yVal > self.yMax:\n break\n f.write(\"\\n\")\n\n def _writeHashLabel(self, f, bench, pos):\n f.write(\"xaxis hash_label at \" + str(pos) + \" : \" + bench)\n f.write(\"\\n\")\n\n def __generateAxis(self, f, isX):\n if isX:\n f.write(\"xaxis\\n\")\n f.write(\" min 0.0\\n\")\n f.write(\" max \" + str(self.xMax) + \"\\n\")\n f.write(\" size \" + str(self.xInches) + \"\\n\")\n f.write(\" no_auto_hash_labels\\n\")\n f.write(\" no_draw_hash_marks\\n\")\n f.write(\" hash 1.0\\n\\n\")\n\n f.write(\"hash_labels hjl vjt rotate -\" + str(self.X_TEXT_ANGLE) + \" fontsize \" +\n str(self.FONTSIZE) + \"\\n\\n\")\n else:\n f.write(\"yaxis\\n\")\n f.write(\" label : \" + self.key + \"\\n\")\n f.write(\" fontsize \" + str(JGraph.FONTSIZE) + \"\\n\")\n f.write(\" min 0.0\\n\")\n f.write(\" max \" + str(self.yMax) + \"\\n\")\n f.write(\" size \" + str(self.yInches) + \"\\n\")\n f.write(\" hash \" + str(self.yMajorStride) + \"\\n\\n\")\n\n def _customizeLegend(self, f):\n \"\"\"Write the legends string.\"\"\"\n f.write(\"legend defaults fontsize \" + str(self.FONTSIZE) + \"\\n\")\n f.write(\"\\n\")\n\n def _plotOverflownYValues(self, f):\n for str_cmd in self.li_OverflownYValues:\n f.write(str_cmd + \"\\n\")\n f.write(\"\\n\")\n\n def _drawTextCommand(self, x_pos, y_pos, str_text):\n return (\"newstring vjc hjc x \" + str(x_pos) + \" y \" + str(y_pos) + \" fontsize \" + str(\n self.FONTSIZE) + \" : \" + str_text)\n\n def __mean_confidence_interval(self, data, confidence=0.95):\n \"\"\"Compute 95% confidence intervals.\"\"\"\n a = 1.0 * numpy.array(data)\n n = len(a)\n m, se = numpy.mean(a), scipy.stats.sem(a)\n h = se * scipy.stats.t._ppf((1 + confidence) / 2., n - 1)\n return m, m - h, m + h\n\n def __drawLine(self, f, width, srcX, srcY, destX, destY):\n f.write(\"newline poly linethickness \" + str(width) + \"\\n\")\n f.write(\" pts \" + str(srcX) + \" \" + str(srcY) + \" \" + str(destX) + \" \" + str(destY))\n f.write(\"\\n\")\n\n def _generateErrorBars(self, f, li_bench, fl_barStart, fl_width, str_tool, str_bench):\n di_limit = {}\n di_limit[\"bench\"] = str_bench\n di_limit[\"tool\"] = str_tool\n di_limitedRs = ResultSet.limitResultSetWithDict(self.rs, di_limit)\n li_values = []\n for d in di_limitedRs:\n li_values.append(d.get(self.key))\n m, lci, uci = self.__mean_confidence_interval(li_values)\n if self.normalize:\n if m > 0.0:\n li_actValue = ResultSet.limitResultSetWithDict(li_bench, di_limit)\n assert len(li_actValue) == 1\n di_actValue = li_actValue[0]\n fl_actValue = di_actValue.get(self.key)\n lci = fl_actValue - ((m - lci) / m)\n uci = fl_actValue + ((uci - m) / m)\n\n # Let us not plot the error bars if the lci is not within the yMax,\n # because otherwise it is going to look weird\n if lci <= self.yMax:\n self.__drawLine(f, fl_width, fl_barStart, lci, fl_barStart, uci)\n self.__drawLine(f, fl_width, fl_barStart - fl_width / 2, lci,\n fl_barStart + fl_width / 2, lci)\n self.__drawLine(f, fl_width, fl_barStart - fl_width / 2, uci,\n fl_barStart + fl_width / 2, uci)\n","sub_path":"sim-framework/src/result/jgraph.py","file_name":"jgraph.py","file_ext":"py","file_size_in_byte":8363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"586087833","text":"# -*- coding: utf-8 -*-\n# @Author: Tianxiao Yang\n# @Date: 2017-06-13 12:30:58\n# @Last Modified by: Tianxiao Yang\n# @Last Modified time: 2017-06-20 16:35:46\nfrom util.questionmeta import QuestionMeta\nfrom tools.syntaxparser import SyntaxParser\nfrom util.data_settings import *\n\n'''\n'''\nDELI = ''\nclass CodeGenerator:\n def __init__(self, problem_id, l_type, total_testcases):\n self.sp = SyntaxParser(problem_id, JAVA)\n input_trees = self.sp.get_input_type()\n output_trees = self.sp.get_output_type()\n param_name_arrs = self.sp.get_param_name()\n self.func_names = self.sp.get_func_name()\n self.gens = []\n # function order in func_names is the same as in input, param, output arrs\n for i in range(len(self.func_names)):\n self.gens.append(Gen(problem_id, l_type, total_testcases, input_trees[i][1], output_trees[i][1], param_name_arrs[i][1], self.func_names[i]))\n\n def generate_variable(self, offset, end):\n var_arr = [gen.generate_variable(offset, end) for gen in self.gens]\n return \"\".join(var_arr)\n\n def generate_function(self, boolean_value):\n func_arr = [gen.generate_function(boolean_value) for gen in self.gens]\n return \"\".join(func_arr)\n\n def get_function_names(self):\n return self.func_names\n\nclass Gen:\n def __init__(self, problem_id, l_type, total_testcases, input_tree, output_tree, param_name_arr, func_name): \n self.problem_id = str(problem_id)\n self.l_type = l_type\n # self.qm = QuestionMeta()\n # self.qm.load()\n self.JAVA = 'java'\n self.PYTHON = 'python'\n self.CPP = 'cpp'\n\n # self.sp = SyntaxParser(self.problem_id, self.JAVA)\n self.total_testcases = total_testcases\n self.input_tree = input_tree\n self.output_tree = output_tree\n self.param_name_arr = param_name_arr\n self.func_name = func_name\n self.param_arr = []\n self.param_name_template = \"_{num}Param_\" + self.func_name\n # the problem may have no input parameter\n if self.param_name_arr:\n for i, child in enumerate(self.input_tree.get_root_child()):\n self.param_arr.append((self.param_name_arr[i], str(child)))\n # generate static variable that are used to cache test cases\n def generate_variable(self, offset, end):\n if type(offset) is not int:\n raise TypeError('offset must be a int instead of {0}'.format(type(offset)))\n if type(end) is not int:\n raise TypeError('end must be a int instead of {0}'.format(type(end)))\n switch = {self.CPP: self.__gen_cpp_static,\n self.JAVA: self.__gen_java_static,\n self.PYTHON: self.__gen_py_static}\n if self.l_type not in switch:\n raise TypeError('Unsupported l_type: {0}'.format(self.l_type))\n return switch[self.l_type](offset, end)\n\n def generate_function(self, boolean_value):\n # if self.l_type == 'cpp':\n # return self.__gen_cpp_func()\n if self.l_type == 'java':\n return self.__gen_java_func(boolean_value)\n # if self.l_type == 'python':\n # return self.__gen_py_func()\n raise TypeError('Unsupported l_type: {0}'.format(self.l_type))\n\n # boolean_value is needed to when return type is boolean(50% probability accepted)\n def __gen_java_func(self, boolean_value):\n self.boolean_value = boolean_value\n func_define = \"{accessibility} {output_type} {func_name} ({param_list})\"\n func_body = \"{{{0}}};\"\n\n # defination\n param_template = \"{type} {name}\"\n param_arr = []\n for p_name, p_type in self.param_arr:\n param_arr.append(param_template.format(type=p_type, name=p_name))\n\n func_define = func_define.format(accessibility='public', \n output_type=str(self.output_tree.get_root().get_child_type()[0]), \n func_name=self.func_name, \n param_list=\",\".join(param_arr))\n\n # body\n func_body = func_body.format(self.__body(\n self.__printer(\n self.__printer_body(\n self.__formatter(\n self.__sub_printer(\n self.__recur_printer\n ))))))\n # _encode_tree method can serialize a tree with inorder traversal\n util_func = 'void _encode_tree(TreeNode root, List cache) {if (root == null) {cache.add(\"#\"); return; } cache.add(Integer.toString(root.val)); _encode_tree(root.left, cache); _encode_tree(root.right, cache); }'\n return \"\".join([util_func, func_define, func_body])\n\n def __body(self, printer):\n body_template = \"{limiter}{walker}{printer}{returner}\"\n limiter_template = \"if (_walker >= _home) {{{adder}}};\"\n # adder_template = \"_{num}Param.add({param_name});\"\n # adder_template = \"_{num}Param[_walker - _home] = {param_name};\"\n # Becuase of some wired stuff in leetcode case runner, I need to initiate an array long enough to get all test cases\n adder_template = self.param_name_template + \".add({param_name});\"\n adder = \"\".join([adder_template.format(num=i, param_name=self.param_name_arr[i], total_testcases=self.total_testcases) for i in range(len(self.param_name_arr))])\n limiter = limiter_template.format(adder=adder)\n walker = \"_walker++;\"\n returner_template = \"{do_return} _{origin_func_name}({origin_params});\"\n # if the return type of this solution is void, \n # then we don't need to return any thing, just call the function is fine\n output_type_str = str(self.output_tree.get_root_child()[0])\n do_return = 'return'\n if output_type_str == 'void':\n do_return = \"\"\n returner = returner_template.format(do_return=do_return, origin_func_name=self.func_name, origin_params=\",\".join(self.param_name_arr))\n return body_template.format(do_return=do_return,\n limiter=limiter,\n walker=walker,\n printer=printer,\n returner=returner)\n\n def __printer(self, printer_body):\n printer_template = \"if (_walker == _office) {{{print_body}}};\"\n return printer_template.format(print_body=printer_body)\n\n def __printer_body(self, formatter):\n print_body_template = \"for (int i = 0; i < _walker - _home; i++) {{{formatter}}};return {code_stopper};\"\n output_type_str = str(self.output_tree.get_root_child()[0])\n code_stopper = 'null'\n if output_type_str in ['int', 'double', 'float', 'long', 'short']:\n code_stopper = '-19930326'\n type_cases = {\n 'char': \"'*'\",\n 'boolean': self.boolean_value,\n 'void': '',\n }\n if output_type_str in type_cases:\n code_stopper = type_cases[output_type_str]\n return print_body_template.format(formatter=formatter, code_stopper=code_stopper)\n\n def __formatter(self, sub_printers):\n formatter_template = '{beginner}{sub_printers}{endder}'\n # beginner = 'System.out.println(\"---BEGIN:\" + (i + _home + 1) + \"---\");'\n beginner = ''\n endder = 'System.out.println(\"---END:\" + (i + _home + 1) + \"---\");'\n return formatter_template.format(beginner=beginner, endder=endder, sub_printers=sub_printers)\n\n def __sub_printer(self, recur_printer):\n pre_fix = \"_\"\n separator = \"System.out.println();\"\n # recur_printer_template = \"System.out.print('[');for ({sub_type} {pre_fix}p: _{num}Param.get(i)) {{{recur_printer}}}System.out.print(']');{separator}\"\n code_arr = []\n for num in range(len(self.param_name_arr)):\n _node = self.input_tree.get_root_child()[num]\n recur_printer_template = \"System.out.print('[');for ({sub_type} {pre_fix}p:\" + self.param_name_template + \".get(i)) {{{recur_printer}}}System.out.print(']');{separator}\"\n\n if _node.get_type() not in ['List', '[]', 'ListNode', 'TreeNode']:\n recur_printer_template = ''.join(['System.out.print(\"[\");',\n 'System.out.print(' + self.param_name_template + '.get(i));',\n 'System.out.print(\"]\");', \n '{separator}'])\n code_arr.append(recur_printer_template.format(num=num, separator=separator))\n elif _node.get_type() == 'ListNode':\n recur_printer_template = ''.join(['System.out.print(\"[\");',\n 'ListNode _{num}temp_node = ' + self.param_name_template + '.get(i); while(_{num}temp_node != null) {{'+ DELI +' System.out.print(_{num}temp_node.val + \",\"); '+ DELI +' _{num}temp_node = _{num}temp_node.next; }}',\n 'System.out.print(\"]\");', \n '{separator}'])\n code_arr.append(recur_printer_template.format(num=num, separator=separator))\n elif _node.get_type() == 'TreeNode':\n recur_printer_template = ''.join(['System.out.print(\"[\");',\n 'List __cache = new ArrayList(); _encode_tree(' + self.param_name_template + '.get(i), __cache); System.out.print(__cache);',\n 'System.out.print(\"]\");', \n '{separator}'])\n code_arr.append(recur_printer_template.format(num=num, separator=separator))\n else:\n code_arr.append(recur_printer_template.format(sub_type=str(_node.get_child_type()[0]),\n pre_fix=pre_fix,\n num=num,\n recur_printer=recur_printer(_node.get_child_type()[0], pre_fix),\n separator=separator)) \n return ''.join(code_arr)\n\n def __recur_printer(self, param_node, pre_fix):\n recur_printer_template = 'System.out.print(\"[\"); for ({sub_type} {pre_son}p: {pre_dad}p) {{{sub_printer}}}; System.out.print(\"]\");'\n return self.__java_recursive_printer(recur_printer_template, param_node, pre_fix)\n\n def __java_recursive_printer(self, recur_printer_template, param_node, pre_fix):\n if param_node.get_type() in ['List', '[]']:\n return recur_printer_template.format(sub_type=str(param_node.get_child_type()[0]),\n pre_son=pre_fix + '_', \n pre_dad=pre_fix, \n sub_printer=self.__java_recursive_printer(recur_printer_template,\n param_node.get_child_type()[0],\n pre_fix + '_'))\n return DELI +'System.out.print({0}p);System.out.print(\",\");'.format(pre_fix)\n\n def __gen_java_static(self, offset, end):\n static_counter = \"static int _home = {0};static int _walker = 0;static int _office = {1};\".format(offset, end)\n static_cache_template = \"static List<{param_type}> \" + self.param_name_template + \" = new ArrayList<{param_type}>({fetching_length});\"\n # static_cache_template = \"static {param_type}[] _{param_num}Param = new {param_type}[{fetching_length}];\"\n static_statement_arr = [static_counter]\n\n for i, child in enumerate(self.input_tree.get_root_child()):\n type_str = str(child)\n boxing = {\n 'int': 'Integer',\n 'double': 'Double',\n 'float': 'Float',\n 'char': 'Character',\n 'boolean': 'Boolean',\n 'long': 'Long',\n 'short': 'Short',\n }\n\n if type_str in boxing:\n type_str = boxing[type_str]\n static_statement_arr.append(static_cache_template.format(param_type=type_str, \n num=str(i), \n fetching_length=self.total_testcases))\n\n static_statement = \"\".join(static_statement_arr)\n return static_statement\n\n def __gen_cpp_static(self, offset):\n raise NotImplementedError\n\n def __gen_py_static(self, offset):\n raise NotImplementedError\n","sub_path":"leet_crawler/leet_crawler/tools/codegen.py","file_name":"codegen.py","file_ext":"py","file_size_in_byte":13050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"29976341","text":"from django.template import Context, loader\nfrom django.http import HttpResponse\ndef index(request):\n\tt = loader.get_template('hello/index.html')\n\tmy_list = [\"yo\", \"oi\", \"heya\"]\n\td = {'greeting': 'hola', 'my_list':my_list}\n\tc = Context(d)\n\treturn HttpResponse(t.render(c))\n\ndef howdy(request):\n\tt = loader.get_template('hello/howdy.html')\n\td = {'greeting': 'howdy'}\n\tc = Context(d)\n\treturn HttpResponse(t.render(c))","sub_path":"class12/helloworld/hello/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"170383519","text":"# coding: utf-8\n\n# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n\n\"\"\"\nFILE: sample_build_model_async.py\n\nDESCRIPTION:\n This sample demonstrates how to build a model. For this sample, you can use the training\n documents found in https://aka.ms/azsdk/formrecognizer/sampletrainingfiles\n\n More details on setting up a container and required file structure can be found here:\n https://aka.ms/azsdk/formrecognizer/buildtrainingset\n\nUSAGE:\n python sample_build_model_async.py\n\n Set the environment variables with your own values before running the sample:\n 1) AZURE_FORM_RECOGNIZER_ENDPOINT - the endpoint to your Form Recognizer resource.\n 2) AZURE_FORM_RECOGNIZER_KEY - your Form Recognizer API key\n 3) CONTAINER_SAS_URL - The shared access signature (SAS) Url of your Azure Blob Storage container with your training files.\n\"\"\"\n\nimport os\nimport asyncio\n\n\nasync def sample_build_model_async():\n # [START build_model_async]\n from azure.ai.formrecognizer.aio import DocumentModelAdministrationClient\n from azure.ai.formrecognizer import ModelBuildMode\n from azure.core.credentials import AzureKeyCredential\n\n endpoint = os.environ[\"AZURE_FORM_RECOGNIZER_ENDPOINT\"]\n key = os.environ[\"AZURE_FORM_RECOGNIZER_KEY\"]\n container_sas_url = os.environ[\"CONTAINER_SAS_URL\"]\n\n document_model_admin_client = DocumentModelAdministrationClient(\n endpoint, AzureKeyCredential(key)\n )\n async with document_model_admin_client:\n poller = await document_model_admin_client.begin_build_document_model(\n ModelBuildMode.TEMPLATE,\n blob_container_url=container_sas_url,\n description=\"my model description\",\n )\n model = await poller.result()\n\n print(f\"Model ID: {model.model_id}\")\n print(f\"Description: {model.description}\")\n print(f\"Model created on: {model.created_on}\")\n print(f\"Model expires on: {model.expires_on}\")\n print(\"Doc types the model can recognize:\")\n for name, doc_type in model.doc_types.items():\n print(\n f\"Doc Type: '{name}' built with '{doc_type.build_mode}' mode which has the following fields:\"\n )\n for field_name, field in doc_type.field_schema.items():\n print(\n f\"Field: '{field_name}' has type '{field['type']}' and confidence score \"\n f\"{doc_type.field_confidence[field_name]}\"\n )\n # [END build_model_async]\n\n\nasync def main():\n await sample_build_model_async()\n\n\nif __name__ == \"__main__\":\n import sys\n from azure.core.exceptions import HttpResponseError\n\n try:\n asyncio.run(main())\n except HttpResponseError as error:\n print(\n \"For more information about troubleshooting errors, see the following guide: \"\n \"https://aka.ms/azsdk/python/formrecognizer/troubleshooting\"\n )\n # Examples of how to check an HttpResponseError\n # Check by error code:\n if error.error is not None:\n if error.error.code == \"InvalidImage\":\n print(f\"Received an invalid image error: {error.error}\")\n if error.error.code == \"InvalidRequest\":\n print(f\"Received an invalid request error: {error.error}\")\n # Raise the error again after printing it\n raise\n # If the inner error is None and then it is possible to check the message to get more information:\n if \"Invalid request\".casefold() in error.message.casefold():\n print(f\"Uh-oh! Seems there was an invalid request: {error}\")\n # Raise the error again\n raise\n","sub_path":"sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2_and_later/async_samples/sample_build_model_async.py","file_name":"sample_build_model_async.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"617044926","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\nimport math\r\ndef quadratic(a, b, c):\r\n\t#ax2 + bx + c = 0\r\n\tL = [a, b, c]\r\n\tfor x in L:\r\n\t\tif not isinstance(x, (int, float)):\r\n\t\t raise TypeError('bad operand type')\r\n #not check delta \r\n\tdelta = math.sqrt(b * b - 4 * a * c)\r\n\r\n\tm = (-b + delta) / (2 * a)\r\n\tn = (-b - delta) / (2 * a)\r\n\r\n\treturn m, n\r\n\r\n","sub_path":"study/quadratic.py","file_name":"quadratic.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"209607668","text":"import os\nimport utils\nfrom utils import *\nimport pandas as pd\nimport chemdner_data_converter\n\n\ndef labels_to_spantokens(df, mode='label'):\n \"\"\"dfを受け取ってlabel結果からspantokenにして返す。\n mode : label or pred_label\n \"\"\"\n spantokens = set()\n entity = ''\n ann_start = 0\n pre_label = utils.SOS\n for key, row in df.iterrows():\n now_label = row[mode]\n pre_now = (pre_label, now_label)\n # pre_labelとnow_labelのあり得る組み合わせの中で分岐(SOSやBOSはここで弾く。)\n if pre_now in [(B, M), (B, E), (M, E), (E, B), (E, S), (S, B), (O, S), (O, B), (O, M), (O, E)]:\n if now_label == S:\n spantokens.add((row.token, row.start_ix, row.end_ix))\n elif now_label == B:\n ann_start = row.start_ix\n entity += row.token\n elif now_label == M:\n entity += row.token\n elif now_label == E:\n entity += row.token\n spantokens.add((entity, ann_start, row.end_ix))\n entity = ''\n elif now_label == O:\n entity += row.token\n pre_label = now_label\n return spantokens\n\nif __name__ == '__main__':\n CHEM_DATA_PATH = '/Users/user/chemdner_pytorch/chemdner_datas/'\n correct = 0\n test_num = 0\n pred_num = 0\n # load data\n pred_df = pd.read_csv(os.path.join(CHEM_DATA_PATH, 'pred.csv'))\n for file_ix in set(pred_df.file_ix):\n test_spantokens = labels_to_spantokens(pred_df[pred_df.file_ix == file_ix], mode=\"label\")\n pred_spantokens = labels_to_spantokens(pred_df[pred_df.file_ix == file_ix], mode=\"pred_label\")\n print(\"-----------------\")\n print(file_ix)\n print(test_spantokens)\n print(pred_spantokens)\n test_num += len(test_spantokens)\n pred_num += len(pred_spantokens)\n for test_spantoken in test_spantokens:\n for pred_spantoken in pred_spantokens:\n if test_spantoken == pred_spantoken:\n correct += 1\n print(\"test_num: {}, pred_num: {}, correct_num: {}\".format(test_num, pred_num, correct))\n print(\"precision : {}\".format(correct / pred_num))\n print(\"recall : {}\".format(correct / test_num))\n precision = correct / pred_num\n recall = correct / test_num\n print(\"f-score : {}\".format((2 * precision * recall) / (precision + recall)))","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"139884137","text":"#https://codeforces.com/contest/9/problem/A\n\n\na,b = input().split(' ')\na=int(a)\nb=int(b)\nmax=a\n\nif(a GAE:\n \"\"\" Get the critic. \"\"\"\n return self._critic\n\n @critic.setter\n def critic(self, critic: GAE):\n \"\"\" Set the critic. \"\"\"\n if not isinstance(critic, GAE):\n pyrado.TypeErr(given=critic, expected_type=GAE)\n self._critic = critic\n\n @property\n def expl_strat(self) -> NormalActNoiseExplStrat:\n return self._expl_strat\n\n def step(self, snapshot_mode: str, meta_info: dict = None):\n # Sample rollouts\n ros = self.sampler.sample()\n\n # Log return-based metrics\n rets = [ro.undiscounted_return() for ro in ros]\n ret_min = np.min(rets)\n ret_avg = np.mean(rets)\n ret_med = np.median(rets)\n ret_max = np.max(rets)\n ret_std = np.std(rets)\n self.logger.add_value('max return', ret_max)\n self.logger.add_value('median return', ret_med)\n self.logger.add_value('avg return', ret_avg)\n self.logger.add_value('min return', ret_min)\n self.logger.add_value('std return', ret_std)\n self.logger.add_value('num rollouts', len(ros))\n self.logger.add_value('avg rollout len', np.mean([ro.length for ro in ros]))\n\n # Update the advantage estimator and the policy\n self.update(ros)\n\n # Save snapshot data\n self.make_snapshot(snapshot_mode, float(ret_avg), meta_info)\n\n @abstractmethod\n def update(self, rollouts: Sequence[StepSequence]):\n \"\"\"\n Update the actor and critic parameters from the given batch of rollouts.\n\n :param rollouts: batch of rollouts\n \"\"\"\n raise NotImplementedError\n\n def reset(self, seed: int = None):\n # Reset the exploration strategy, internal variables and the random seeds\n super().reset(seed)\n\n # Re-initialize sampler in case env or policy changed\n self.sampler.reinit()\n\n # Reset the critic (also resets its learning rate scheduler)\n self.critic.reset()\n\n # Reset the learning rate scheduler\n if self._lr_scheduler is not None:\n self._lr_scheduler.last_epoch = -1\n\n def save_snapshot(self, meta_info: dict = None):\n super().save_snapshot(meta_info)\n\n if meta_info is None:\n # This algorithm instance is not a subroutine of a meta-algorithm\n joblib.dump(self._env, osp.join(self._save_dir, 'env.pkl'))\n to.save(self._expl_strat.policy, osp.join(self._save_dir, 'policy.pt'))\n to.save(self._critic.value_fcn, osp.join(self._save_dir, 'valuefcn.pt'))\n else:\n # This algorithm instance is a subroutine of a meta-algorithm\n if 'prefix' in meta_info and 'suffix' in meta_info:\n to.save(self._expl_strat.policy, osp.join(self._save_dir,\n f\"{meta_info['prefix']}_policy_{meta_info['suffix']}.pt\"))\n to.save(self._critic.value_fcn, osp.join(self._save_dir,\n f\"{meta_info['prefix']}_valuefcn_{meta_info['suffix']}.pt\"))\n elif 'prefix' in meta_info and 'suffix' not in meta_info:\n to.save(self._expl_strat.policy, osp.join(self._save_dir, f\"{meta_info['prefix']}_policy.pt\"))\n to.save(self._critic.value_fcn, osp.join(self._save_dir, f\"{meta_info['prefix']}_valuefcn.pt\"))\n elif 'prefix' not in meta_info and 'suffix' in meta_info:\n to.save(self._expl_strat.policy, osp.join(self._save_dir, f\"policy_{meta_info['suffix']}.pt\"))\n to.save(self._critic.value_fcn, osp.join(self._save_dir, f\"valuefcn_{meta_info['suffix']}.pt\"))\n else:\n raise NotImplementedError\n\n def load_snapshot(self, load_dir: str = None, meta_info: dict = None):\n # Get the directory to load from\n ld = load_dir if load_dir is not None else self._save_dir\n super().load_snapshot(ld, meta_info)\n\n if meta_info is None:\n # This algorithm instance is not a subroutine of a meta-algorithm\n self._env = joblib.load(osp.join(ld, 'env.pkl'))\n self._critic.value_fcn.load_state_dict(to.load(osp.join(ld, 'valuefcn.pt')).state_dict())\n else:\n # This algorithm instance is a subroutine of a meta-algorithm\n if 'prefix' in meta_info and 'suffix' in meta_info:\n self._critic.value_fcn.load_state_dict(\n to.load(osp.join(ld, f\"{meta_info['prefix']}_valuefcn_{meta_info['suffix']}.pt\")).state_dict()\n )\n elif 'prefix' in meta_info and 'suffix' not in meta_info:\n self._critic.value_fcn.load_state_dict(\n to.load(osp.join(ld, f\"{meta_info['prefix']}_valuefcn.pt\")).state_dict()\n )\n elif 'prefix' not in meta_info and 'suffix' in meta_info:\n self._critic.value_fcn.load_state_dict(\n to.load(osp.join(ld, f\"valuefcn_{meta_info['suffix']}.pt\")).state_dict()\n )\n else:\n raise NotImplementedError\n","sub_path":"Pyrado/pyrado/algorithms/actor_critic.py","file_name":"actor_critic.py","file_ext":"py","file_size_in_byte":6919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"35924056","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns=[\n url(r'^$',views.index),\n url(r'^register$',views.register),\n url(r'^home$',views.home),\n url(r'^add$',views.newJob),\n url(r'^save$',views.saveNewJob),\n url(r'^login$',views.login),\n url(r'^logout$',views.logout),\n url(r'^edit/(?P\\d+)$',views.edit),\n url(r'^saveJob/(?P\\d+)$',views.saveJob),\n url(r'^cancel/(?P\\d+)$',views.cancel),\n url(r'^jobs/view/(?P\\d+)$',views.view),\n url(r'^jobs/add/(?P\\d+)$',views.add),\n url(r'^jobs/done/(?P\\d+)$',views.doneJob) \n]","sub_path":"apps/jobs/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"278538023","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn.cluster import DBSCAN\nfrom sklearn import metrics\nfrom sklearn.datasets.samples_generator import make_blobs\nfrom sklearn.preprocessing import StandardScaler\n\n\nif __name__ == \"__main__\":\n data = pd.read_csv('/home/qiu/Documents/ys_ais/201606_paint_ais_opt.csv')\n # data.columns = [\"unique_ID\", \"acquisition_time\", \"target_type\", \"data_supplier\", \"data_source\",\n # \"status\", \"longitude\", \"latitude\", \"area_ID\", \"speed\", \"conversion\", \"cog\",\n # \"true_head\", \"power\", \"ext\", \"extend\"]\n # data = data[(data[\"longitude\"] >= 122.10 * 1000000.) & (data[\"longitude\"] <= 122.30 * 1000000.) &\n # (data[\"latitude\"] >= 30.50 * 1000000.) & (data[\"latitude\"] <= 30.65 * 1000000.)]\n # data.to_csv(\"/home/qiu/Documents/ys_ais/201606_warning_area_ys.csv\", index=None)\n data = data.loc[:, [\"unique_ID\", \"acquisition_time\", \"longitude\", \"latitude\"]]\n data[\"longitude\"] = data[\"longitude\"] * 1000000.\n data[\"latitude\"] = data[\"latitude\"] * 1000000.\n print(data.head())\n # input(\"==============\")\n X = []\n for index, value in data.iterrows():\n X.append([value[\"longitude\"], value[\"latitude\"]])\n X = np.array(X)\n # #############################################################################\n # Compute DBSCAN\n print(\"start computing...\")\n db = DBSCAN(eps=400, min_samples=6).fit(X)\n core_samples_mask = np.zeros_like(db.labels_, dtype=bool)\n core_samples_mask[db.core_sample_indices_] = True\n labels = db.labels_\n # Number of clusters in labels, ignoring noise if present.\n n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\n print('Estimated number of clusters: %d' % n_clusters_)\n\n # #############################################################################\n # Plot result\n import matplotlib.pyplot as plt\n\n # Black removed and is used for noise instead.\n unique_labels = set(labels)\n colors = [plt.cm.Spectral(each)\n for each in np.linspace(0, 1, len(unique_labels))]\n\n # 初始化主航道内的AIS数据\n main_channel_ais = pd.DataFrame()\n for k, col in zip(unique_labels, colors):\n if k == -1:\n # Black used for noise.\n col = [0, 0, 0, 1]\n class_member_mask = (labels == k)\n\n if col == (0.61960784313725492, 0.0039215686274509803, 0.25882352941176473, 1.0):\n xy = X[class_member_mask & core_samples_mask]\n main_channel_ais = main_channel_ais.append(data[class_member_mask & core_samples_mask])\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),\n markeredgecolor='k', markersize=14)\n\n xy = X[class_member_mask & ~core_samples_mask]\n main_channel_ais = main_channel_ais.append(data[class_member_mask & ~core_samples_mask])\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),\n markeredgecolor='k', markersize=6)\n main_channel_ais.columns = [\"unique_ID\", \"acquisition_time\", \"longitude\", \"latitude\"]\n main_channel_ais[\"longitude\"] = main_channel_ais[\"longitude\"] / 1000000.\n main_channel_ais[\"latitude\"] = main_channel_ais[\"latitude\"] / 1000000.\n print(len(main_channel_ais))\n main_channel_ais.to_csv(\"/home/qiu/Documents/ys_ais/main_channel_ais.csv\", index=None)\n plt.title('Estimated number of clusters: %d' % n_clusters_)\n plt.show()\n","sub_path":"ys_2017/ys_cluster.py","file_name":"ys_cluster.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"414223963","text":"import itertools\n\nimport graphene\nfrom graphene.types.generic import GenericScalar\n\n# from .. import services\n\n\ndef get_graphene_type(*args):\n options = {\n str: graphene.String,\n bool: graphene.Boolean,\n int: graphene.Int,\n float: graphene.Float,\n \"json\": GenericScalar,\n list: graphene.List,\n object: graphene.Field,\n }\n kwargs = {}\n if len(args) > 1:\n kwargs = args[1]\n try:\n if isinstance(kwargs, dict):\n result = options[args[0]](**kwargs)\n else:\n result = options[args[0]](kwargs)\n except KeyError:\n result = args[0]\n except TypeError:\n result = args[0]\n return result\n\n\ndef getFunc(key, name):\n def func(self, info, **kwargs):\n if hasattr(self, key):\n return getattr(self, key)\n return self.get(key)\n\n func.__name__ = name\n return func\n\n\ndef get_graphene_types(values):\n return {key[0]: get_graphene_type(*key[1:]) for key in values}\n\n\ndef createGrapheneClass(className, values):\n \"\"\"This class helps in creating graphene models in which the\n keys are the fields and the values are what the resolve function\n returns\n \"\"\"\n class_fields = {key[0]: get_graphene_type(*key[1:]) for key in values}\n cls = type(className, (graphene.ObjectType, ), class_fields)\n for key in values:\n if type(key) == tuple and len(key) > 2:\n name = f\"resolve_{key[0]}\"\n func = lambda self, info, **kwargs: key[-1](self)\n func.__name__ = name\n else:\n name = f\"resolve_{key[0]}\"\n func = getFunc(key[0], name)\n setattr(cls, name, func)\n return cls\n\n\ndef createGrapheneInputClass(className, values):\n class_fields = {key[0]: get_graphene_type(*key[1:]) for key in values}\n cls = type(className, (graphene.InputObjectType, ), class_fields)\n return cls\n\n\ndef dict_from_list(obj, _list):\n result = {}\n for key in _list:\n if isinstance(key, tuple):\n result[key[0]] = getattr(obj, key[1])\n else:\n if isinstance(key, dict):\n new_key = list(key.keys())[0]\n new_value = list(key.values())[0]\n result[new_key] = obj.get(new_key, new_value)\n else:\n if hasattr(obj, key):\n result[key] = getattr(obj, key)\n else:\n result[key] = obj.get(key)\n return result\n\n\nclass BaseMutation(object):\n fields = []\n form_fields = {}\n service_func_name = \"\"\n stop_point = \"\"\n\n def build_form_fields(self,\n key,\n fields=None,\n name=None,\n is_list=False,\n **kwargs):\n for i in [fields]:\n if not i:\n raise NotImplementedError(f\"Missing parameter for {key} \")\n if not name:\n return (key, get_graphene_type(*fields, kwargs))\n klass = type(name, (graphene.InputObjectType, ),\n get_graphene_types(fields))\n if is_list:\n return (key, graphene.List(klass, **kwargs))\n return (key, klass(**kwargs))\n\n def get_form_fields(self):\n result = []\n for key, values in self.form_fields.items():\n if isinstance(values, dict) and values.get(\"fields\"):\n result.append(self.build_form_fields(key, **values))\n else:\n result.append((key, values))\n return dict(result)\n\n def get_fields(self):\n return get_graphene_types(self.fields)\n\n def get_form(self):\n raise NotImplementedError\n\n def callback(self, *args, **kwargs):\n return self.form.save(*args, **kwargs)\n\n def mutate(self, *args, **kwargs):\n [klass, _, info] = args\n return authenticated_result(klass, info, self.callback, **kwargs)\n\n def service_action(self, user, param, fields=None, no_error=False):\n new_data = (param, )\n if isinstance(param, tuple):\n new_data = param\n ss = services.NewTutorApplicationService(user)\n func = getattr(ss, self.service_func_name)\n errors = None\n result = func(*new_data)\n\n self.update_stop_points(ss, user)\n\n data = {}\n if isinstance(result, tuple):\n user = result[0]\n errors = result[1]\n data = result\n if fields:\n data = UserToDict(user).to_dict()\n if isinstance(fields, list):\n data = dict_from_list(data, fields)\n if fields == \"user\":\n data = {\"user\": data}\n if no_error:\n return {**data}, result[1]\n return {**data, \"errors\": errors}\n\n @classmethod\n def Field(cls):\n m_instance = cls()\n klass = type(\n cls.__name__,\n (graphene.Mutation, ),\n {\n **m_instance.get_fields(),\n \"Arguments\":\n type(\"Arguments\", (), m_instance.get_form_fields()),\n \"mutate\":\n m_instance.mutate,\n },\n )\n instance = klass.Field()\n instance.resolver = lambda *args, **kwargs: m_instance.mutate(\n klass, *args, **kwargs\n )\n return instance\n\n\ndef authenticated_result(cls, info, callback, **kwargs):\n result = callback(info, **kwargs)\n return cls(**result)\n","sub_path":"graphene_utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"54002954","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n___author___ = 'Steven Emerson'\n___date___ = '2020/8/31 9:25'\n\nimport logging\nimport threading\nfrom time import sleep, ctime\n\nlogging.basicConfig(level=logging.INFO)\nloops = [2, 4]\n\n\ndef loop(nloop, nesc):\n logging.info(\"start loop \" + str(nloop) + \"at\" + ctime())\n sleep(nesc)\n logging.info(\"end loop \" + str(nloop) + \"at\" + ctime())\n\n\ndef main():\n logging.info(\"start all at \" + ctime())\n threads = []\n nloops = range(len(loops))\n for i in nloops:\n t = threading.Thread(target=loop, args=(i, loop[i]))\n threads.append(t)\n for i in nloops:\n threads[i].start()\n for i in nloops:\n threads[i].join()\n logging.info(\"end all at \" + ctime())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"exercise_case/threading_demo.py","file_name":"threading_demo.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"435971202","text":"from flask import request, jsonify\nfrom flask_restplus import Resource, fields\nfrom app import db, api, app\nfrom app.models import Movement, Budget\nimport traceback\nfrom datetime import datetime\n\nmovements = api.namespace('api/v1.0/movements', description ='CRUD operation for movements')\n\nbudgetModel = movements.model('budgetModel', {\n 'name' : fields.String(required=True, validate=True)\n }\n)\n\nmovementModel = movements.model('movementModel', {\n 'amount' : fields.Float(required=True, validate=True),\n 'date' : fields.DateTime(required=False, validate=True),\n 'entry' : fields.Boolean(required=True, validate=True),\n 'description' : fields.String(required=False, validate=True)\n }\n)\n\nresp = {200: 'Success', 400: 'movement already in db', 400: 'Content not allowed', \\\n 400: 'Payload too large', 500: 'Server Error'}\n\n\n@movements.route('/')\nclass Budget_Requests(Resource):\n @movements.expect(budgetModel)\n def post(self,id_user):\n \"\"\"Post a user budget\"\"\"\n data = request.get_json()\n budget = Budget(id_user=id_user, name=data.get('name'))\n db.session.add(budget)\n db.session.commit()\n return jsonify(budget.asDict())\n\n\n@movements.route('//')\nclass Movement_Requests(Resource):\n @movements.expect(movementModel)\n def post(self,id_user,id_budget):\n budget = Budget.query.get(id_budget)\n if not budget:\n return 'budget not found', 404\n if id_user != budget.id_user:\n return 'not allow', 406\n data = request.get_json()\n amount = data.get('amount') \n date = data.get('date')\n entry = data.get('entry')\n description = data.get('description')\n date = datetime.strptime(date, '%d/%m/%Y')\n movement = Movement(id_budget=id_budget, amount=amount, \n date=date, entry=entry, description=description)\n if entry:\n budget.amount += amount\n else:\n budget.amount -= amount\n db.session.add(movement)\n db.session.commit()\n return jsonify(movement.asDict())\n\n def get(self,id_user,id_budget):\n budget = Budget.query.get(id_budget)\n if not budget:\n return 'budget not found', 404\n response={budget.amount : []}\n print(budget.movements[0].asDict())\n for movement in budget.movements:\n response[budget.amount]+= [movement.amount, movement.date, movement.entry, movement.description]\n print(movement.asDict())\n return jsonify(response)","sub_path":"Movements/app/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"98629766","text":"from __future__ import absolute_import\nfrom __future__ import print_function\nfrom .util import get_data\nimport unittest\nimport schema_salad.ref_resolver\nimport schema_salad.main\nimport schema_salad.schema\nfrom schema_salad.jsonld_context import makerdf\nimport rdflib\nimport ruamel.yaml\nimport json\nimport os\nfrom schema_salad.sourceline import cmap, SourceLine\n\ntry:\n from ruamel.yaml import CSafeLoader as SafeLoader\nexcept ImportError:\n from ruamel.yaml import SafeLoader # type: ignore\n\nfrom ruamel.yaml.comments import CommentedSeq, CommentedMap\n\n\nclass TestSchemas(unittest.TestCase):\n def test_schemas(self):\n loader = schema_salad.ref_resolver.Loader({})\n\n ra, _ = loader.resolve_all(cmap({\n u\"$schemas\": [schema_salad.ref_resolver.file_uri(get_data(\"tests/EDAM.owl\"))],\n u\"$namespaces\": {u\"edam\": u\"http://edamontology.org/\"},\n u\"edam:has_format\": u\"edam:format_1915\"\n }), \"\")\n\n self.assertEqual({\n u\"$schemas\": [schema_salad.ref_resolver.file_uri(get_data(\"tests/EDAM.owl\"))],\n u\"$namespaces\": {u\"edam\": u\"http://edamontology.org/\"},\n u'http://edamontology.org/has_format': u'http://edamontology.org/format_1915'\n }, ra)\n\n # def test_domain(self):\n # l = schema_salad.ref_resolver.Loader({})\n\n # l.idx[\"http://example.com/stuff\"] = {\n # \"$schemas\": [\"tests/EDAM.owl\"],\n # \"$namespaces\": {\"edam\": \"http://edamontology.org/\"},\n # }\n\n # ra, _ = l.resolve_all({\n # \"$import\": \"http://example.com/stuff\",\n # \"edam:has_format\": \"edam:format_1915\"\n # }, \"\")\n\n # self.assertEqual(ra, {\n # \"$schemas\": [\"tests/EDAM.owl\"],\n # \"$namespaces\": {\"edam\": \"http://edamontology.org/\"},\n # 'http://edamontology.org/has_format': 'http://edamontology.org/format_1915'\n # })\n\n def test_self_validate(self):\n self.assertEqual(0, schema_salad.main.main(\n argsl=[get_data(\"metaschema/metaschema.yml\")]))\n self.assertEqual(0, schema_salad.main.main(\n argsl=[get_data(\"metaschema/metaschema.yml\"),\n get_data(\"metaschema/metaschema.yml\")]))\n\n def test_avro_regression(self):\n self.assertEqual(0, schema_salad.main.main(\n argsl=[get_data(\"tests/Process.yml\")]))\n\n def test_jsonld_ctx(self):\n ldr, _, _, _ = schema_salad.schema.load_schema(cmap({\n \"$base\": \"Y\",\n \"name\": \"X\",\n \"$namespaces\": {\n \"foo\": \"http://example.com/foo#\"\n },\n \"$graph\": [{\n \"name\": \"ExampleType\",\n \"type\": \"enum\",\n \"symbols\": [\"asym\", \"bsym\"]}]\n }))\n\n ra, _ = ldr.resolve_all(cmap({\"foo:bar\": \"asym\"}), \"X\")\n\n self.assertEqual(ra, {\n 'http://example.com/foo#bar': 'asym'\n })\n\n def test_idmap(self):\n ldr = schema_salad.ref_resolver.Loader({})\n ldr.add_context({\n \"inputs\": {\n \"@id\": \"http://example.com/inputs\",\n \"mapSubject\": \"id\",\n \"mapPredicate\": \"a\"\n },\n \"outputs\": {\n \"@type\": \"@id\",\n \"identity\": True,\n },\n \"id\": \"@id\"})\n\n ra, _ = ldr.resolve_all(cmap({\n \"id\": \"stuff\",\n \"inputs\": {\n \"zip\": 1,\n \"zing\": 2\n },\n \"outputs\": [\"out\"],\n \"other\": {\n 'n': 9\n }\n }), \"http://example2.com/\")\n\n self.assertEqual(\"http://example2.com/#stuff\", ra[\"id\"])\n for item in ra[\"inputs\"]:\n if item[\"a\"] == 2:\n self.assertEqual(\n 'http://example2.com/#stuff/zing', item[\"id\"])\n else:\n self.assertEqual('http://example2.com/#stuff/zip', item[\"id\"])\n self.assertEqual(['http://example2.com/#stuff/out'], ra['outputs'])\n self.assertEqual({'n': 9}, ra['other'])\n\n def test_scoped_ref(self):\n ldr = schema_salad.ref_resolver.Loader({})\n ldr.add_context({\n \"scatter\": {\n \"@type\": \"@id\",\n \"refScope\": 0,\n },\n \"source\": {\n \"@type\": \"@id\",\n \"refScope\": 2,\n },\n \"in\": {\n \"mapSubject\": \"id\",\n \"mapPredicate\": \"source\"\n },\n \"out\": {\n \"@type\": \"@id\",\n \"identity\": True\n },\n \"inputs\": {\n \"mapSubject\": \"id\",\n \"mapPredicate\": \"type\"\n },\n \"outputs\": {\n \"mapSubject\": \"id\",\n },\n \"steps\": {\n \"mapSubject\": \"id\"\n },\n \"id\": \"@id\"})\n\n ra, _ = ldr.resolve_all(cmap({\n \"inputs\": {\n \"inp\": \"string\",\n \"inp2\": \"string\"\n },\n \"outputs\": {\n \"out\": {\n \"type\": \"string\",\n \"source\": \"step2/out\"\n }\n },\n \"steps\": {\n \"step1\": {\n \"in\": {\n \"inp\": \"inp\",\n \"inp2\": \"#inp2\",\n \"inp3\": [\"inp\", \"inp2\"]\n },\n \"out\": [\"out\"],\n \"scatter\": \"inp\"\n },\n \"step2\": {\n \"in\": {\n \"inp\": \"step1/out\"\n },\n \"scatter\": \"inp\",\n \"out\": [\"out\"]\n }\n }\n }), \"http://example2.com/\")\n\n self.assertEqual(\n {'inputs': [{\n 'id': 'http://example2.com/#inp',\n 'type': 'string'\n }, {\n 'id': 'http://example2.com/#inp2',\n 'type': 'string'\n }],\n 'outputs': [{\n 'id': 'http://example2.com/#out',\n 'type': 'string',\n 'source': 'http://example2.com/#step2/out'\n }],\n 'steps': [{\n 'id': 'http://example2.com/#step1',\n 'scatter': 'http://example2.com/#step1/inp',\n 'in': [{\n 'id': 'http://example2.com/#step1/inp',\n 'source': 'http://example2.com/#inp'\n }, {\n 'id': 'http://example2.com/#step1/inp2',\n 'source': 'http://example2.com/#inp2'\n }, {\n 'id': 'http://example2.com/#step1/inp3',\n 'source': ['http://example2.com/#inp', 'http://example2.com/#inp2']\n }],\n \"out\": [\"http://example2.com/#step1/out\"],\n }, {\n 'id': 'http://example2.com/#step2',\n 'scatter': 'http://example2.com/#step2/inp',\n 'in': [{\n 'id': 'http://example2.com/#step2/inp',\n 'source': 'http://example2.com/#step1/out'\n }],\n \"out\": [\"http://example2.com/#step2/out\"],\n }]\n }, ra)\n\n def test_examples(self):\n for a in [\"field_name\", \"ident_res\", \"link_res\", \"vocab_res\"]:\n ldr, _, _, _ = schema_salad.schema.load_schema(\n get_data(\"metaschema/%s_schema.yml\" % a))\n with open(get_data(\"metaschema/%s_src.yml\" % a)) as src_fp:\n src = ldr.resolve_all(\n ruamel.yaml.round_trip_load(src_fp), \"\",\n checklinks=False)[0]\n with open(get_data(\"metaschema/%s_proc.yml\" % a)) as src_proc:\n proc = ruamel.yaml.safe_load(src_proc)\n self.assertEqual(proc, src)\n\n def test_yaml_float_test(self):\n self.assertEqual(ruamel.yaml.safe_load(\"float-test: 2e-10\")[\"float-test\"],\n 2e-10)\n\n def test_typedsl_ref(self):\n ldr = schema_salad.ref_resolver.Loader({})\n ldr.add_context({\n \"File\": \"http://example.com/File\",\n \"null\": \"http://example.com/null\",\n \"array\": \"http://example.com/array\",\n \"type\": {\n \"@type\": \"@vocab\",\n \"typeDSL\": True\n }\n })\n\n ra, _ = ldr.resolve_all(cmap({\"type\": \"File\"}), \"\")\n self.assertEqual({'type': 'File'}, ra)\n\n ra, _ = ldr.resolve_all(cmap({\"type\": \"File?\"}), \"\")\n self.assertEqual({'type': ['null', 'File']}, ra)\n\n ra, _ = ldr.resolve_all(cmap({\"type\": \"File[]\"}), \"\")\n self.assertEqual({'type': {'items': 'File', 'type': 'array'}}, ra)\n\n ra, _ = ldr.resolve_all(cmap({\"type\": \"File[]?\"}), \"\")\n self.assertEqual(\n {'type': ['null', {'items': 'File', 'type': 'array'}]}, ra)\n\n def test_scoped_id(self):\n ldr = schema_salad.ref_resolver.Loader({})\n ctx = {\n \"id\": \"@id\",\n \"location\": {\n \"@id\": \"@id\",\n \"@type\": \"@id\"\n },\n \"bar\": \"http://example.com/bar\",\n \"ex\": \"http://example.com/\"\n }\n ldr.add_context(ctx)\n\n ra, _ = ldr.resolve_all(cmap({\n \"id\": \"foo\",\n \"bar\": {\n \"id\": \"baz\"\n }\n }), \"http://example.com\")\n self.assertEqual({'id': 'http://example.com/#foo',\n 'bar': {\n 'id': 'http://example.com/#foo/baz'},\n }, ra)\n\n g = makerdf(None, ra, ctx)\n print(g.serialize(format=\"n3\"))\n\n ra, _ = ldr.resolve_all(cmap({\n \"location\": \"foo\",\n \"bar\": {\n \"location\": \"baz\"\n }\n }), \"http://example.com\", checklinks=False)\n self.assertEqual({'location': 'http://example.com/foo',\n 'bar': {\n 'location': 'http://example.com/baz'},\n }, ra)\n\n g = makerdf(None, ra, ctx)\n print(g.serialize(format=\"n3\"))\n\n ra, _ = ldr.resolve_all(cmap({\n \"id\": \"foo\",\n \"bar\": {\n \"location\": \"baz\"\n }\n }), \"http://example.com\", checklinks=False)\n self.assertEqual({'id': 'http://example.com/#foo',\n 'bar': {\n 'location': 'http://example.com/baz'},\n }, ra)\n\n g = makerdf(None, ra, ctx)\n print(g.serialize(format=\"n3\"))\n\n ra, _ = ldr.resolve_all(cmap({\n \"location\": \"foo\",\n \"bar\": {\n \"id\": \"baz\"\n }\n }), \"http://example.com\", checklinks=False)\n self.assertEqual({'location': 'http://example.com/foo',\n 'bar': {\n 'id': 'http://example.com/#baz'},\n }, ra)\n\n g = makerdf(None, ra, ctx)\n print(g.serialize(format=\"n3\"))\n\n def test_subscoped_id(self):\n ldr = schema_salad.ref_resolver.Loader({})\n ctx = {\n \"id\": \"@id\",\n \"bar\": {\n \"subscope\": \"bar\",\n }\n }\n ldr.add_context(ctx)\n\n ra, _ = ldr.resolve_all(cmap({\n \"id\": \"foo\",\n \"bar\": {\n \"id\": \"baz\"\n }\n }), \"http://example.com\")\n self.assertEqual({'id': 'http://example.com/#foo',\n 'bar': {\n 'id': 'http://example.com/#foo/bar/baz'},\n }, ra)\n\n\n def test_mixin(self):\n base_url = schema_salad.ref_resolver.file_uri(os.path.join(os.getcwd(), \"tests\"))\n ldr = schema_salad.ref_resolver.Loader({})\n ra = ldr.resolve_ref(cmap({\"$mixin\": get_data(\"tests/mixin.yml\"), \"one\": \"five\"}),\n base_url=base_url)\n self.assertEqual({'id': 'four', 'one': 'five'}, ra[0])\n ldr = schema_salad.ref_resolver.Loader({\"id\": \"@id\"})\n\n ra = ldr.resolve_all(cmap([{\n \"id\": \"a\",\n \"m\": {\"$mixin\": get_data(\"tests/mixin.yml\")}\n }, {\n \"id\": \"b\",\n \"m\": {\"$mixin\": get_data(\"tests/mixin.yml\")}\n }]), base_url=base_url)\n self.assertEqual([{\n 'id': base_url + '#a',\n 'm': {\n 'id': base_url + u'#a/four',\n 'one': 'two'\n },\n }, {\n 'id': base_url + '#b',\n 'm': {\n 'id': base_url + u'#b/four',\n 'one': 'two'}\n }], ra[0])\n\n def test_fragment(self):\n ldr = schema_salad.ref_resolver.Loader({\"id\": \"@id\"})\n b, _ = ldr.resolve_ref(get_data(\"tests/frag.yml#foo2\"))\n self.assertEqual({\"id\": b[\"id\"], \"bar\":\"b2\"}, b)\n\n def test_file_uri(self):\n # Note: this test probably won't pass on Windows. Someone with a\n # windows box should add an alternate test.\n self.assertEqual(\"file:///foo/bar%20baz/quux\", schema_salad.ref_resolver.file_uri(\"/foo/bar baz/quux\"))\n self.assertEqual(os.path.normpath(\"/foo/bar baz/quux\"),\n schema_salad.ref_resolver.uri_file_path(\"file:///foo/bar%20baz/quux\"))\n self.assertEqual(\"file:///foo/bar%20baz/quux%23zing%20zong\", schema_salad.ref_resolver.file_uri(\"/foo/bar baz/quux#zing zong\"))\n self.assertEqual(\"file:///foo/bar%20baz/quux#zing%20zong\", schema_salad.ref_resolver.file_uri(\"/foo/bar baz/quux#zing zong\", split_frag=True))\n self.assertEqual(os.path.normpath(\"/foo/bar baz/quux#zing zong\"),\n schema_salad.ref_resolver.uri_file_path(\"file:///foo/bar%20baz/quux#zing%20zong\"))\n\n\nclass SourceLineTest(unittest.TestCase):\n def test_sourceline(self):\n ldr = schema_salad.ref_resolver.Loader({\"id\": \"@id\"})\n b, _ = ldr.resolve_ref(get_data(\"tests/frag.yml\"))\n\n class TestExp(Exception):\n pass\n\n try:\n with SourceLine(b, 1, TestExp, False):\n raise Exception(\"Whoops\")\n except TestExp as e:\n self.assertTrue(str(e).endswith(\"frag.yml:3:3: Whoops\"))\n except Exception:\n self.assertFail()\n\n try:\n with SourceLine(b, 1, TestExp, True):\n raise Exception(\"Whoops\")\n except TestExp as e:\n self.assertTrue(str(e).splitlines()[0].endswith(\"frag.yml:3:3: Traceback (most recent call last):\"))\n except Exception:\n self.assertFail()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"cwltool/schemas/v1.1.0-dev1/salad/schema_salad/tests/test_examples.py","file_name":"test_examples.py","file_ext":"py","file_size_in_byte":14748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"567152437","text":"from pickle import FALSE, TRUE\nfrom manim.utils.color import DARK_BLUE, LIGHT_GRAY\nfrom numpy.lib.nanfunctions import _nanmedian1d\nfrom manim import *\nimport numpy as np\nimport math\nimport random\n\nfrom pyglet.com import pIUnknown\n\nX1 = 1;\n#X2 = (random. randint(1,50))*10;\nX3 = 5;\n#X4 = random. randint(1,20);\nX5 = 2;\n\nvv = X1 + X5*X3;\nA2 = X3*X1;\nA1 = 0.5*X3*(vv-X1);\n\nclass Figma_s(Scene):\n def construct(self):\n # axes\n axes = Axes(\n x_range=[0, int(X3+3),1],\n y_range=[0, int(vv+3), 2],\n x_length=12,\n y_length=6,\n \n ).set_stroke(WHITE).to_corner(DL, buff=1)\n axes.add_coordinates()\n \n #axes_lables = axes.get_axis_labels(x_label_tex=\"t(sec)\", y_label_tex=\"v(m/s)\",).set_color(WHITE)\n y_label = axes.get_y_axis_label(\"v(m/s)\", edge=UP, direction=LEFT, buff=0.9)\n x_label = axes.get_x_axis_label(\"t(sec)\", edge=RIGHT, direction=RIGHT, buff=0.3)\n axes_lables = VGroup(x_label.set_color(BLUE), y_label.set_color(BLUE))\n #self.play(\n # Write(axes, run_time=3) \n #)\n self.add(axes, axes_lables)\n i = 0;\n j = 0;\n while i < vv+3: \n h1 = Line(start= (axes.c2p(0, i)), end= (axes.c2p(X3+3, i))).set_stroke(BLUE).set_opacity(0.2)\n self.add(h1)\n i = i+1;\n while j < X3+3: \n h2 = Line(start= (axes.c2p(j, 0)), end= (axes.c2p(j, vv+3))).set_stroke(BLUE).set_opacity(0.2)\n self.add(h2)\n j = j+1;\n\n \n self.play(\n Write(axes, run_time=3) \n )\n #initial velocity text\n eqn = VGroup(\n Tex(r\"Given: initial velocity = \", str(X1), r\"m/s\").scale(0.9),\n Tex(r\"So at t = 0 s, u = }\", str(X1), r\"m/s\").scale(0.9),\n Tex(r\"Hence co-ordinates of point on the axes : (0,\",str(X1),\")\").scale(0.9),\n )\n self.play(Write(eqn[0][0]))\n self.play(Write(eqn[0][1].set_color(GREEN).next_to(eqn[0][0],RIGHT)))\n self.play(Write(eqn[0][2].next_to(eqn[0][1],RIGHT)))\n self.wait()\n\n self.play(Write(eqn[1].next_to(eqn[0],DOWN)))\n self.wait()\n self.play(Write(eqn[2].next_to(eqn[1],DOWN)))\n self.wait()\n self.play(FadeOut(eqn))\n #initial velocity graph\n dot = Dot(color=GREEN)\n h_line = always_redraw(lambda: axes.get_horizontal_line(dot.get_left()))\n v_line = always_redraw(lambda: axes.get_vertical_line(dot.get_bottom()))\n\n self.play(\n FadeIn(h_line),\n FadeIn(v_line),\n )\n self.play(dot.animate.move_to(axes.c2p(0, X1)))\n self.wait()\n\n # accleration text\n eqn = VGroup(\n Tex(r\"Given: acceleration = \", str(X5), r\"$m/s^2$\"),\n Tex(r\"Slope of the velocity-time curve gives accleration\"),\n Tex(r\"Hence slope of the curve is \",str(X5),\"=\",str(X5),\"/1\"),\n )\n self.play(Write(eqn[0][0]))\n self.play(Write(eqn[0][1].set_color(YELLOW).next_to(eqn[0][0],RIGHT)))\n self.play(Write(eqn[0][2].next_to(eqn[0][1],RIGHT)))\n self.wait()\n\n self.play(Write(eqn[1].scale(0.9).next_to(eqn[0],DOWN)))\n self.wait()\n self.play(Write(eqn[2].scale(0.9).next_to(eqn[1],DOWN)))\n self.wait()\n self.play(FadeOut(eqn))\n\n # accleration graph\n\n dot2 = Dot(color=GREY).move_to(axes.c2p(1, int(X1+X5)))\n dots = Dot(color=BLACK).move_to(axes.c2p(1, X1))\n sv_line = VGroup(Line(dots.get_center(), dot2.get_center()).set_stroke(WHITE))\n sh_line = VGroup(Line(dot.get_center(), dots.get_center()).set_stroke(WHITE))\n \n # updater\n braceh = Brace(sh_line)\n\n bracev = Brace(sv_line, direction = RIGHT)\n\n text = label = Text(\"1\").set_stroke(YELLOW).scale(1/2)\n labelv = Tex(str(X5)).set_stroke(YELLOW)\n always(label.next_to, braceh, DOWN)\n self.add(sh_line, braceh, label)\n always(labelv.next_to, bracev, RIGHT)\n gg = self.add(sh_line, bracev, labelv)\n \n self.play(\n FadeIn(sh_line),\n FadeIn(sv_line),\n )\n self.wait(3)\n refline = VGroup(DashedLine(dot.get_center(), dot2.get_center()).set_stroke(YELLOW_E))\n self.add(dot, dot2, refline)\n self.play(FadeIn(refline))\n self.wait(2)\n\n #time text\n eqn = VGroup(\n Tex(r\"Given: time of motion = \", str(X3), r\" s\"),\n )\n\n self.play(Write(eqn[0][1].set_color(PINK).next_to(eqn[0][0],RIGHT)))\n self.play(Write(eqn[0][2].next_to(eqn[0][1],RIGHT)))\n self.wait()\n self.play(FadeOut(eqn))\n\n #time graph\n dot3 = Dot(color=PINK)\n ddot = Dot(color=BLACK).move_to(axes.c2p(X3,vv+1))\n self.play(dot3.animate.move_to(axes.c2p(0, 0)))\n self.wait()\n self.play(dot3.animate.move_to(axes.c2p(X3, 0)))\n self.wait()\n\n \n v_line = VGroup(DashedLine(dot3.get_center(), ddot.get_center()).set_stroke(PINK))\n \n self.play(\n FadeIn(v_line.set_stroke(PINK))\n )\n self.add(v_line)\n\n\n # final point\n h_line = always_redraw(lambda: axes.get_horizontal_line(dot3.get_left()))\n h_line = h_line.set_stroke(LIGHT_PINK)\n \n dot4 = Dot(color=PINK).move_to(axes.c2p(X3, vv))\n dot5 = Dot(color=PINK).move_to(axes.c2p(0, vv))\n\n fline = VGroup(Line(dot.get_center(), dot4.get_center()).set_stroke(BLUE_E))\n self.add(dot, dot4, fline)\n f2line = VGroup(DashedLine(dot4.get_center(), dot5.get_center()).set_stroke(GREEN_A))\n #self.add(fline, v_line, dot5, f2line)\n self.play(\n FadeIn(fline),\n FadeIn(h_line),\n run_time = 5\n )\n\n\n #area\n self.play(FadeOut(braceh, bracev, labelv, label))\n curve1 = axes.get_graph(lambda x: (X1) + (X5)*x , x_range=[0, X3+2], color=BLUE_C)\n curve2 = axes.get_graph(lambda x: (X1) , x_range=[0, X3+2], color=BLUE_C)\n area = axes.get_area(curve1, [0, X3], color=GREEN, opacity=0.5)\n area1 = axes.get_area(curve1, [0, X3], bounded_graph=curve2, color=LIGHT_BROWN, opacity=0.6)\n area2 = axes.get_area(curve2, [0, X3], color=YELLOW_E, opacity=0.6)\n\n \n self.wait(2)\n self.play(FadeIn(area1), FadeIn(area1))\n self.play(FadeOut(h_line))\n\n #area braces\n\n brace_a11 = Brace(area1, direction = RIGHT).set_color(BLUE)\n brace_a12 = Brace(area1, direction = UP).set_color(BLUE)\n brace_a21 = Brace(area2, direction = RIGHT).set_color(BLUE)\n brace_a22 = Brace(area2, direction = UP).set_color(BLUE)\n\n label_a11 = brace_a11.get_text(str(vv-X1)).set_color(BLUE)\n label_a12 = brace_a12.get_text(str(X3)).set_color(BLUE)\n label_a21 = brace_a21.get_text(str(X1)).set_color(BLUE)\n label_a22 = brace_a22.get_text(str(X3)).set_color(BLUE)\n\n #area text1\n eqn = VGroup(\n Tex(r\"Area under\", r\" v-t\", r\" curve gives displacemet covered in the given time interval\").scale(0.6),\n Tex(r\"lets highlight the region for which area needs to be found\").scale(0.6),\n Tex(r\"Total area =\", r\"$a_{1}$\", \" + \", r\"$a_{2}$\").scale(0.6),\n Tex(r\"$a_{1}$\",r\"$ = \\frac{1}{2} \\times base \\times height $\", ).scale(0.6),\n Tex(r\"$a_{1}$\",r\"$ = \\frac{1}{2} \\times$\",str(vv-X1), r\"$\\times$\", str(X3), r\" = \", str(A1)).scale(0.6),\n\n Tex(r\"$a_{2}$\",r\"$= length \\times breadth$\", ).scale(0.6),\n Tex(r\"$a_{1}$\",r\" = \", str(X1), r\"$\\times $\", str(X3), r\" = \", str(A2)).scale(0.6),\n\n Tex(r\"Total area = \", str(A1+A2)).scale(0.6),\n Tex(r\"Hence, displacemet covered = \", str(A1+A2), r\" m\").scale(0.6),\n\n #Tex(r\"Total area =\", str(A1), r\" + \", str(A1)).scale(0.6)\n \n )\n # calcuation animation\n #Area shading\n self.play(Write(eqn[0].move_to(UP)))\n self.wait(2)\n self.play(FadeOut(eqn[0]))\n self.play(Write(eqn[1].move_to(UP)))\n self.play(FadeOut(eqn[1]))\n self.play(Create(area))\n self.wait(2)\n #Breaking into two\n eqn[2][1].set_color(GREEN)\n eqn[2][3].set_color(YELLOW_E)\n self.play(Write(eqn[2].move_to(UP)))\n self.play(FadeIn(area1), FadeIn(area2))\n self.add(eqn[2], area1, area2)\n #garea = self.add(area1, area2)\n #a1\n #self.play(Transform(area1, area1.set_color(GREEN).set_opacity(0.5)) )\n #self.play(Transform(area2, area2.set_opacity(0.2)) )\n#############\n self.add(area1, brace_a11, brace_a12, label_a11,label_a12 )\n self.play(Write(eqn[3].next_to(eqn[2], DOWN)))\n self.wait(2)\n self.play(Write(eqn[4].next_to(eqn[3], DOWN)))\n self.wait(2)\n self.play(FadeOut(eqn[3], eqn[4]))\n self.play(FadeOut(area1, brace_a11, label_a11, brace_a12, label_a12))\n #self.play(Transform(area1, area1.set_color(LIGHT_BROWN)) )\n self.wait()\n #a2\n #self.play(Transform(area2, area2.set_color(GREEN).set_opacity(0.5)) )\n #self.play(Transform(area1, area1.set_opacity(0.2)) )\n################# \n self.add(area2, brace_a21, brace_a22,label_a21, label_a22)\n self.play(Write(eqn[5].next_to(eqn[2], DOWN)))\n self.wait()\n self.play(Write(eqn[6].next_to(eqn[5], DOWN)))\n self.wait()\n self.play(FadeOut(eqn[5], eqn[6]))\n self.play(FadeOut(area2, brace_a21, label_a21, brace_a22, label_a22))\n #self.play(Transform(area2, area2.set_color(YELLOW_E)) )\n self.wait()\n #total\n #self.play(Transform(eqn[2], eqn[9]))\n #self.play(Transform(eqn[2][3], Tex(str(A2)).scale(0.6)))\n self.play(FadeOut(area1, area2))\n self.play(FadeIn(area))\n self.play(Write(eqn[7].next_to(eqn[2], DOWN)))\n self.wait()\n self.play(Write(eqn[8].next_to(eqn[7], DOWN)))\n self.wait()\n","sub_path":"manim-main/Autosolver/figma_s_area.py","file_name":"figma_s_area.py","file_ext":"py","file_size_in_byte":10006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"642598432","text":"#!/usr/bin/env python\nimport os\nimport struct\nimport binascii\nimport argparse\n\ndef param_to_data_string(param):\n # strip leading '0x'\n param = param.replace('0x','')\n # pad to even number of characters (required by binascii)\n if len(param) % 2 == 1:\n param = '0' + param\n\n return binascii.a2b_hex(param)\n\ndef generate_file_header(indicator, headers):\n header_bytes = indicator\n for header in headers:\n header_bytes += chr(len(header))\n for item in header:\n header_bytes += chr(len(item)) + item\n return header_bytes\n\ndef main():\n # example: python rwd-builder.py --can-address 0x18DA30F1 --supported-versions 12345-XXX-A030 12345-XXX-A040 --security-key 0x000100020003 0x000100020003 --encryption-key 0x0a0b0c --encrypted-file 12345-YYY-A030-M1.enc --start-address 0x0 --data-size 0x10000\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--can-address\", required=True, help=\"CAN address of ECU (e.g. 0x18DA30F1)\")\n parser.add_argument(\"--supported-versions\", required=True, nargs='+', help=\"software version(s) supported (e.g. 39990-TLA-A030\")\n parser.add_argument(\"--security-keys\", required=True, nargs='+', help=\"security key for each supported software version (e.g. 0x000100020003\")\n parser.add_argument(\"--encryption-key\", required=True, help=\"firmware encryption key (e.g. 0x010203)\")\n parser.add_argument(\"--encrypted-file\", required=True, help=\"encrypted firmware file (e.g. test.bin)\")\n parser.add_argument(\"--start-address\", required=True, help=\"address to start at in firmware file (e.g. 0x00)\")\n parser.add_argument(\"--data-size\", required=True, help=\"number of bytes to copy after start address (e.g. 0x10000)\")\n args = parser.parse_args()\n\n # convert from string to hex\n can_addr = param_to_data_string(args.can_address)\n fw_versions = map(lambda x: x.ljust(16, '\\x00'), args.supported_versions)\n sa_keys = map(param_to_data_string, args.security_keys)\n fw_key = param_to_data_string(args.encryption_key)\n start_addr = param_to_data_string(args.start_address)\n data_size = param_to_data_string(args.data_size)\n\n f_dir = os.path.dirname(args.encrypted_file)\n f_base = os.path.splitext(os.path.basename(args.encrypted_file))[0]\n rwd_file = os.path.join(f_dir, f_base + '.rwd')\n\n indicator = '\\x5A\\x0D\\x0A' # CAN format\n headers = [\n ['\\x00'], # always zero\n [], # always empty\n [can_addr[2]], # significant byte in 29 bit addr (0x18da__f1)\n fw_versions, # previous firmware version(s)\n sa_keys, # security access key (one per prev firmware version)\n [fw_key], # firmware encryption key\n ]\n for i in range(len(headers)):\n print('[{}]: {}'.format(i, headers[i]))\n print('start = {} len = {}'.format(args.start_address, args.data_size))\n\n rwd_header_bytes = generate_file_header(indicator, headers)\n with open(args.encrypted_file, 'rb') as f:\n rwd_fw_bytes = f.read()\n\n rwd_start_len = start_addr.rjust(4, '\\x00') + data_size.rjust(4, '\\x00')\n file_checksum = sum(map(ord, rwd_header_bytes+rwd_start_len+rwd_fw_bytes)) & 0xFFFFFFFF\n print('file checksum: {}'.format(hex(file_checksum)))\n rwd_checksum_bytes = struct.pack(' 0:\n print(line.replace(group[0], str(new)), end='')\n else:\n print(line, end='')\n\n\n def put_obj(self, key, new):\n with fileinput.FileInput(self.file_path, inplace=True) as file:\n for line in file:\n group = self.find_obj(line, key)\n if len(group) > 0:\n print(line.replace(group[0], str(new)), end='')\n else:\n print(line, end='')\n\n\n def put_bool(self, key, new):\n with fileinput.FileInput(self.file_path, inplace=True) as file:\n for line in file:\n group = self.find_obj(line, key)\n if len(group) > 0:\n print(line.replace(group[0], str(new).lower()), end='')\n else:\n print(line, end='')\n\n # CONFIGURABLE BY APPLICATION\n def configure_by_app(self, config: DriverApplication):\n self.put_string(TENANT, config.tenant_name)\n self.put_string(HOST, config.host)\n self.put_string(HOST_NEW, config.new_host)\n self.put_string(CHAT_SERVER, config.chat_host)\n self.put_string(URL_GEOCODE, config.geocode_host)\n self.put_string(SENDER_ID, config.push_key)\n self.put_obj(TYPE_APP, config.app_type)\n self.put_obj(APP_VERSION, config.version_app)\n self.put_bool(USE_SMS_AUTH, config.use_sms_auth)\n\n self.put_bool(USE_WORKER_REG, config.use_worker_reg)\n self.put_string(WORKER_REG_URL, config.worker_reg_url)\n self.put_string(WORKER_REG_DESCRIPTION, config.worker_reg_description)\n self.put_string(WORKER_REG_BUTTON, config.worker_reg_button)\n","sub_path":"builder/lib/script/configurator/driver_configurator.py","file_name":"driver_configurator.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"398119467","text":"# Copyright (c) maiot GmbH 2020. 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\n# or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\"\"\"Pipeline to create data sources\"\"\"\n\nfrom typing import Dict, Text, Any, List\n\nfrom tfx.components.schema_gen.component import SchemaGen\nfrom tfx.components.statistics_gen.component import StatisticsGen\n\nfrom zenml.components import DataGen\nfrom zenml.enums import GDPComponent\nfrom zenml.pipelines import BasePipeline\nfrom zenml.utils.post_training.post_training_utils import \\\n view_statistics, view_schema\n\n\nclass DataPipeline(BasePipeline):\n \"\"\"DataPipeline definition to create datasources.\n\n A DataPipeline is used to create datasources in ZenML. Each data pipeline\n creates a snapshot of the datasource in time. All datasources are consumed\n by different ZenML pipelines like the TrainingPipeline.\n \"\"\"\n PIPELINE_TYPE = 'data'\n\n def get_tfx_component_list(self, config: Dict[Text, Any]) -> List:\n \"\"\"\n Creates a data pipeline out of TFX components.\n\n A data pipeline is used to ingest data from a configured source, e.g.\n local files or cloud storage. In addition, a schema and statistics are\n also computed immediately afterwards for the processed data points.\n\n Args:\n config: Dict. Contains a ZenML configuration used to build the\n data pipeline.\n\n Returns:\n A list of TFX components making up the data pipeline.\n \"\"\"\n data = DataGen(\n name=self.datasource.name,\n source=self.datasource._source,\n source_args=self.datasource._source_args).with_id(\n GDPComponent.DataGen.name\n )\n statistics_data = StatisticsGen(\n examples=data.outputs.examples\n ).with_id(GDPComponent.DataStatistics.name)\n\n schema_data = SchemaGen(\n statistics=statistics_data.outputs.statistics,\n infer_feature_shape=False,\n ).with_id(GDPComponent.DataSchema.name)\n\n return [data, statistics_data, schema_data]\n\n def view_statistics(self, magic: bool = False, port: int = 0):\n \"\"\"\n View statistics for data pipeline in HTML.\n\n Args:\n magic (bool): Creates HTML page if False, else\n creates a notebook cell.\n port (int): Port at which to launch the statistics facet.\n \"\"\"\n uri = self.get_artifacts_uri_by_component(\n GDPComponent.DataStatistics.name)[0]\n view_statistics(uri, magic, port)\n\n def view_schema(self):\n \"\"\"View schema of data flowing in pipeline.\"\"\"\n uri = self.get_artifacts_uri_by_component(\n GDPComponent.DataSchema.name)[0]\n view_schema(uri)\n\n def steps_completed(self) -> bool:\n return True\n","sub_path":"zenml/pipelines/data_pipeline.py","file_name":"data_pipeline.py","file_ext":"py","file_size_in_byte":3273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"264090544","text":"from fasttext_helper import *\nimport xgboost as xg\nimport sklearn\nimport fasttext as ft\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('N', type=int, help='number of models to train')\nargs = parser.parse_args()\nN = args.N\n\nprint('Loading train labels...')\n_, train_y = load_set(TRAIN)\n\nprint('Loading validation labels...')\n_, val_y = load_set(VALIDATION)\n\nprint(f'Reading {N} train predictions...')\nlabels = []\nfor i in range(1, N+1):\n print(f'Reading train predictions from model {i}...')\n labels.append(load_preds(TRAIN_PREDS.format(i), probs=False))\n\nprint('Arranging train predictions for meta-training...')\ntrain_X = np.transpose(np.matrix(labels))\nprint(f'DEBUG: train X is {train_X.shape}')\n\nprint('Training meta-model...')\nclf = xg.XGBClassifier().fit(train_X, train_y) # either logreg or xgboost\n\nprint(f'Reading {N} validation predictions...')\nlabels = []\nfor i in range(1, N+1):\n print(f'Reading validation predictions from model {i}...')\n labels.append(load_preds(VAL_PREDS.format(i), probs=False))\n\nprint('Arranging validation predictions for meta-prediction...')\nval_X = np.transpose(np.matrix(labels))\nprint(f'DEBUG: validation X is {val_X.shape}')\n\nprint('Computing meta-accuracy...')\nval_preds = clf.predict(val_X)\nprint(accuracy(val_preds, val_y))\n\nprint(f'Reading {N} test predictions...')\nlabels = []\nfor i in range(1, N+1):\n print(f'Reading test predictions from model {i}...')\n labels.append(load_preds(TEST_PREDS.format(i), probs=False))\n\nprint('Arranging validation predictions for meta-prediction...')\ntest_X = np.transpose(np.matrix(labels))\nprint(f'DEBUG: test X is {test_X.shape}')\n\nprint('Writing submission...')\ntest_preds = clf.predict(test_X)\nsubmission(test_preds)\n","sub_path":"scripts/fasttext_stacking.py","file_name":"fasttext_stacking.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"165983875","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Author: Leonardo Pistone\n# Copyright 2014 Camptocamp SA\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\nimport datetime as dt\nfrom dateutil.relativedelta import relativedelta\nfrom dateutil.rrule import rrule, MONTHLY\nimport calendar\n\nfrom openerp.osv import orm\nfrom openerp.tools.translate import _\nfrom openerp.tools import DEFAULT_SERVER_DATE_FORMAT as DATE_FORMAT\n\n\nclass CrmToBudgetWizard(orm.TransientModel):\n\n _name = 'crm.to.budget.wizard'\n\n def _line_dates(self, start_date, count):\n for date in rrule(MONTHLY, count=count, bymonthday=1,\n dtstart=start_date):\n yield (date, date + relativedelta(months=1, days=-1))\n\n def do_compute(self, cr, uid, ids, context=None):\n lead_obj = self.pool['crm.lead']\n budget_line_obj = self.pool['budget.line']\n\n lead_ids = context['active_ids']\n\n for lead in lead_obj.browse(cr, uid, lead_ids, context):\n\n if lead.budget_line_ids:\n budget_line_obj.unlink(cr, uid, [\n line.id for line in lead.budget_line_ids\n ], context=context)\n\n if not lead.budget_item_id:\n # we do not raise here because we do not want to revert the\n # deletion of old budget lines\n continue\n\n if not lead.date_deadline:\n raise orm.except_orm(_(u'Error'),\n _(u'The Expected Date must be set'))\n\n if not lead.months:\n raise orm.except_orm(\n _(u'Error'),\n _(u'The Duration in months must be set'))\n\n if not lead.planned_revenue:\n raise orm.except_orm(\n _(u'Error'),\n _(u'The Expected Revenue must be set'))\n\n if not lead.analytic_account_id:\n raise orm.except_orm(\n _(u'Error'),\n _(u'The Analytic Account must be set'))\n\n version = lead.company_id.budget_version_id\n if not version:\n raise orm.except_orm(\n _(u'Error'),\n _(u'The budget version must be set in the company'))\n\n deadline = dt.datetime.strptime(lead.date_deadline,\n DATE_FORMAT)\n budget_lines = []\n for date_start, date_stop in self._line_dates(deadline,\n lead.months):\n budget_lines.append((0, 0, {\n 'name': u'{0} - {1} {2}'.format(\n lead.name,\n _(calendar.month_name[date_start.month]),\n date_start.year),\n 'date_start': date_start,\n 'date_stop': date_stop,\n 'analytic_account_id': lead.analytic_account_id.id,\n 'budget_item_id': lead.budget_item_id.id,\n 'amount': lead.planned_revenue / lead.months,\n 'currency_id': lead.currency_id.id,\n 'budget_version_id': version.id,\n }))\n\n lead.write({'budget_line_ids': budget_lines})\n","sub_path":"budget_crm/wizard/crm_to_budget.py","file_name":"crm_to_budget.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"22765987","text":"#!/usr/bin/python\nfrom __future__ import print_function\n#\n# Copyright (c) 2009, Georgia Tech Research Corporation\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the Georgia Tech Research Corporation nor the\n# names of its contributors may be used to endorse or promote products\n# derived from this software without specific prior written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n\n## Controlling Robotis Dynamixel RX-28 & RX-64 servos from python\n## using the USB2Dynamixel adaptor.\n\n## Authors: Travis Deyle, Advait Jain & Marc Killpack (Healthcare Robotics Lab, Georgia Tech.)\n\nimport time\ntry:\n import thread\nexcept:\n import _thread as thread\nimport sys, optparse\nimport math\nimport string\nimport opbots.serial_manager\n\nclass RobotisServo():\n ''' Class to use a robotis RX-28 or RX-64 servo.\n '''\n def __init__(self, SerialManager, servo_id):\n ''' USB2Dynamixel - USB2Dynamixel_Device object to handle serial port.\n Handles threadsafe operation for multiple servos\n servo_id - servo ids connected to USB2Dynamixel 1,2,3,4 ... (1 to 253)\n [0 is broadcast if memory serves]\n series - Just a convenience for defining \"good\" defaults on MX series.\n When set to \"MX\" it uses these values, otherwise it uses values\n better for AX / RX series. Any of the defaults can be overloaded\n on a servo-by-servo bases in servo_config.py\n '''\n defaults = {\n 'home_encoder': 0x7FF,\n 'max_encoder': 0xFFF,\n 'rad_per_enc': math.radians(360.0) / 4096, \n 'max_ang': math.radians(180),\n 'min_ang': math.radians(-180),\n 'flipped': False,\n 'max_speed': math.radians(360)\n }\n\n self.position = 1800\n\n # Error Checking\n if SerialManager == None:\n raise RuntimeError('lib_robotis: Robotis Servo requires serial connection!\\n')\n else:\n self.dyn = SerialManager\n\n # ID exists on bus?\n self.servo_id = servo_id\n try:\n self.read_address(3)\n except:\n raise RuntimeError('lib_robotis: Error encountered. Could not find ID (%d)\\n' %( servo_id ))\n\n # Set Return Delay time - Used to determine when next status can be requested\n data = self.read_address( 0x05, 1)\n self.return_delay = data[0] * 2e-6\n\n # Set various parameters. Load from servo_config.\n self.settings = {}\n try:\n import servo_config as sc\n if sc.servo_param.has_key( self.servo_id ):\n self.settings = sc.servo_param[ self.servo_id ]\n else:\n print('Warning: servo_id ', self.servo_id, ' not found in servo_config.py. Using defaults.')\n except:\n print('Warning: servo_config.py not found. Using defaults.')\n\n # Set to default any parameter not specified in servo_config\n for key in defaults.keys():\n if self.settings.has_key( key ):\n pass\n else:\n self.settings[ key ] = defaults[ key ]\n\n def init_cont_turn(self):\n '''sets CCW angle limit to zero and allows continuous turning (good for wheels).\n After calling this method, simply use 'set_angvel' to command rotation. This \n rotation is proportional to torque according to Robotis documentation.\n '''\n self.write_address(0x08, [0,0])\n\n def kill_cont_turn(self):\n '''resets CCW angle limits to allow commands through 'move_angle' again\n '''\n self.write_address(0x08, [255, 3])\n\n def is_moving(self):\n ''' returns True if servo is moving.\n '''\n data = self.read_address( 0x2e, 1 )\n return data[0] != 0\n\n def read_voltage(self):\n ''' returns voltage (Volts)\n '''\n data = self.read_address( 0x2a, 1 )\n return data[0] / 10.\n\n def read_temperature(self):\n ''' returns the temperature (Celcius)\n '''\n data = self.read_address( 0x2b, 1 )\n return data[0]\n\n def read_load(self):\n ''' number proportional to the torque applied by the servo.\n sign etc. might vary with how the servo is mounted.\n '''\n data = self.read_address( 0x28, 2 )\n load = data[0] + (data[1] >> 6) * 256\n if data[1] >> 2 & 1 == 0:\n return -1.0 * load\n else:\n return 1.0 * load\n\n def read_encoder(self):\n ''' returns position in encoder ticks\n '''\n data = self.read_address( 0x24, 2 )\n enc_val = data[0] + data[1] * 256\n return enc_val\n\n def read_angle(self):\n ''' returns the current servo angle (radians)\n '''\n ang = (self.read_encoder() - self.settings['home_encoder']) * self.settings['rad_per_enc']\n if self.settings['flipped']:\n ang = ang * -1.0\n return ang\n\n def read_propGain(self):\n data = self.read_address( 0X1C , 1 )\n return data[0]\n\n def write_propGain(self, value):\n if value > 0:\n data = self.write_address( 0X1C , [value] )\n\n def read_dervGain(self):\n data = self.read_address( 0X1A , 1 )\n return data[0]\n\n def write_dervGain(self, value):\n if value > 0:\n data = self.write_address( 0X1A , [value] )\n\n def read_intGain(self):\n data = self.read_address( 0X1B , 1 )\n return data[0]\n\n def write_intGain(self, value):\n if value > 0:\n data = self.write_address( 0X1B , [value] )\n\n def move_angle(self, ang, angvel=None, blocking=True):\n ''' move to angle in DEGREES\n '''\n #print \"angle: \"+ang\n if not isinstance(ang, float) or not isinstance(ang, int):\n ang= float(ang)\n #ang= math.radians(ang) #comment out for rads\n if angvel == None:\n angvel = self.settings['max_speed']\n\n if angvel > self.settings['max_speed']:\n print('lib_robotis.move_angle: angvel too high - %.2f deg/s' % (math.degrees(angvel)))\n print('lib_robotis.ignoring move command.')\n return\n\n if ang > self.settings['max_ang'] or ang < self.settings['min_ang']:\n print('lib_robotis.move_angle: angle out of range- ', math.degrees(ang))\n print('lib_robotis.ignoring move command.')\n return\n \n self.set_angvel(angvel)\n\n if self.settings['flipped']:\n ang = ang * -1.0\n enc_tics = int(round( ang / self.settings['rad_per_enc'] ))\n enc_tics += self.settings['home_encoder']\n self.move_to_encoder( enc_tics )\n\n if blocking == True:\n while(self.is_moving()):\n continue\n\n def move_to_encoder(self, n):\n ''' move to encoder position n\n '''\n # In some border cases, we can end up above/below the encoder limits.\n # eg. int(round(math.radians( 180 ) / ( math.radians(360) / 0xFFF ))) + 0x7FF => -1\n n = min( max( n, 0 ), self.settings['max_encoder'] ) \n hi,lo = n / 256, n % 256\n return self.write_address( 0x1e, [lo,hi] )\n\n def enable_torque(self):\n return self.write_address(0x18, [1])\n\n def disable_torque(self):\n return self.write_address(0x18, [0])\n\n def set_angvel(self, angvel):\n ''' angvel - in rad/sec\n ''' \n rpm = angvel / (2 * math.pi) * 60.0\n angvel_enc = int(round( rpm / 0.111 ))\n if angvel_enc<0:\n hi,lo = abs(angvel_enc) / 256 + 4, abs(angvel_enc) % 256\n else:\n hi,lo = angvel_enc / 256, angvel_enc % 256\n \n return self.write_address( 0x20, [lo,hi] )\n\n def write_id(self, id):\n ''' changes the servo id\n '''\n return self.write_address( 0x03, [id] )\n\n def __calc_checksum(self, msg):\n chksum = 0\n for m in msg:\n chksum += m\n chksum = ( ~chksum ) % 256\n return chksum\n\n def set_cw_limit(self, cw_limit):\n ''' set the clockwise servo limit\n '''\n self.write_address(0x06, [cw_limit % 256, cw_limit / 256])\n\n def set_ccw_limit(self, ccw_limit):\n ''' set the counterclockwise servo limit\n '''\n self.write_address(0x08, [ccw_limit % 256, ccw_limit / 256])\n\n def read_multi_offset(self):\n ''' gets the offset in multi-turn mode\n '''\n return self.read_address(0x14, 2)\n\n def set_multi_offset(self, offset):\n ''' sets the offset in multi-turn mode\n '''\n self.write_address(0x14, [offset % 256, offset / 256])\n\n def read_address(self, address, nBytes=1):\n ''' reads nBytes from address on the servo.\n returns [n1,n2 ...] (list of parameters)\n '''\n msg = [ 0x02, address, nBytes ]\n return self.send_instruction( msg, self.servo_id )\n\n def write_address(self, address, data):\n ''' writes data at the address.\n data = [n1,n2 ...] list of numbers.\n return [n1,n2 ...] (list of return parameters)\n '''\n msg = [ 0x03, address ] + data\n return self.send_instruction( msg, self.servo_id )\n\n def send_instruction(self, instruction, id):\n msg = [ id, len(instruction) + 1 ] + instruction # instruction includes the command (1 byte + parameters. length = parameters+2)\n chksum = self.__calc_checksum( msg )\n msg = [ 0xff, 0xff ] + msg + [chksum]\n \n self.dyn.acq_mutex()\n\n try:\n self.send_serial( msg )\n data, err = self.receive_reply()\n except:\n self.dyn.rel_mutex()\n raise\n self.dyn.rel_mutex()\n \n if err != 0:\n self.process_err( err )\n\n return data\n\n def process_err( self, err ):\n raise RuntimeError('lib_robotis: An error occurred: %d\\n' % err)\n\n def receive_reply(self):\n start = self.dyn.read_serial( 2 )\n if start != '\\xff\\xff':\n raise RuntimeError('lib_robotis: Failed to receive start bytes\\n')\n servo_id = self.dyn.read_serial( 1 )\n if ord(servo_id) != self.servo_id:\n raise RuntimeError('lib_robotis: Incorrect servo ID received: %d\\n' % ord(servo_id))\n data_len = self.dyn.read_serial( 1 )\n err = self.dyn.read_serial( 1 )\n data = self.dyn.read_serial( ord(data_len) - 2 )\n checksum = self.dyn.read_serial( 1 ) # I'm not going to check...\n return [ord(v) for v in data], ord(err)\n\n def send_serial(self, msg):\n \"\"\" sends the command to the servo\n \"\"\"\n out = ''\n for m in msg:\n out += chr(m)\n self.dyn.serial_io.write( out )\n\n def move_cw(self):\n self.move(20)\n\n def move_ccw(self):\n self.move(-20)\n\n def move(self, adjustment):\n self.position = self.position + adjustment\n self.position = min(self.position, 4095)\n self.position = max(1, self.position)\n self.move_to_encoder(int(self.position))\n\n def send_command(self, command):\n self.manager.serial_io.write(command)","sub_path":"src/opbots/robotis_servo.py","file_name":"robotis_servo.py","file_ext":"py","file_size_in_byte":12409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649581739","text":"from keras.models import Model, load_model\nfrom keras.layers import Input, Dense, Dropout, Flatten, Activation, Reshape\nfrom keras.layers.convolutional import Conv2D, ZeroPadding2D\nfrom keras.layers.pooling import MaxPooling2D, AveragePooling2D\nfrom keras.optimizers import SGD, Adam, Adadelta\nfrom keras.preprocessing.image import ImageDataGenerator\nimport numpy as np\nimport pandas as pd\nimport keras\nimport sys\n\ntrain_file = sys.argv[1]\n#test_file = 'test.csv'\nx_train_file = 'x_train.csv'\ny_train_file = 'y_train.csv'\nall_train_file = 'all_train.csv'\nmodel_file = 'model/model_sample_4.h5'\n\n\nbatch_size = 128\ntotal_epochs = 0\nPATIENCE = 50\n\nimg_row = 48\nimg_col = 48\ninput_shape = (img_row, img_col, 1)\nnum_classes = 7\n\n#read in datas\n\ndf = pd.read_csv(train_file,header=None)\n\ndf_label = df[0]\n\ndf_label.drop( df_label.index[[0]], inplace=True)\ndf_label = df_label.convert_objects(convert_numeric=True)\nLables = df_label.as_matrix()\nnp.savetxt('y_train.csv', Lables, delimiter=\",\")\n\ndf = df[1].str.split(' ', 48*48, expand=True)\ndf.drop( df.index[[0]], inplace=True)\ndf = df.convert_objects(convert_numeric=True)\nAll_datas = df.as_matrix(columns=df.columns[:])\nnp.savetxt('x_train.csv', All_datas, delimiter=\",\")\n\nx = np.genfromtxt(x_train_file, delimiter=',')\ny = np.genfromtxt(y_train_file, delimiter=',')\ny = np.reshape(y,(y.shape[0],1))\nAll_datas = np.hstack((y,x))\nnp.savetxt('all_train.csv', All_datas, delimiter=\",\")\n\ndef build_model():\n\n input_img = Input(shape=(48, 48, 1))\n block1 = Conv2D(64, (5, 5), padding='valid', activation='relu')(input_img)\n block1 = ZeroPadding2D(padding=(2, 2), data_format='channels_last')(block1)\n block1 = MaxPooling2D(pool_size=(5, 5), strides=(2, 2))(block1)\n block1 = ZeroPadding2D(padding=(1, 1), data_format='channels_last')(block1)\n\n block2 = Conv2D(64, (3, 3), activation='relu')(block1)\n block2 = ZeroPadding2D(padding=(1, 1), data_format='channels_last')(block2)\n\n block3 = Conv2D(64, (3, 3), activation='relu')(block2)\n block3 = AveragePooling2D(pool_size=(3, 3), strides=(2, 2))(block3)\n block3 = ZeroPadding2D(padding=(1, 1), data_format='channels_last')(block3)\n\n block4 = Conv2D(128, (3, 3), activation='relu')(block3)\n block4 = ZeroPadding2D(padding=(1, 1), data_format='channels_last')(block4)\n\n block5 = Conv2D(128, (3, 3), activation='relu')(block4)\n block5 = ZeroPadding2D(padding=(1, 1), data_format='channels_last')(block5)\n block5 = AveragePooling2D(pool_size=(3, 3), strides=(2, 2))(block5)\n block5 = Flatten()(block5)\n\n fc1 = Dense(1024, activation='relu')(block5)\n fc1 = Dropout(0.5)(fc1)\n\n fc2 = Dense(1024, activation='relu')(fc1)\n fc2 = Dropout(0.5)(fc2)\n\n predict = Dense(7)(fc2)\n predict = Activation('softmax')(predict)\n model = Model(inputs=input_img, outputs=predict)\n\n #opt = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)\n opt = Adam(lr=1e-3)\n #opt = Adadelta(lr=0.1, rho=0.95, epsilon=1e-08)\n model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])\n model.summary()\n return model\n\n#generate validation set and train set\nprint(\"generate training data ...\")\n#All_datas = np.genfromtxt(all_train_file, delimiter=',')\nnp.random.shuffle(All_datas)\nx_test = All_datas[:4000,1:]\nx_test = np.reshape(x_test,(x_test.shape[0], img_row, img_col, 1))\ny_test = np.reshape(All_datas[:4000, 0],(-1,1))\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nx_train = All_datas[4000:,1:]\ny_train = np.reshape(All_datas[4000:, 0],(-1,1))\nx_train = np.reshape(x_train,(x_train.shape[0], img_row, img_col, 1))\ny_train = keras.utils.to_categorical(y_train, num_classes)\n\nx_train /= 255\nx_test /= 255\n\n\nmodel = build_model()\n\ntrain_datagen = ImageDataGenerator(\n shear_range = 0.2,\n zoom_range = 0.2,\n horizontal_flip=True)\n\n\nbest_acc = 0\nearly_stop_counter = 0\nflag_run = True\n\nwhile flag_run:\n if early_stop_counter < PATIENCE:\n #run = input(\"want to do fitting? (y/n) \")\n run = 'y'\n else:\n run = 'n'\n \n if run != 'y' and run != 'Y':\n print(\"total_epochs = %d\" %(total_epochs*5), end=\"\\n\")\n print(\"best accuracy = %.5f\" %best_acc)\n break\n\n #fit model\n #epochs = eval(input(\"number of epochs: \"))\n epochs = 60\n #shuffle every epoch\n for e in range(epochs):\n print(\"####################\")\n print(\"Epoch cycle: %d / %d\" %(e+1,epochs))\n print(\"####################\")\n rand_data = np.random.permutation(All_datas[4000:,:])\n x_train = rand_data[:,1:]\n y_train = np.reshape(rand_data[:, 0],(-1,1))\n y_train = keras.utils.to_categorical(y_train, num_classes)\n\n #rand_flip_data = np.random.permutation(flip_datas)\n #x_train = np.concatenate((x_train, rand_flip_data[:,1:]), axis=0)\n #y_train = np.concatenate((y_train, keras.utils.to_categorical(np.reshape(rand_flip_data[:, 0],(-1,1)), num_classes)), axis=0)\n x_train = np.reshape(x_train,(x_train.shape[0], img_row, img_col, 1))\n\n for i in range(5):\n model.fit_generator(train_datagen.flow(x_train, y_train, batch_size=batch_size),\n steps_per_epoch=len(x_train)/batch_size, \n epochs=1, \n validation_data=(x_test,y_test))\n \n score = model.evaluate(x_test, y_test, verbose=0)\n #print('Val loss:', score[0])\n #print('Val accuracy:', score[1])\n if score[1] > best_acc:\n best_acc = score[1]\n early_stop_counter = 0\n model.save(model_file)\n\n #predict\n \"\"\"\n print(\"start prediction ...\")\n test_prob = model.predict(X)\n results = test_prob.argmax(axis=-1)\n results = np.reshape(results,(-1,1))\n results = results.astype(int)\n\n #write to result\n print(\"start writing result\")\n out = np.column_stack((ID, results))\n np.savetxt( out_file , out, delimiter=',', fmt=\"%s\", header = 'id,label',comments='')\n \"\"\" \n else:\n early_stop_counter += 1\n\n if early_stop_counter > PATIENCE:\n print(\"incounter early stop! best acc: %d\" %best_acc)\n print(\"total epoch cycle: %d\" %e)\n total_epochs += e\n break\n #if never early stop\n early_stop_counter = 0\n\n print(\"now best_acc = %.5f\" %best_acc)\n\n total_epochs += epochs\n flag_run = False","sub_path":"hw3/sample_code.py","file_name":"sample_code.py","file_ext":"py","file_size_in_byte":6593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"103451957","text":"import sys\r\n\r\nimport psycopg2\r\n\r\nconn = psycopg2.connect(database=\"rusbd\", user=\"rus\", password=\"111\", host=\"127.0.0.1\", port=\"5432\")\r\ncur = conn.cursor()\r\n\r\nif sys.argv[1] == \"fill\":\r\n\r\n cur.execute(\"delete from nginx_log_parser\");\r\n\r\n nginx_log_file = open(\"nginx.log\")\r\n\r\n for line in nginx_log_file:\r\n\r\n line_list = line.split(\" \")\r\n\r\n query_params = '{}, \\'{}\\', \\'{}\\''.format(int(line_list[8]), line_list[0], line_list[5].replace(\"\\\"\",\"\"))\r\n\r\n cur.execute(\"insert into nginx_log_parser (code, ip, method) \\\r\n values ({}) \".format(query_params) );\r\n\r\n conn.commit()\r\n conn.close()\r\n\r\nif sys.argv[1] == \"count\":\r\n\r\n\tcur.execute(\"select count (distinct ip), count (distinct method), count (distinct code) from nginx_log_parser\");\r\n\trows = cur.fetchall()\r\n\r\n\tfor row in rows:\r\n\r\n\t\tprint(\"IP: \" + str(row[0]) + \", METHOD: \" + str(row[1]) + \", CODE: \" + str(row[2]))\r\n\r\n\r\nconn.close()","sub_path":"nginx_log_parser.py","file_name":"nginx_log_parser.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"351926021","text":"import os.path\nfrom PIL import Image\nfrom torch.utils.data import Dataset\n\n# Within package imports\nfrom .data_loader import register_dataset_obj, register_data_params\nfrom .data_loader import DatasetParams\n\n@register_data_params('swit')\nclass SWITParams(DatasetParams):\n \n num_channels = 3\n image_size = 99\n mean = 0.5\n std = 0.5\n num_cls = 10\n\n@register_dataset_obj('swit')\nclass SWIT_dataset(Dataset):\n\n \"\"\"MultiPIE datasets\n \"\"\"\n\n def __init__(self, root, train=True, transform=None, target_transform=None,\ndownload=False):\n\n self.root = root\n self.train = train\n self.dataroot = os.path.join(self.root, 'numbers')\n\n # if self.train:\n # self.txt = os.path.join(root, '%s_train.txt'%self.src)\n # else:\n # self.txt = os.path.join(root, '%s_test.txt'%self.src)\n\n self.txt = os.path.join(self.root, 'swit_all.txt')\n\n self.img_path = []\n self.labels = []\n self.transform = transform\n\n with open(self.txt) as f:\n for line in f:\n self.img_path.append(os.path.join(self.dataroot, line.split()[0]))\n self.labels.append(int(line.split()[1]))\n\n\n def __len__(self):\n return len(self.labels)\n\n def __getitem__(self, index):\n\n path = self.img_path[index]\n target = self.labels[index]\n \n with open(path, 'rb') as f:\n image = Image.open(f).convert('RGB')\n \n if self.transform is not None:\n image = self.transform(image)\n\n return image, target\n","sub_path":"classification_multi_face/dataset_comp/swit.py","file_name":"swit.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"209131213","text":"from .scuba_thrower import ScubaThrower\nfrom utils import terminators_win\nfrom.dragon import Dragon\n\nclass DragonKing(ScubaThrower): \n # Dragon King Kin\n name = 'King'\n implemented = True # Change to True to view in the GUI\n food_cost=7\n # END 4.3\n def __init__(self, armor=1):\n \"*** YOUR CODE HERE ***\"\n super().__init__(armor)\n self.real_one=False\n if DragonKing.instantiated is False:\n self.real_one=True\n DragonKing.instantiated=True\n\n def action(self, colony):\n \"\"\"A dragon king throws a stone, but also doubles the damage of dragons\n in his tunnel.\n \n Impostor kings do only one thing: reduce their own armor to 0.\n \"\"\"\n # BEGIN 4.3\n \"*** YOUR CODE HERE ***\"\n if self.real_one is False:\n self.reduce_armor(self.armor)\n else:\n super().action(colony)\n x=self.place.exit\n while x is not None:\n if x.dragon is not None:\n if x.dragon.is_doubled is False:\n x.dragon.damage=2*x.dragon.damage\n x.dragon.is_doubled=True\n if x.dragon.is_container:\n if x.dragon.contained_dragon is not None and x.dragon.contained_dragon.is_doubled is False:\n x.dragon.contained_dragon.damage=2*x.dragon.contained_dragon.damage\n x.dragon.contained_dragon.is_doubled=True\n x=x.exit\n \n \n # END 4.3\n\n def reduce_armor(self, amount):\n \"\"\"Reduce armor by AMOUNT, and if the True DragonKing has no armor\n remaining, signal the end of the game. \n \"\"\"\n self.armor-=amount\n if self.armor<=0:\n self.place.remove_fighter(self)\n self.death_callback()\n if self.real_one is True:\n terminators_win()\n # BEGIN 4.3\n \"*** YOUR CODE HERE ***\"\n","sub_path":"characters/dragons/dragon_king.py","file_name":"dragon_king.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"143082155","text":"import os,sys\nimport pandas as pd\nimport xml.etree.ElementTree as ET\n\ndef xml_to_csv(xml_file):\n xml_list = []\n img_names = []\n tree = ET.parse(xml_file)\n root = tree.getroot()\n c = 0\n for image in root.findall('image'):\n image_name = image[0].text\n img_name = image_name.split('/')[-1]\n img_names.append(img_name)\n c += 1\n #print(image_name)\n reso_x = int(image[3].get('x'))\n reso_y = int(image[3].get('y'))\n #print(reso_x,reso_y)\n for i in image[4]:\n #print(i.get('height'),i.get('width'),i.get('x'),i.get('y'))\n xmin = int(i.get('x'))\n ymin = int(i.get('y'))\n xmax = int(i.get('x')) + int(i.get('width'))\n ymax = int(i.get('y')) + int(i.get('height'))\n #print xmin,ymin,xmax,ymax\n value = (image_name,reso_x,reso_y,'text',xmin,ymin,xmax,ymax)\n xml_list.append(value) \n #print('\\n')\n #print(xml_list)\n print('No of instances {}.xml = {}'.format(name,len(xml_list)))\n print('No. of images in {} xml = {}'.format(name,c))\n # sys.exit()\n \n \n column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']\n xml_df = pd.DataFrame(xml_list, columns=column_name)\n return xml_df,img_names\n \nprint(' *** script started...!!!\\n')\nlist1 = []\n\nimg_folder_path = '/home/ashwini/Downloads/Text_Detection_Dataset/svt/svt1/img'\nxmls_folder_path = '/home/ashwini/Downloads/Text_Detection_Dataset/svt/svt1/xmls'\n\nimg_list = os.listdir(img_folder_path) \n\nfor xml in os.listdir(xmls_folder_path):\n #print(xml)\n name = xml.split('.')[0]\n xml_df,img_names = xml_to_csv(xml)\n for i in img_names:\n list1.append(i)\n xml_df.to_csv(str(name) + '_labels.csv', index=None)\n#print len(list1)\nfor i in img_list:\n if i not in list1:\n print ('\\nNOTE : extra image in img folder : ',i)\nprint('\\n *** script executed...!!!')\n\n","sub_path":"Text_detection_scripts_and_dataset/my_scripts/xml_to_csv_svt.py","file_name":"xml_to_csv_svt.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"586634944","text":"from django.conf.urls import url, include\nfrom rest_framework.urlpatterns import format_suffix_patterns\nimport views\n\n\nurlpatterns = {\n url(r'^twitter_login/$', views.twitter_login, name='twitter_login'),\n url(r'^twitter_home/$', views.twitter_home, name='twitter_home'),\n url(r'^twitter_logout/$', views.twitter_logout, name='twitter_logout'),\n url(r'^twitter_register/$',views.twitter_register, name='register'),\n url(r'^users_list/$',views.users_list, name='users_list'),\n url(r'^create_post/$',views.create_post, name='create_post'),\n url(r'^(?P[a-z0-9-]+)/(?P\\d+)/$', views.update_followers, name='update_followers'),\n url(r'^(?P\\d+)/$', views.delete_post, name='delete_post'),\n}\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"346320929","text":"\"\"\"Support for Drive sensors.\"\"\"\nimport logging\n\nfrom homeassistant.core import callback\nfrom homeassistant.helpers.entity import Entity\nfrom homeassistant.util import slugify\nfrom .config_flow import configured_drivers\n_LOGGER = logging.getLogger(__name__)\n\n\nasync def async_setup_platform(hass, config, async_add_entities, discovery_info=None):\n \"\"\"Set up an Drive sensor based on existing config.\"\"\"\n pass\n\n\nasync def async_setup_entry(hass, entry, async_add_entities):\n \"\"\"Set up a drive sensor based on a rclone config entry.\"\"\"\n from homeassistant.components.ais_drives_service import rclone_get_remotes_long, DRIVES_TYPES\n remotes = rclone_get_remotes_long()\n conf_drives = configured_drivers(hass)\n sensors = []\n for remote in remotes:\n drive_type = remote[\"type\"]\n code, icon = DRIVES_TYPES[drive_type]\n srn = slugify(remote[\"name\"])\n # if srn in conf_drives:\n # _LOGGER.info('Drive exists ' + srn)\n # else:\n # # check if sensor exists\n # #state = hass.states.get('sensor.ais_drives_service_' + srn)\n # #if state is None:\n sensors.append(DriveSensor(srn, icon))\n\n async_add_entities(sensors, True)\n\n\nclass DriveSensor(Entity):\n \"\"\"Implementation of a Drive sensor.\"\"\"\n\n def __init__(self, name, icon):\n \"\"\"Initialize the Drive sensor.\"\"\"\n self._icon = icon\n self._name = name\n self._data = None\n self._attrs = {}\n\n @property\n def icon(self):\n \"\"\"Return the icon.\"\"\"\n return self._icon\n\n @property\n def state(self):\n \"\"\"Return the state of the device.\"\"\"\n return 1\n\n # @property\n # def unit_of_measurement(self):\n # \"\"\"Return the unit of measurement of this entity, if any.\"\"\"\n # return '%'\n\n @property\n def should_poll(self):\n \"\"\"Disable polling.\"\"\"\n return False\n\n @property\n def unique_id(self) -> str:\n \"\"\"Return a unique, friendly identifier for this entity.\"\"\"\n return self._name\n\n @property\n def device_state_attributes(self):\n \"\"\"Return the state attributes.\"\"\"\n return\n\n async def async_added_to_hass(self):\n \"\"\"Register callbacks.\"\"\"\n @callback\n def update():\n \"\"\"Update the state.\"\"\"\n self.async_schedule_update_ha_state(True)\n\n async def async_will_remove_from_hass(self):\n \"\"\"Disconnect dispatcher listener when removed.\"\"\"\n pass\n\n async def async_update(self):\n \"\"\"Get the latest data and update the state.\"\"\"\n try:\n self._data = 1\n except KeyError:\n return\n","sub_path":"homeassistant/components/ais_drives_service/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"132909022","text":"#P11_Datetime_03\n\nimport datetime\ndef diffDate(x):\n from datetime import date\n y = x.split('/')\n tgl1 = date(year = int(y[0]), month = int(y[1]), day = int(y[2]))\n tgl2 = date.today()\n selisih = tgl1 - tgl2\n selisih.days\n return\nterlambat = str(diffDate('2021/1/2'))\n\nKode = input('Masukkan Kode Member : ')\nfile = open(\"DataPeminjamanBuku.txt\", \"r\")\nfiles = file.readlines()\ntglkembali = datetime.date.today()\n\nfor x in range(len(files)):\n if(Kode in files[x]):\n KODE = 'ada'\n if(KODE == 'ada'):\n y = files[x].split('|')\n print('\\nData Peminjaman Buku')\n print('Kode Member\\t\\t\\t:',y[0])\n print('Nama Member\\t\\t\\t:',y[1])\n print('Judul Buku\\t\\t\\t:',y[2])\n print('Tanggal Mulai Peminjaman\\t:',y[3])\n print('Tanggal Maks Peminjaman\\t\\t:',y[4])\n print('Tanggal Pengembalian\\t\\t:',tglkembali)\n if terlambat == 'None':\n print('Terlambat\\t\\t\\t: -')\n print('Denda\\t\\t\\t\\t: Rp.0') \n else:\n denda = int(terlambat)*2000\n print('Terlambat\\t\\t\\t: ',terlambat)\n print('Denda\\t\\t\\t\\t: Rp.',denda) \n break\n if(Kode not in files[x]):\n KODE = 'tdk ada'\n continue\nif(KODE == 'tdk ada'):\n print('Data Peminjaman Buku tidak ditemukan')\n \n","sub_path":"Praktikum 11 Datetime/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"323031731","text":"#!/usr/bin/python3\n#\n# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n#\n\n# Necessary Imports\nimport jetson.inference\nimport jetson.utils\nimport csv\nimport sys\nimport time\nfrom datetime import datetime\nimport os\n\n# Ask user for names of parts and stages model. Only for testing purposes.\ndirs = os.listdir('/home')\n#part_model_name = input(\"Enter part model name with extension: \")\n#stage_model_name = input(\"Enter stage model name with extension: \")\ndirs = os.listdir('/home')\n#part_model_path = '/home/'+ str(dirs[0]) + '/Capstone/models/PartDetection/' + str(part_model_name)\n#stage_model_path = '/home/'+ str(dirs[0]) + '/Capstone/models/Stages/' + str(stage_model_name)\npart_model_path = '/home/' + 'rishit/'+ 'Capstone/models/PartDetection/All_Parts.onnx'\nstage_model_path = '/home/'+ 'rishit/' + '/Capstone/models/Stages/All_Stages.onnx'\n\n\n# Get info from csv. Only run once. Comment out once .db is generated\nwith open(os.path.join(sys.path[0], \"instructions.csv\"),'r') as file:\n reader = csv.reader(file)\n instructions = list(reader)\n\nprint(instructions)\n\n# Open up labels file for part detection\nf = open(\"labels_parts.txt\",\"r\")\nlabels = []\nfor i in f.readlines():\n\tlabels.append(i.strip('\\n'))\nf.close()\n\n# This net used with Part Detection.\n# Change model directory depending on user. Stores labels in same directory as src\n\npart_net = jetson.inference.detectNet(argv=['--model='+part_model_path,'--labels=./labels_parts.txt','--input_blob=input_0','--output-cvg=scores','--output-bbox=boxes','--threshold=.8'])\nstages_net = jetson.inference.detectNet(argv=['--model='+stage_model_path,'--labels=./labels_stages.txt','--input_blob=input_0','--output-cvg=scores','--output-bbox=boxes','--threshold=.8'])\n\ncamera = jetson.utils.videoSource(\"/dev/video0\") # '/dev/video0' for V4L2\ndisplay = jetson.utils.videoOutput(\"display://0\") # 'my_video.mp4' for file\n\n# Add another net, camera, and display for Stage Detection\nbeginTime = time.time()\nprocedureTime = time.time()\nendTime = 0\ncurrentInstr, stageCount = 0, 0\n\n# Open up labels file for stage detection\nf = open(\"labels_stages.txt\",\"r\")\nlabels_stages = []\nfor i in f.readlines():\n\tlabels_stages.append(i.strip('\\n'))\nf.close()\n\nbuttonPressed = True\n\nprint(instructions[0][0], instructions[0][1])\n\n# Lists will hold information for duration of procedure\nobjects = []\nvertices = []\nPartTimeStamps = []\nStageName = []\nStageTimeStamps = []\nincorrectValidation = []\nmissedValidations = 0\n\n\n#while display.IsStreaming():\nwhile True:\n\tif currentInstr >= len(instructions):\t# end program if all instructions have been passed through\n\t\tbreak\n\t# Keep Track of Time\n\tbeginTime = time.time()\n\timg = camera.Capture()\n\tdetections = part_net.Detect(img) # Holds all the valuable Information\n\tstages = stages_net.Detect(img)\n\t#if len(stages) != 0:\n\t#\tprint(instructions[currentInstr][0])\n\t#\tprint(instructions[currentInstr][1])\n\tif buttonPressed and len(stages) != 0:\t# user has pressed 'Stage Complete' button\n\t\tif labels_stages[stages[0].ClassID] == instructions[currentInstr][1]:\n\t\t\t#print(\"stageCount increased\")\n\t\t\tstageCount += 1\n\t\telse:\n\t\t\t#print(\"stageCount = 0\")\n\t\t\tstageCount = 0\n\t\t\tmissedValidations += 1\n\t#\t\tbuttonPressed = False\n\t\tif stageCount == 48:\n\t\t\tStageName.append(instructions[currentInstr][1])\n\t\t\tincorrectValidation.append(missedValidations)\n\t\t\tmissedValidations = 0\n\t\t\tnow = datetime.now()\n\t\t\tcurrent_time = now.strftime(\"%H:%M:%S\")\n\t\t\tStageTimeStamps.append(current_time)\n\t\t\tcurrentInstr += 1\n\t\t\tprint(instructions[currentInstr][0], instructions[currentInstr][1])\n\t\t\tuserInput = int(input(\"Skip how many stages? (0-7) \"))\n\t\t\tcurrentInstr += userInput\n\t\t\tif userInput != 0:\n\t\t\t\tprint(instructions[currentInstr][0], instructions[currentInstr][1])\n\t\t\t#buttonPressed = False\n\t#\t\t# add timestamp of stage complete to datalog\n\t# If difference greater than log time desired in seconds, log the data. Currently, logging data every five seconds\n\tif(beginTime-endTime > 1):\n\t\tfor i in range(len(detections)):\n\t\t\tobjects.append(labels[detections[i].ClassID])\n\t\t\t# Store box vertices in clockwise order\n\t\t\tbottomLeft = (detections[i].Left, detections[i].Bottom)\n\t\t\tbottomRight = (detections[i].Right, detections[i].Bottom)\n\t\t\ttopLeft = (detections[i].Left, detections[i].Top)\n\t\t\ttopRight = (detections[i].Right, detections[i].Top)\n\t\t\tvertices.append((topLeft,topRight,bottomRight,bottomLeft))\n\t\tnow = datetime.now()\n\t\tcurrent_time = now.strftime(\"%H:%M:%S\")\n\t\tPartTimeStamps.append(current_time)\n\t\tendTime = time.time()\n\t\n\tdisplay.Render(img)\n\tdisplay.SetStatus(\"Object Detection | Network {:.0f} FPS\".format(part_net.GetNetworkFPS()))\n\tif not camera.IsStreaming() or not display.IsStreaming():\n\t\tbreak\n\n\n# Create two csv files: one will hold information about parts and other will hold information about procedure\nprint(\"Success: Procedure Complete!\")\n\nprint(\"Writing Information into CSV Files ...\")\n\nwith open('Stages.csv',mode='w') as stages_file:\n\tstages_file_writer = csv.writer(stages_file,delimiter=',')\n\n\tstages_file_writer.writerow(['Stage Completed', 'Time Completed', 'Missed Validations'])\n\n\tfor i in range(len(StageName)):\n\t\tstages_file_writer.writerow([StageName[i],StageTimeStamps[i],incorrectValidation[i]])\n\nwith open('Parts.csv',mode='w') as parts_file:\n\tparts_file_writer = csv.writer(parts_file,delimiter=',')\n\n\tparts_file_writer.writerow(['Object Name', 'Top Left Coordinate', 'Top Right Coordinate', 'Bottom Right Coordinate', 'Bottom Left Coordinate', 'Time Stamped'])\n\n\tfor i in range(len(objects)):\n\t\tparts_file_writer.writerow([objects[i], vertices[i][0],vertices[i][1],vertices[i][2],vertices[i][3], PartTimeStamps[i]])\n\nprint(\"Writing Complete\")\n","sub_path":"src/my-detection.py","file_name":"my-detection.py","file_ext":"py","file_size_in_byte":6716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"74681716","text":"from time import sleep\nimport socket\nimport pickle\nfrom configparser import ConfigParser\n\ncfg = ConfigParser()\ncfg.read('settings.ini')\nHOST = cfg.get('server', 'host')\nPORT = int(cfg.get('server', 'port'))\n\nsock = socket.socket()\nsock.connect((HOST, PORT))\ndict = {\"id\": 1, \"name\": \"abc\"}\n\nfor i in range(10):\n sock.send(pickle.dumps(dict))\n sleep(0.5)\n\ndata = sock.recv(1024)\nprint(data)\n\nsock.close()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"498565657","text":"import numpy\nimport random\nimport pylab as pl\n\nclass SimpleVirus(object):\n \"\"\"\n Representation of a simple virus (does not model drug effects/resistance).\n \"\"\"\n def __init__(self, maxBirthProb, clearProb):\n \"\"\"\n Initialize a SimpleVirus instance, saves all parameters as attributes\n of the instance.\n maxBirthProb: Maximum reproduction probability (a float between 0-1)\n clearProb: Maximum clearance probability (a float between 0-1).\n \"\"\"\n self.maxBirthProb=maxBirthProb\n self.clearProb=clearProb\n\n\n def doesClear(self):\n \"\"\"\n Stochastically determines whether this virus is cleared from the\n patient's body at a time step.\n returns: Using a random number generator (random.random()), this method\n returns True with probability self.clearProb and otherwise returns\n False.\n \"\"\"\n if random.random() <= self.clearProb:\n return True\n else:\n return False\n\n def reproduce(self, popDensity):\n \"\"\"\n Stochastically determines whether this virus particle reproduces at a\n time step. Called by the update() method in the SimplePatient and\n Patient classes. The virus particle reproduces with probability\n self.maxBirthProb * (1 - popDensity).\n\n If this virus particle reproduces, then reproduce() creates and returns\n the instance of the offspring SimpleVirus (which has the same\n maxBirthProb and clearProb values as its parent).\n\n popDensity: the population density (a float), defined as the current\n virus population divided by the maximum population.\n\n returns: a new instance of the SimpleVirus class representing the\n offspring of this virus particle. The child should have the same\n maxBirthProb and clearProb values as this virus. Raises a\n NoChildException if this virus particle does not reproduce.\n \"\"\"\n if random.random() <= self.maxBirthProb * (1 - popDensity):\n return SimpleVirus(self.maxBirthProb, self.clearProb)\n else:\n raise NoChildException()\n\nclass SimplePatient(object):\n \"\"\"\n Representation of a simplified patient. The patient does not take any drugs\n and his/her virus populations have no drug resistance.\n \"\"\"\n def __init__(self, viruses, maxPop):\n \"\"\"\n Initialization function, saves the viruses and maxPop parameters as attributes.\n viruses: the list representing the virus population (a list of\n SimpleVirus instances)\n maxPop: the maximum virus population for this patient (an integer)\n \"\"\"\n self.viruses=viruses\n self.maxPop=maxPop\n\n def getTotalPop(self):\n \"\"\"\n Gets the current total virus population.\n returns: The total virus population (an integer)\n \"\"\"\n return len(self.viruses)\n\n def update(self):\n \"\"\"\n Update the state of the virus population in this patient for a single\n time step. update() should execute the following steps in this order:\n - Determine whether each virus particle survives and updates the list\n of virus particles accordingly.\n\n - The current population density is calculated. This population density\n value is used until the next call to update()\n\n - Determine whether each virus particle should reproduce and add\n offspring virus particles to the list of viruses in this patient.\n returns: the total virus population at the end of the update (an\n integer)\n \"\"\"\n for i in range(len(self.viruses)-1, -1, -1):\n if self.viruses[i].doesClear():\n self.viruses.pop(i)\n current_popDensity=self.getTotalPop()/self.maxPop\n for virus in self.viruses:\n try:\n self.viruses.append(virus.reproduce(current_popDensity))\n except NoChildException:\n pass\n return self.getTotalPop()\n\nclass NoChildException(Exception):\n \"\"\"\n a NoChildException indicating that the virus particle does not reproduce during the current time step.\n \"\"\"\n pass\n\ndef problem2():\n \"\"\"\n Run the simulation and plot the graph for problem 2 (no drugs are used,\n viruses do not have any drug resistance).\n Instantiates a patient, runs a simulation for 300 timesteps, and plots the\n total virus population as a function of time.\n \"\"\"\n len_viruses=100\n maxPop=1000\n maxBirthProb=0.1\n clearProb=0.05\n timesteps=300\n single_virus=SimpleVirus(maxBirthProb,clearProb)\n viruses=[]\n for i in range(len_viruses):\n viruses.append(single_virus)\n single_patient=SimplePatient(viruses,maxPop)\n #initial state\n x_time=[0]\n y_pop=[100]\n for i in range(1,timesteps+1):\n x_time.append(i)\n y_pop.append(single_patient.update())\n pl.plot(x_time,y_pop)\n pl.xlabel(\"time step\")\n pl.ylabel(\"virus population\")\n pl.title(\"Simulating Virus Population Dynamics without Drug Treatment\")\n pl.show()\n\n#problem2()\n\n\nclass ResistantVirus(SimpleVirus):\n \"\"\"\n Representation of a virus which can have drug resistance.\n \"\"\"\n\n def __init__(self, maxBirthProb, clearProb, resistances, mutProb):\n \"\"\"\n Initialize a ResistantVirus instance, saves all parameters as attributes of the instance.\n maxBirthProb: Maximum reproduction probability (a float between 0-1)\n clearProb: Maximum clearance probability (a float between 0-1).\n resistances: A dictionary of drug names (strings) mapping to the state\n of this virus particle's resistance (either True or False) to each drug.\n e.g. {'guttagonol':False, 'grimpex',False}, means that this virus\n particle is resistant to neither guttagonol nor grimpex.\n mutProb: Mutation probability for this virus particle (a float). This is\n the probability of the offspring acquiring or losing resistance to a drug.\n \"\"\"\n self.maxBirthProb = maxBirthProb\n self.clearProb = clearProb\n self.resistances = resistances\n self.mutProb = mutProb\n\n def getResistance(self, drug):\n \"\"\"\n Get the state of this virus particle's resistance to a drug. This method\n is called by getResistPop() in Patient to determine how many virus\n particles have resistance to a drug.\n drug: the drug (a string).\n returns: True if this virus instance is resistant to the drug, False\n otherwise.\n \"\"\"\n return self.resistances.get(drug, False)\n\n\n def reproduce(self, popDensity, activeDrugs):\n \"\"\"\n Stochastically determines whether this virus particle reproduces at a\n time step. Called by the update() method in the Patient class.\n\n If the virus particle is not resistant to any drug in activeDrugs,\n then it does not reproduce. Otherwise, the virus particle reproduces\n with probability: self.maxBirthProb * (1 - popDensity).\n\n If this virus particle reproduces, then reproduce() creates and returns\n the instance of the offspring ResistantVirus (which has the same\n maxBirthProb and clearProb values as its parent).\n\n For each drug resistance trait of the virus (i.e. each key of\n self.resistances), the offspring has probability 1-mutProb of\n inheriting that resistance trait from the parent, and probability\n mutProb of switching that resistance trait in the offspring.\n\n For example, if a virus particle is resistant to guttagonol but not\n grimpex, and `self.mutProb` is 0.1, then there is a 10% chance that\n that the offspring will lose resistance to guttagonol and a 90%\n chance that the offspring will be resistant to guttagonol.\n There is also a 10% chance that the offspring will gain resistance to\n grimpex and a 90% chance that the offspring will not be resistant to\n grimpex.\n\n popDensity: the population density (a float), defined as the current\n virus population divided by the maximum population\n activeDrugs: a list of the drug names acting on this virus particle\n (a list of strings).\n returns: a new instance of the ResistantVirus class representing the\n offspring of this virus particle. The child should have the same\n maxBirthProb and clearProb values as this virus. Raises a\n NoChildException if this virus particle does not reproduce.\n \"\"\"\n for drug in activeDrugs:\n if not self.getResistance(drug):\n raise NoChildException()\n\n if random.random() <= (self.maxBirthProb * (1 - popDensity)):\n newresistances = {}\n for drug in self.resistances.keys():\n if random.random() <= (1 - self.mutProb):\n newresistances[drug] = self.resistances[drug]\n else:\n newresistances[drug] = not self.resistances[drug]\n return ResistantVirus(self.maxBirthProb, self.clearProb, newresistances, self.mutProb)\n else:\n raise NoChildException()\n\n\n\nclass Patient(SimplePatient):\n \"\"\"\n Representation of a patient. The patient is able to take drugs and his/her virus population\n can acquire resistance to the drugs he/she takes.\n \"\"\"\n def __init__(self, viruses, maxPop):\n \"\"\"\n Initialization function, saves the viruses and maxPop parameters as\n attributes. Also initializes the list of drugs being administered\n (which should initially include no drugs).\n viruses: the list representing the virus population (a list of\n SimpleVirus instances)\n maxPop: the maximum virus population for this patient (an integer)\n \"\"\"\n self.viruses=viruses\n self.maxPop=maxPop\n self.administered=[]\n\n def addPrescription(self, newDrug):\n \"\"\"\n Administer a drug to this patient. After a prescription is added, the\n drug acts on the virus population for all subsequent time steps. If the\n newDrug is already prescribed to this patient, the method has no effect.\n newDrug: The name of the drug to administer to the patient (a string).\n postcondition: list of drugs being administered to a patient is updated\n \"\"\"\n if newDrug not in self.administered:\n self.administered.append(newDrug)\n\n def getPrescriptions(self):\n \"\"\"\n Returns the drugs that are being administered to this patient.\n returns: The list of drug names (strings) being administered to this\n patient.\n \"\"\"\n return self.administered\n\n def getResistPop(self, drugResist):\n \"\"\"\n Get the population of virus particles resistant to the drugs listed in drugResist.\n drugResist: Which drug resistances to include in the population (a list\n of strings - e.g. ['guttagonol'] or ['guttagonol', 'grimpex'])\n returns: the population of viruses (an integer) with resistances to all drugs in the drugResist list.\n \"\"\"\n notresist_pop=0\n for virus in self.viruses:\n for drug in drugResist:\n if virus.getResistance(drug)== False:\n notresist_pop=notresist_pop +1\n break\n resist_pop=len(self.viruses)-notresist_pop\n return resist_pop\n\n def update(self):\n \"\"\"\n Update the state of the virus population in this patient for a single\n time step. update() should execute these actions in order:\n - Determine whether each virus particle survives and update the list of virus particles accordingly\n - The current population density is calculated. This population density value is used until the next call to update().\n - Determine whether each virus particle should reproduce and add offspring virus particles to the list of viruses in this patient.\n The list of drugs being administered should be accounted for in the determination of whether each virus particle reproduces.\n returns: the total virus population at the end of the update (an integer)\n \"\"\"\n for i in range(len(self.viruses) - 1, -1, -1):\n if self.viruses[i].doesClear():\n self.viruses.pop(i)\n current_popDensity = len(self.viruses) / self.maxPop\n for virus in self.viruses:\n try:\n self.viruses.append(virus.reproduce(current_popDensity, self.administered))\n except NoChildException:\n pass\n return self.getTotalPop()\n\n\ndef problem4():\n \"\"\"\n Runs simulations and plots graphs for problem 4.\n Instantiates a patient, runs a simulation for 150 timesteps, adds\n guttagonol, and runs the simulation for an additional 150 timesteps.\n total virus population vs. time and guttagonol-resistant virus population\n vs. time are plotted\n \"\"\"\n len_viruses = 100\n maxPop = 1000\n maxBirthProb = 0.1\n clearProb = 0.05\n resistances = {'guttagonol': False}\n mutProb = 0.005\n timesteps = 300\n resistant_virus = ResistantVirus(maxBirthProb, clearProb, resistances, mutProb)\n viruses = []\n for i in range(len_viruses):\n viruses.append(resistant_virus)\n single_patient = Patient(viruses, maxPop)\n\n x_time = [0]\n y_pop = [100]\n y_pop_resistant = [0]\n for i in range(1, timesteps + 1):\n x_time.append(i)\n y_pop.append(single_patient.update())\n y_pop_resistant.append(single_patient.getResistPop(['guttagonol']))\n if i == 150:\n single_patient.addPrescription(\"guttagonol\")\n\n pl.plot(x_time, y_pop,label=\"Total virus population\")\n pl.plot(x_time, y_pop_resistant,label=\"guttagonol-resistant population\")\n pl.xlabel(\"time step\")\n pl.ylabel(\"virus population\")\n pl.title(\"Simulating Virus Population Dynamics with Drug Treatment\")\n pl.legend()\n pl.show()\n\n#problem4()\n\ndef problem5():\n \"\"\"\n Runs simulations and make histograms for problem 5.\n Runs multiple simulations to show the relationship between delayed treatment and patient outcome.\n Histograms of final total virus populations are displayed for delays of 300,150, 75, 0 timesteps\n (followed by an additional 150 timesteps of simulation).\n \"\"\"\n patientsnum = 200\n len_viruses = 100\n maxPop = 1000\n maxBirthProb = 0.1\n clearProb = 0.05\n resistances = {'guttagonol': False}\n mutProb = 0.005\n timesteps = 150\n resistant_virus = ResistantVirus(maxBirthProb, clearProb, resistances, mutProb)\n delay_timesteps=[300,150,75,0]\n for delaytime in delay_timesteps:\n y_pop_total = []\n cured_num=0\n for i in range(patientsnum):\n viruses = []\n for j in range(len_viruses):\n viruses.append(resistant_virus)\n single_patient = Patient(viruses, maxPop)\n #y_pop = [100]\n for m in range(delaytime + timesteps):\n y_pop = single_patient.update()\n if m == delaytime:\n single_patient.addPrescription(\"guttagonol\")\n y_pop_total.append(y_pop)\n if y_pop<=50:\n cured_num=cured_num+1\n cured_prob=cured_num/patientsnum\n pl.hist(y_pop_total)\n pl.title(str(cured_prob*100) + \"% of patients were cured when the drug added after \" + str(delaytime) + \" timesteps\")\n pl.xlabel('Total virus populations')\n pl.ylabel('Number of patients')\n pl.show()\n\n#problem5()\n\n\ndef problem6():\n \"\"\"\n Runs simulations and make histograms for problem 6.\n Runs multiple simulations to show the relationship between administration\n of multiple drugs and patient outcome.\n Histograms of final total virus populations are displayed for lag times of\n 150, 75, 0 timesteps between adding drugs (followed by an additional 150\n timesteps of simulation).\n \"\"\"\n patientsnum = 30\n len_viruses = 100\n maxPop = 1000\n maxBirthProb = 0.1\n clearProb = 0.05\n resistances = {'guttagonol': False, 'grimpex':False}\n mutProb = 0.005\n timesteps = 150\n resistant_virus = ResistantVirus(maxBirthProb, clearProb, resistances, mutProb)\n lag_timesteps = [300, 150, 75, 0]\n for lagtime in lag_timesteps:\n y_pop_total = []\n cured_num = 0\n for i in range(patientsnum):\n viruses = []\n for j in range(len_viruses):\n viruses.append(resistant_virus)\n single_patient = Patient(viruses, maxPop)\n # y_pop = [100]\n for m in range(timesteps + lagtime + timesteps):\n y_pop = single_patient.update()\n if m == timesteps:\n single_patient.addPrescription(\"guttagonol\")\n if m == (timesteps+lagtime):\n single_patient.addPrescription(\"grimpex\")\n y_pop_total.append(y_pop)\n if y_pop <= 50:\n cured_num = cured_num + 1\n #print(y_pop_total)\n cured_prob = cured_num / patientsnum\n pl.hist(y_pop_total)\n pl.title(str(cured_prob * 100) + \"% of patients were cured when the interval of two drugs is \" + str(lagtime) + \" timesteps\")\n pl.xlabel('Total virus populations')\n pl.ylabel('Number of patients')\n pl.show()\n\nproblem6()\n\ndef problem7():\n \"\"\"\n Run simulations and plot graphs examining the relationship between\n administration of multiple drugs and patient outcome.\n Plots of total and drug-resistant viruses vs. time are made for a\n simulation with a 300 time step delay between administering the 2 drugs and\n a simulations for which drugs are administered simultaneously.\n \"\"\"\n #150-300-150\n len_viruses = 100\n maxPop = 1000\n maxBirthProb = 0.1\n clearProb = 0.05\n resistances = {'guttagonol': False, 'grimpex': False}\n mutProb = 0.005\n timesteps = 150\n lag_time=300\n resistant_virus = ResistantVirus(maxBirthProb, clearProb, resistances, mutProb)\n viruses = []\n for j in range(len_viruses):\n viruses.append(resistant_virus)\n single_patient = Patient(viruses, maxPop)\n y_pop = []\n resist_gut = []\n resist_gri = []\n resist_all = []\n for m in range(timesteps+lag_time+timesteps):\n y_pop.append(single_patient.update())\n resist_gut.append(single_patient.getResistPop(['guttagonol']))\n resist_gri.append(single_patient.getResistPop(['grimpex']))\n resist_all.append(single_patient.getResistPop(['guttagonol', 'grimpex']))\n if m == timesteps:\n single_patient.addPrescription(\"guttagonol\")\n if m == (timesteps + lag_time):\n single_patient.addPrescription(\"grimpex\")\n pl.plot(y_pop,label = 'Total virus population')\n pl.plot(resist_gut,label = 'guttagonol-resistant')\n pl.plot(resist_gri,label = 'grimpex-resistant')\n pl.plot(resist_all,label = 'all-resistant')\n pl.xlabel('virus populations')\n pl.ylabel('Number of patients')\n pl.legend()\n pl.show()\n\n #150-150\n viruses = []\n for j in range(len_viruses):\n viruses.append(resistant_virus)\n single_patient = Patient(viruses, maxPop)\n y_pop = []\n resist_gut = []\n resist_gri = []\n resist_all = []\n for m in range(timesteps+timesteps):\n y_pop.append(single_patient.update())\n resist_gut.append(single_patient.getResistPop(['guttagonol']))\n resist_gri.append(single_patient.getResistPop(['grimpex']))\n resist_all.append(single_patient.getResistPop(['guttagonol', 'grimpex']))\n if m == timesteps:\n single_patient.addPrescription(\"guttagonol\")\n single_patient.addPrescription(\"grimpex\")\n pl.plot(y_pop, label='Total virus population')\n pl.plot(resist_gut, label='guttagonol-resistant')\n pl.plot(resist_gri, label='grimpex-resistant')\n pl.plot(resist_all, label='all-resistant')\n pl.xlabel('Total virus populations')\n pl.ylabel('Number of patients')\n pl.legend()\n pl.show()\n\nproblem7()","sub_path":"Final project.py","file_name":"Final project.py","file_ext":"py","file_size_in_byte":20294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"53334215","text":"# pylint: disable=too-few-public-methods\n\n# Standard libraries. Should not fail.\nimport sys\nimport json\nimport textwrap\n\nfrom argparse import Action\nfrom argparse import ArgumentParser\nfrom argparse import RawTextHelpFormatter\n\n# Required 3rd-party libraries.\ntry:\n from requests_html import HTMLSession\n from tabulate import tabulate\n from colorama import init\n from colorama import Fore\n from colorama import Style\n\n init(autoreset=True)\n\nexcept ImportError as err:\n print(\n 'TPSP: impossible to import 3rd-party libraries.\\n'\n 'Latest traceback: {0}'.format(err.args[0])\n )\n\n sys.exit(1)\n\n\nPROGRAM_NAME = 'tpsp'\nPROGRAM_DESCRIPTION = 'CLI to CPTM and Metro lines status'\nPROGRAM_VERSION = '1.0.1'\nPROGRAM_URL = 'https://github.com/caian-org/tpsp'\n\nCOPYRIGHT_INFO = \"\"\"\nThe person who associated a work with this deed has dedicated the work to the\npublic domain by waiving all of his or her rights to the work worldwide under\ncopyright law, including all related and neighboring rights, to the extent\nallowed by law.\n\nYou can copy, modify, distribute and perform the work, even for commercial\npurposes, all without asking permission.\n\nAFFIRMER OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\nANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,\nINCLUDING WITHOUT LIMITATION WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR\nA PARTICULAR PURPOSE, NON INFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER\nDEFECTS, ACCURACY, OR THE PRESENT OR ABSENCE OF ERRORS, WHETHER OR NOT\nDISCOVERABLE, ALL TO THE GREATEST EXTENT PERMISSIBLE UNDER APPLICABLE LAW.\n\nFor more information, please see\n\n\"\"\"\n\n\nclass CLI:\n def __init__(self):\n self.sources = list(Service.all())\n\n self.parser = ArgumentParser(\n prog=PROGRAM_NAME,\n formatter_class=RawTextHelpFormatter,\n description=textwrap.dedent(\n '''\\\n {0}: {1}\n\n {0} (portuguese for \"São Paulo public transportation\")\n is a tiny command-line tool that tells you the current\n status of CPTM's and Metro lines.\n '''.format(\n PROGRAM_NAME, PROGRAM_DESCRIPTION\n )\n ),\n epilog=textwrap.dedent(\n '''\\\n examples:\n $ {0} cptm\n # => shows the current state of all CPTM lines\n\n $ {0} metro --json\n # => shows the current state of all Metro lines and formats\n the output in JSON\n\n This is a Free and Open-Source Software (FOSS).\n Project page: <{1}>'''.format(\n PROGRAM_NAME, PROGRAM_URL\n )\n ),\n )\n\n # --------------------------------------------------\n\n self.parser.add_argument(\n 'service',\n action='store',\n choices=self.sources,\n nargs=1,\n type=str,\n help='the public transportation service',\n )\n\n self.parser.add_argument(\n '-v',\n '--version',\n action='version',\n version='{0} ({1})'.format(PROGRAM_NAME, PROGRAM_VERSION),\n help='show the program version and exit',\n )\n\n self.parser.add_argument(\n '-j',\n '--json',\n action='store_true',\n dest='json',\n help='show the output in JSON format',\n )\n\n self.parser.add_argument(\n '--copyright',\n action=Copyright,\n nargs=0,\n help='show the copyright information and exit',\n )\n\n def act(self):\n return self.parser.parse_args()\n\n\nclass Copyright(Action):\n def __init__(self, option_strings, dest, **kwargs):\n super().__init__(option_strings, dest, **kwargs)\n\n def __call__(self, parser, namespace, values, option_string=None):\n print(COPYRIGHT_INFO)\n sys.exit(0)\n\n\nclass Service:\n @staticmethod\n def all():\n for ds in Service.__subclasses__():\n yield ds.__name__.lower()\n\n\nclass CPTM(Service):\n def __init__(self):\n self.url = 'https://www.cptm.sp.gov.br/Pages/Home.aspx'\n self.session = HTMLSession()\n\n def fetch_data(self):\n refs = ['rubi', 'diamante', 'esmeralda', 'turquesa', 'coral', 'safira', 'jade']\n res = self.session.get(self.url)\n\n for ref in refs:\n data = res.html.find('.{0}'.format(ref), first=True)\n yield {\n 'line': ref.capitalize(),\n 'status': data.text.replace(ref.upper(), ''),\n }\n\n\nclass METRO(Service):\n def __init__(self):\n self.url = 'http://www.metro.sp.gov.br/Sistemas/direto-do-metro-via4/diretodoMetroHome.aspx'\n self.session = HTMLSession()\n\n def fetch_data(self):\n res = self.session.get(self.url)\n\n names = res.html.find('.{0}'.format('nomeDaLinha'))\n stati = res.html.find('.{0}'.format('statusDaLinha'))\n\n for idx, name in enumerate(names):\n line = name.text.split('-')[1]\n status = stati[idx].text\n\n yield {'line': line.strip(), 'status': status}\n\n\nclass Output:\n def __init__(self, data):\n self.data = data\n\n @property\n def table(self):\n def header(cols):\n for col in cols:\n yield '{}{}{}'.format(Style.BRIGHT, col, Style.RESET_ALL)\n\n def line_status(status):\n color = Fore.WHITE\n if 'normal' in status:\n color = Fore.GREEN\n\n elif 'reduzida' in status:\n color = Fore.YELLOW\n\n elif 'paralisada' in status:\n color = Fore.RED\n\n elif 'encerrada' in status:\n color = Style.DIM\n\n return '{}{}{}'.format(color, status.title(), Style.RESET_ALL)\n\n def beautify():\n for data in self.data:\n yield [data['line'], line_status(data['status'].lower())]\n\n cols = ['Linha', 'Status']\n return tabulate(list(beautify()), headers=list(header(cols)))\n\n @property\n def json(self):\n return json.dumps(\n {'code': 200, 'data': list(self.data), 'message': 'success'},\n ensure_ascii=False,\n sort_keys=True,\n indent=4,\n )\n\n\ndef main():\n cli = CLI()\n args = cli.act()\n\n service = getattr(sys.modules[__name__], args.service[0].upper())\n\n try:\n data = service().fetch_data()\n outp = Output(data)\n print('\\n{}'.format(outp.json if args.json else outp.table))\n\n except Exception as error:\n print('Could not fetch data\\n')\n print(str(error))\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tpsp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"284734100","text":"# coding:utf-8\r\n__author__ = 'xudazhou'\r\n\r\n\"\"\"\r\n读文件 然后再写回\r\n\"\"\"\r\nf = open(\"hello2.txt\", \"r+\")\r\ntext = \"\"\r\nfor line in f:\r\n if \"hello jim\" == line.strip():\r\n text += \"jack\\n\"\r\n else:\r\n text += line\r\n\r\nprint(text)\r\n\r\nf.seek(0)\r\nf.truncate()\r\nf.write(text)\r\n\r\nf.close()\r\n","sub_path":"python/file/filerw2.py","file_name":"filerw2.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"330275301","text":"n=int(input())\nstudent=[]\nfor _ in range(n):\n student.append(list(map(int, input().split())))\nfor i in student:\n rank=1\n for j in student:\n if i[0] h)\n psiBc[lbound,0] = 0.0\n for j in ubound[0]:\n psiBc[j,0] = in1[j - ny1] \n psiBc[-1,:] = psiBc[-1,0]\n psiBc[:,-1] = psiBc[:,-2] \n return psiBc\n\n#def parProf(h,y):\n# return - (16.0/3.0)*(y**3 - h**3) + 12.0*(y**2 - h**2) - 8.0*(y - h)","sub_path":"explicitScheme/streamFunction/constructBc.py","file_name":"constructBc.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"169612410","text":"import threading as thread\nimport time\nimport conf\nfrom pymongo import MongoClient\n\n\nmongod_base_host = MongoClient(conf.main_host, conf.main_port)\nmongod_base = mongod_base_host.get_database(conf.main_base)\nmongod_coll = mongod_base.get_collection('positions')\n\nmeter_file = conf.meter_file_to\n\n\nclass CleanUsedDataThread(thread.Thread):\n\n def __init__(self):\n thread.Thread(self, name='CleanUsedDataThread')\n\n def run(self):\n while True:\n time.sleep(60)\n curr_hour = time.localtime(time.strftime(time.time()))\n mongod_coll.delete_many({'TIME': curr_hour})\n if meter_file.__sizeof__() >= 1024 * 1024 * 24:\n meter_file.mode = 'w'\n meter_file.write('')\n meter_file.mode = 'a'\n","sub_path":"data/data_manager.py","file_name":"data_manager.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"37804661","text":"from django.core.management.base import BaseCommand, CommandError\nfrom usaspending_api.references.models import ToptierAgency, SubtierAgency, OfficeAgency, Agency\nimport os\nimport csv\nimport logging\nimport django\n\n\nclass Command(BaseCommand):\n help = \"Loads agencies and sub-tier agencies from authoritative OMB list in \\\n the folder of this management command.\"\n\n logger = logging.getLogger('console')\n\n def handle(self, *args, **options):\n\n try:\n with open(os.path.join(django.conf.settings.BASE_DIR,\n 'usaspending_api/references/management/commands/agency_list.csv')) \\\n as csvfile:\n\n reader = csv.DictReader(csvfile)\n for row in reader:\n fpds_code = row.get('FPDS DEPARTMENT ID', '')\n cgac_code = row.get('CGAC AGENCY CODE', '')\n department_name = row.get('AGENCY NAME', '')\n subtier_name = row.get('SUB TIER NAME', '')\n subtier_code = row.get('SUB TIER CODE', '')\n\n toptier_agency = None\n subtier_agency = None\n\n # Toptier agency\n toptier_agency, created = ToptierAgency.objects.get_or_create(cgac_code=cgac_code,\n fpds_code=fpds_code,\n name=department_name)\n\n subtier_agency, created = SubtierAgency.objects.get_or_create(subtier_code=subtier_code,\n name=subtier_name)\n\n # Create new summary agency object\n agency, created = Agency.objects.get_or_create(toptier_agency=toptier_agency,\n subtier_agency=subtier_agency)\n\n # self.logger.log(20, \"loaded %s\" % agency)\n\n except IOError:\n self.logger.log(\"Could not open file to load from\")\n","sub_path":"usaspending_api/references/management/commands/loadagencies.py","file_name":"loadagencies.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"538217519","text":"\"\"\"\ntree_view.py\n\"\"\"\n\n# Load the needed packages\nimport code\nimport pyart\n\nimport sys\nimport os\n\npath = os.path.dirname(sys.modules[__name__].__file__)\npath = os.path.join(path, '...')\nsys.path.insert(0, path)\n\nimport artview\n\nfrom ..core import Component, Variable, common, QtGui, QtCore, componentsList\n\n# get list of read functions\nimport inspect\naux_read_functions = inspect.getmembers(pyart.aux_io, inspect.isfunction)\nread_functions = [\n pyart.io.read,\n pyart.io.read_grid,\n pyart.io.read_grid_mdv] + [a[1] for a in aux_read_functions]\ntry:\n read_functions.append(pyart.io.read_legacy_grid)\nexcept:\n pass\n\n# test for missing dependency\nbrocken_read_functions = []\ntry:\n for func in read_functions:\n try:\n func(None)\n except pyart.exceptions.MissingOptionalDependency:\n brocken_read_functions.append(func)\n except:\n pass\nexcept:\n pass\n\n\nclass FileList(Component):\n '''\n Open an interactive python console so the direct manipulation\n '''\n\n Vradar = None #: see :ref:`shared_variable`\n Vgrid = None #: see :ref:`shared_variable`\n\n @classmethod\n def guiStart(self, parent=None):\n '''Graphical interface for starting this class.'''\n kwargs, independent = \\\n common._SimplePluginStart(\"FileList\").startDisplay()\n kwargs['parent'] = parent\n return self(**kwargs), independent\n return self(), False\n\n def __init__(self, dirIn=None, name=\"FileList\", parent=None):\n '''Initialize the class to create the interface.\n\n Parameters\n ----------\n [Optional]\n dirIn: string\n Initial directory path to open.\n name : string\n Field Radiobutton window name.\n parent : PyQt instance\n Parent instance to associate to this class.\n If None, then Qt owns, otherwise associated with parent PyQt\n instance.\n '''\n super(FileList, self).__init__(name=name, parent=parent)\n self.listView = QtGui.QListView()\n\n # set up listView\n model = QtGui.QFileSystemModel()\n model.setFilter(QtCore.QDir.AllEntries |\n QtCore.QDir.AllDirs |\n QtCore.QDir.NoDot)\n model.setRootPath(QtCore.QDir.currentPath())\n self.listView.setModel(model)\n if dirIn is None: # avoid reference to path while building doc\n dirIn = os.getcwd()\n index = model.index(dirIn)\n self.listView.setRootIndex(index)\n # self.clicked.connect(self.test)\n self.listView.doubleClicked.connect(self.doubleClick)\n # context (right-click) menu\n self.listView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)\n\n # setup widget\n self.setCentralWidget(self.listView)\n self.listView.customContextMenuRequested.connect(self.contextMenu)\n self.Vradar = Variable(None)\n self.Vgrid = Variable(None)\n self.sharedVariables = {\"Vradar\": None,\n \"Vgrid\": None}\n self.connectAllVariables()\n self.show()\n\n def doubleClick(self, index):\n '''Open Directory or File on double click.'''\n model = self.listView.model()\n indexItem = model.index(index.row(), 0, index.parent())\n if model.fileName(indexItem) == '..':\n if index.parent().parent().isValid():\n self.listView.setRootIndex(index.parent().parent())\n elif model.isDir(index):\n self.listView.setRootIndex(index)\n else:\n self.open(model.filePath(indexItem))\n\n def open(self, path):\n '''Open file.'''\n # try several open\n print (\"open: %s\" % path)\n self.filename = str(path)\n try:\n radar = pyart.io.read(self.filename, delay_field_loading=True)\n # Add the filename for Display\n radar.filename = self.filename\n self.Vradar.change(radar)\n return\n except:\n try:\n radar = pyart.io.read(self.filename)\n # Add the filename for Display\n radar.filename = self.filename\n self.Vradar.change(radar)\n return\n except:\n import traceback\n print(traceback.format_exc())\n radar_warning = True\n try:\n grid = pyart.io.read_grid(\n self.filename, delay_field_loading=True)\n self.Vgrid.change(grid)\n return\n except:\n try:\n grid = pyart.io.read_grid(self.filename)\n self.Vgrid.change(grid)\n return\n except:\n import traceback\n print(traceback.format_exc())\n grid_warning = True\n\n if grid_warning or radar_warning:\n msg = \"Py-ART didn't recognize this file!\"\n common.ShowWarning(msg)\n else:\n msg = \"Could not open file, invalid mode!\"\n common.ShowWarning(msg)\n return\n\n def contextMenu(self, pos):\n '''Contruct right-click menu.'''\n menu = QtGui.QMenu(self)\n index = self.listView.currentIndex()\n path = str(self.listView.model().filePath(index))\n for func in read_functions:\n action = QtGui.QAction(\"Open with: %s\" % func.__name__, self)\n # lambda inside loop: problem with variable capturing\n if func not in brocken_read_functions:\n f = lambda boo, func=func: self.open_with(func, path)\n action.triggered.connect(f)\n else:\n action.setEnabled(False)\n menu.addAction(action)\n menu.exec_(self.listView.mapToGlobal(pos))\n\n def open_with(self, func, path):\n '''Open file using a given function.'''\n try:\n container = func(path, delay_field_loading=True)\n if isinstance(container, pyart.core.Radar):\n self.Vradar.change(container)\n elif isinstance(container, pyart.core.Grid):\n self.Vgrid.change(container)\n else:\n raise NotImplementedError(\"Unknown container type %s\\n\" %\n container)\n return\n except:\n import traceback\n error = traceback.format_exc()\n common.ShowLongText((\"Opening file %s with %s fails\\n\\n\" %\n (path, func.__name__)) + error)\n traceback.format_exc()\n\n\n_plugins = [FileList]\n","sub_path":"artview/plugins/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":6582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"36768448","text":"\"\"\"\nhttps://leetcode.com/problems/find-all-anagrams-in-a-string/\n\nGiven a string s and a non-empty string p, find all the start indices of p's anagrams in s.\n\nStrings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.\n\nThe order of output does not matter.\n\nExample 1:\n\nInput:\ns: \"cbaebabacd\" p: \"abc\"\n\nOutput:\n[0, 6]\n\nExplanation:\nThe substring with start index = 0 is \"cba\", which is an anagram of \"abc\".\nThe substring with start index = 6 is \"bac\", which is an anagram of \"abc\".\nExample 2:\n\nInput:\ns: \"abab\" p: \"ab\"\n\nOutput:\n[0, 1, 2]\n\nExplanation:\nThe substring with start index = 0 is \"ab\", which is an anagram of \"ab\".\nThe substring with start index = 1 is \"ba\", which is an anagram of \"ab\".\nThe substring with start index = 2 is \"ab\", which is an anagram of \"ab\".\n\n\"\"\"\n\n\nclass Solution:\n def findAnagrams(self, s: str, p: str) :\n n1 = len(s) ## get the lenght of s\n n2 = len(p) ## Get the lenght of p\n ans = [] ## Initialize ans as empty array\n ## Cover the base/edge cases\n if n1 == 0 or n1 < n2:\n return []\n s_array = [0] * 26 ## since lower case english characters\n p_array = [0] * 26 ## since lower case english characters\n ascii_a = ord('a') ## get the ascii of character a\n\n # populate array wit the frequencies\n for chr in p:\n p_array[ord(chr) - ascii_a] += 1\n #print(p_array)\n ## populate the array with frequencies upto the lenght of string p\n for i in range(n2):\n s_array[ord(s[i]) - ascii_a] += 1\n #print(s_array)\n i = 0;\n while (i + n2 < n1): ## While the sliding window does not go out of the string\n if is_anagram(s_array, p_array) :\n ans.append(i)\n s_array[ord(s[i]) - ascii_a] -= 1 ## remove the first element of the sliding\n t=ord(s[i + n2])\n s_array[t - ascii_a] += 1 ## add new element in the sluding window\n i += 1\n if is_anagram(s_array, p_array):\n ans.append(i)\n return ans\n\ndef is_anagram(s_array, p_array):\n for i in range(26):\n if s_array[i] != p_array[i]:\n return False\n return True\n\n\nobject=Solution()\n\ns=\"cbaebabacd\"\np=\"abc\"\n\n# s=\"abab\"\n# p=\"ab\"\n\n\nresult=object.findAnagrams(s,p)\n\nprint(result)\n\n\n\n\n","sub_path":"Leetcode/python/Medium/find-all-anagrams-in-a-string.py","file_name":"find-all-anagrams-in-a-string.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"153186980","text":"repeat=1 #to run at least once.\nwhile repeat: \n\t\n\tx=int(input(\"\\nEnter the size of the square matrix: \"))\n\t\n\t#creates a zero matrix\n\tlist=[[0 for i in range(x)] for i in range(x)]\n\n\ti,a=0,1\n\t\n\t#for a 1x1 matrix, the loop is going to stop at the first control point. Each time indices are increased by 1, the code advances two more steps.\n\t\n\tfor b in range(x):\n\t\t\n\t\t#goes rigt\n\t\tfor j in range(b,x-b):\n\t\t\tlist[i][j]=a\n\t\t\ta=a+1\n\t\t\t\n\t\t#control point \n\t\tif x%2 == 1 and b==x-2:\n\t\t\tbreak\n\t\t\t\n\t\t#goes down\n\t\tfor i in range(b+1,x-(b)):\n\t\t\tlist[i][j]=a\n\t\t\ta=a+1\n\t\t\t\n\t\t#goes left\n\t\tfor j in reversed(range(b,x-(b+1))):\n\t\t\tlist[i][j]=a\n\t\t\ta=a+1\n\t\t\t\n\t\t#control point\t\n\t\tif x%2 == 0 and b==x-3:\n\t\t\tbreak\n\t\t\t\n\t\t#goes up\n\t\tfor i in reversed(range(b+1,x-(b+1))):\n\t\t\tlist[i][j]=a\n\t\t\ta=a+1\n\t\t\t\n\t#output:\n\tprint()\n\tfor o in range(x):\n\t\tprint(list[o])\n\t\t\n\trepeat=int(input('\\nType any number to run it again, type \"0\" to exit. --> '))\n","sub_path":"Spiral matrix.py","file_name":"Spiral matrix.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"463794254","text":"#\n# @lc app=leetcode.cn id=121 lang=python3\n#\n# [121] 买卖股票的最佳时机\n#\n# https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/\n#\n# algorithms\n# Easy (50.41%)\n# Likes: 555\n# Dislikes: 0\n# Total Accepted: 79.6K\n# Total Submissions: 156.9K\n# Testcase Example: '[7,1,5,3,6,4]'\n#\n# 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。\n#\n# 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。\n#\n# 注意你不能在买入股票前卖出股票。\n#\n# 示例 1:\n#\n# 输入: [7,1,5,3,6,4]\n# 输出: 5\n# 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。\n# ⁠ 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。\n#\n#\n# 示例 2:\n#\n# 输入: [7,6,4,3,1]\n# 输出: 0\n# 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。\n#\n#\n#\n\n\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n cost, profit = float('inf'), 0\n for price in prices:\n cost = min(price, cost)\n profit = max(profit, price-cost)\n return profit\n","sub_path":".leetcode/121.买卖股票的最佳时机.py","file_name":"121.买卖股票的最佳时机.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"634329445","text":"import npyscreen\nimport curses.ascii\nfrom curses import endwin\nfrom .communication_framework import hand, Comframe, getOpenPorts\nfrom .ui_widgets import TSlider, TimeSlider, BoxSelectOne, BoxOptions, PortBox\n\nclass MainForm(npyscreen.FormBaseNew):\n DEFAULT_LINES = 26\n\n def create(self):\n # Init Form and Objects\n if(self.parentApp.demomode is True):\n self.name = \"3D-Bionics Hand Control Software DEMO\"\n else:\n self.name = \"3D-Bionics Hand Control Software\"\n\n self.comframe = self.parentApp.comframe\n self.hand = self.parentApp.hand\n\n y, x = self.useable_space()\n\n left = round(x*2/3)\n \n # Create UI\n self.nextrely = 3\n self.klein = self.add(TSlider, max_width=left,name = \"Klein\")\n self.nextrely +=1\n self.ring = self.add(TSlider, max_width=left, name = \"Ring\")\n self.nextrely +=1\n self.mittel = self.add(TSlider, max_width=left, name = \"Mittel\")\n self.nextrely +=1\n self.zeige = self.add(TSlider, max_width=left, name = \"Zeige\")\n self.nextrely +=1\n self.daumen = self.add(TSlider, max_width=left, name = \"Daumen\")\n\n self.nextrely += 3\n self.timeslider = self.add(TimeSlider, max_width=round(left/1.5), value=0.3, name = \"Delay\", hidden = True)\n\n self.nextrely = y-3\n self.ports = self.add(PortBox,max_width=left)\n\n self.nextrelx = left + 10\n self.nextrely = 2\n self.quickPos = self.add(BoxSelectOne, max_height= round((y-2)/2), name = \"Quick Positions\")\n self.nextrely += 1\n self.reloadPos = self.add(npyscreen.ButtonPress, name=\"Nochmal!\", relx=self.nextrelx+15, when_pressed_function = lambda : self.quickPos.entry_widget.setPosition() )\n self.nextrely += 1\n self.options = self.add(BoxOptions)\n\n # init handlers\n\n handlers = {\n '^Q': self.exit_func,\n curses.ascii.ESC: self.exit_func\n }\n\n self.add_handlers(handlers)\n\n # Additional Config\n\n self.keypress_timeout=1\n\n def afterEditing(self):\n self.parentApp.setNextForm(None)\n\n def while_waiting(self):\n self.updatePos()\n\n\n def sendPos(self):\n \n new_pos = [[\n int(self.klein.value),\n int(self.ring.value),\n int(self.mittel.value),\n int(self.zeige.value),\n int(self.daumen.value)\n ]]\n\n self.comframe.queue_clear()\n self.comframe.queue_position(new_pos)\n \n\n def reloadQuickPos(self):\n self.quickPos.entry_widget.setPosition()\n\n def updatePos(self):\n self.klein.set_value(self.hand.getKlein())\n self.mittel.set_value(self.hand.getMittel())\n self.ring.set_value(self.hand.getRing())\n self.zeige.set_value(self.hand.getZeige())\n self.daumen.set_value(self.hand.getDaumen())\n self.display()\n \n # Various functions\n def exit_func(self, _input):\n self.editing = False\n\n\nclass hand_controll(npyscreen.NPSAppManaged):\n\n def __init__(self, comframe: Comframe,hand: hand,demomode = None):\n self.comframe = comframe\n self.hand = hand\n self.demomode = demomode\n super(hand_controll,self).__init__()\n\n def onStart(self):\n self.addForm(\"MAIN\", MainForm)\n\n","sub_path":"handcontrol/src/ui_App.py","file_name":"ui_App.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"496331722","text":"import requests\nfrom flask import jsonify\nfrom datetime import datetime\nfrom app import mongo\nfrom app.config import MKR_balance,MKR_transactions\n\n#----------Function for fetching tx_history and balance storing in mongodb----------\n\ndef mkr_data(address,symbol,type_id):\n print(\"011111\")\n ret=MKR_balance.replace(\"{{address}}\",''+address+'')\n print(ret)\n response_user_token = requests.get(url=ret)\n response = response_user_token.json() \n \n doc=MKR_transactions.replace(\"{{address}}\",''+address+'')\n print(doc)\n response_user = requests.get(url=doc)\n res = response_user.json() \n transactions=res['result']\n print(\"8888\")\n array=[]\n for transaction in transactions:\n frm=[]\n to=[]\n fee =\"\"\n timestamp = transaction['timeStamp']\n first_date=int(timestamp)\n dt_object = datetime.fromtimestamp(first_date)\n fro =transaction['from']\n too=transaction['to']\n send_amount=transaction['value']\n contractAddress = transaction['contractAddress']\n if contractAddress == \"0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2\":\n to.append({\"to\":too,\"receive_amount\":\"\"})\n frm.append({\"from\":fro,\"send_amount\":(int(send_amount)/1000000000000000000)})\n array.append({\"fee\":fee,\"from\":frm,\"to\":to,\"date\":dt_object})\n print(\"333333\")\n balance = response['result']\n amount_recived =\"\"\n amount_sent =\"\"\n print(\"377777\")\n ret = mongo.db.sws_history.update({\n \"address\":address \n },{\n \"$set\":{\n \"address\":address,\n \"symbol\":symbol,\n \"type_id\":type_id,\n \"balance\":(int(balance)/1000000000000000000),\n \"transactions\":array,\n \"amountReceived\":amount_recived,\n \"amountSent\":amount_sent\n }},upsert=True)\n print(\"50000000\")\n return jsonify({\"status\":\"success\"})\n","sub_path":"app/mkr.py","file_name":"mkr.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"150432685","text":"from __future__ import division\nimport nltk\nfrom nltk.corpus import wordnet as wn\nfrom nltk.corpus import brown\nimport math\nimport numpy as np\nimport sys\nfrom .param import *\nfrom . import distribution\n\n\nFreq_Arr = dict()\nN = 0\n\n\ndef most_similar_word(word, word_set):\n max_sim = -1.0\n sim_word = \"\"\n for ref_word in word_set:\n sim = distribution.word_similarity(word, ref_word)\n if sim > max_sim:\n max_sim = sim\n sim_word = ref_word\n return sim_word, max_sim\n \ndef info_content(lookup_word):\n global N\n if N == 0:\n for sent in brown.sents():\n for word in sent:\n word = word.lower()\n if not Freq_Arr.has_key(word):\n Freq_Arr[word] = 0\n Freq_Arr[word] = Freq_Arr[word] + 1\n N = N + 1\n lookup_word = lookup_word.lower()\n n = 0 if not Freq_Arr.has_key(lookup_word) else Freq_Arr[lookup_word]\n return 1.0 - (math.log(n + 1) / math.log(N + 1))\n \ndef semantic_vector(words, joint_words, info_content_norm):\n sent_set = set(words)\n semvec = np.zeros(len(joint_words))\n i = 0\n for joint_word in joint_words:\n if joint_word in sent_set:\n semvec[i] = 1.0\n if info_content_norm:\n semvec[i] = semvec[i] * math.pow(info_content(joint_word), 2)\n else:\n sim_word, max_sim = most_similar_word(joint_word, sent_set)\n semvec[i] = PHI if max_sim > PHI else 0.0\n if info_content_norm:\n semvec[i] = semvec[i] * info_content(joint_word) * info_content(sim_word)\n i = i + 1\n return semvec \n \ndef semantic_similarity(sentence_1, sentence_2, info_content_norm):\n words_1 = nltk.word_tokenize(sentence_1)\n words_2 = nltk.word_tokenize(sentence_2)\n joint_words = set(words_1).union(set(words_2))\n vec_1 = semantic_vector(words_1, joint_words, info_content_norm)\n vec_2 = semantic_vector(words_2, joint_words, info_content_norm)\n return np.dot(vec_1, vec_2.T) / (np.linalg.norm(vec_1) * np.linalg.norm(vec_2))\n\n\ndef word_order_vector(words, joint_words, windex):\n wovec = np.zeros(len(joint_words))\n i = 0\n wordset = set(words)\n for joint_word in joint_words:\n if joint_word in wordset:\n wovec[i] = windex[joint_word]\n else:\n sim_word, max_sim = most_similar_word(joint_word, wordset)\n if max_sim > ETA:\n wovec[i] = windex[sim_word]\n else:\n wovec[i] = 0\n i = i + 1\n return wovec\n\ndef word_order_similarity(sentence_1, sentence_2):\n words_1 = nltk.word_tokenize(sentence_1)\n words_2 = nltk.word_tokenize(sentence_2)\n joint_words = list(set(words_1).union(set(words_2)))\n windex = {x[1]: x[0] for x in enumerate(joint_words)}\n r1 = word_order_vector(words_1, joint_words, windex)\n r2 = word_order_vector(words_2, joint_words, windex)\n return 1.0 - (np.linalg.norm(r1 - r2) / np.linalg.norm(r1 + r2))\n\n\ndef similarity(sentence_1, sentence_2, info_content_norm):\n return DELTA * semantic_similarity(sentence_1, sentence_2, info_content_norm) + \\\n (1.0 - DELTA) * word_order_similarity(sentence_1, sentence_2)","sub_path":"majorproject/path_len_sim.py","file_name":"path_len_sim.py","file_ext":"py","file_size_in_byte":3240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"514324722","text":"from nextcord.embeds import Embed\nfrom nextcord.activity import ActivityType, Activity\nfrom nextcord.ext import commands\nfrom yaml import load as load_yaml, Loader\nfrom math import floor\nfrom re import search\nfrom random import randint\nimport api\n\ndef load_config():\n with open('config.yml') as file:\n data = file.read()\n parsed_data = load_yaml(data, Loader=Loader)\n return parsed_data\n\ndef add_empty_field(embed):\n embed.add_field(name='\\u200b', value='\\u200b', inline=True)\n\ndef add_act(act_name, data, embed: Embed):\n embed.add_field(name=act_name, value='```yml\\nRank: {}\\nWins: {}\\nGames: {}\\nWinrate: {:.1f}%```'.format(data['final_rank_patched'] if 'final_rank_patched' in data else 'Unranked', data['wins'] if 'wins' in data else 0, data['number_of_games'] if 'number_of_games' in data else 0, data['wins'] / data['number_of_games'] * 100 if 'number_of_games' in data else 0))\n\ndef positive_or_negative(num):\n if num < 0:\n return ''\n else:\n return '+'\n\ndef random_display_for_bundle():\n random = randint(1,2)\n if random == 1:\n return 'displayIcon'\n else:\n return 'displayIcon2'\n\ndef calculate_game_acs(score, rounds):\n return score / rounds\n\ndef won_or_lose_game(player, blue):\n team = player['team'].lower()\n\n if blue['has_won'] and team == 'blue':\n return True\n elif not blue['has_won'] and team == 'red':\n return True\n else:\n return False\n\ndef format_rounds_win_lose(player_team):\n return '{}-{}'.format(player_team['rounds_won'], player_team['rounds_lost'])\n\ndef format_win_lose(result):\n if result:\n return 'Win'\n else:\n return 'Lose'\n\ndef format_game_kda(kills, deaths, assists):\n return '{} / {} / {}'.format(kills, deaths, assists)\n\ndef add_game(game_data, embed: Embed, rr_change):\n player = game_data['player']\n\n if not 'player' in game_data:\n return\n\n player_team = player['team'].lower()\n player_stats = player['stats']\n embed.add_field(\n name='**{} | {} | {} | {}**'.format(player['character'], game_data['map'], format_win_lose(won_or_lose_game(player, game_data['blue'])), '{}{}'.format(positive_or_negative(rr_change), rr_change)), \n value='```yml\\nScore: {}\\nACS: {:.0f}\\nKDA: {}\\nAvg Damage/Round: {:.0f}\\nRounds: {}\\nStart: {}```'.format(format_rounds_win_lose(game_data[player_team]), calculate_game_acs(player_stats['score'], game_data['rounds_played']), format_game_kda(player_stats['kills'], player_stats['deaths'], player_stats['assists']), player['damage_made'] / game_data['rounds_played'], game_data['rounds_played'], game_data['game_start_patched']),\n inline=True\n )\n\ndef calculate_total_mmr_stats(seasons):\n wins = 0\n losses = 0\n games = 0\n\n for key, season in seasons.items():\n if not 'error' in season:\n wins += season['wins']\n losses += (season['number_of_games'] - season['wins'])\n games += season['number_of_games']\n \n return {\n 'wins': wins,\n 'losses': losses,\n 'games': games\n }\n\nvalorant_name_regex = '^.+#.+$'\n\nconfig = load_config()\n\nbot = commands.Bot(command_prefix=config['prefix'])\n\n@commands.cooldown(1, 5, commands.BucketType.user)\n@bot.command()\nasync def ping(ctx):\n await ctx.reply('Pong! `{}ms`'.format(floor(bot.latency * 1000)))\n\n@commands.cooldown(1, 15, commands.BucketType.user)\n@bot.command(name='store', aliases=['bundle'])\nasync def val_store(ctx):\n bundle = api.get_store_bundle()\n \n if not bundle:\n return await ctx.reply('An error has occurred.')\n \n data = bundle['data']\n \n bundle_embed = Embed(title='**{}**'.format(data['displayName']), description='**{}**\\n{}'.format(data['description'], data['extraDescription']), color=0x001b3b)\n bundle_embed.set_image(url=data[random_display_for_bundle()])\n\n await ctx.send(embed=bundle_embed)\n\n@commands.cooldown(1, 15, commands.BucketType.user)\n@bot.command(name='rank-history', aliases=['episodes', 'acts'])\nasync def mmr(ctx, *args):\n profile_text = ' '.join(args)\n await ctx.reply('Fetching Rank history for `{}` ...'.format(profile_text))\n\n if not search(valorant_name_regex, profile_text):\n return await ctx.reply('The valorant profile must be in the format `name#tag`')\n\n name_tag = profile_text.split('#')\n\n profile = api.get_profile(name_tag[0], name_tag[1])\n \n if not profile:\n return await ctx.reply('An error has occurred.')\n \n profile_data = profile['data']\n profile_card = profile_data['card']\n\n mmr = api.get_mmr(profile_data['region'], name_tag[0], name_tag[1])\n\n if not mmr:\n return await ctx.reply('An error has occurred.')\n \n mmr_data = mmr['data']\n seasons = mmr_data['by_season']\n\n profile_embed = Embed(title='Rank History for: **{}#{}**'.format(name_tag[0], name_tag[1]), color=0xF24D4E)\n \n profile_embed.set_author(name='{}#{}'.format(profile_data['name'], profile_data['tag']), icon_url=profile_card['small'])\n\n for key in seasons:\n add_act(key.upper(), seasons[key], profile_embed)\n\n\n total_stats_embed = Embed(title='', color=0xF24D4E)\n total_data = calculate_total_mmr_stats(seasons)\n\n total_stats_embed.add_field(name='Ranked Total Wins', value='```diff\\n+ {}```'.format(total_data['wins']), inline=True)\n total_stats_embed.add_field(name='Ranked Total Losses', value='```diff\\n- {}```'.format(total_data['losses']), inline=True)\n total_stats_embed.add_field(name='Ranked Winrate', value='```fix\\n{:.2f}%```'.format((total_data['wins'] / total_data['games']) * 100), inline=True)\n \n \n await ctx.send(embed=profile_embed)\n await ctx.send(embed=total_stats_embed)\n\n@commands.cooldown(1, 20, commands.BucketType.user)\n@bot.command(name='competitive', aliases=['comp', 'ranked'])\nasync def comp_match_history(ctx, *args):\n profile_text = ' '.join(args)\n await ctx.reply('Fetching Competitive data for `{}` ...'.format(profile_text))\n\n if not search(valorant_name_regex, profile_text):\n return await ctx.reply('The valorant profile must be in the format `name#tag`')\n\n name_tag = profile_text.split('#')\n profile = api.get_profile(name_tag[0], name_tag[1])\n\n if not profile:\n return await ctx.reply('An error has occurred.')\n \n profile_data = profile['data']\n profile_card = profile_data['card']\n\n rr_changes = api.get_rr_changes(profile_data['region'], profile_data['name'], profile_data['tag'])\n\n if not rr_changes:\n return await ctx.reply('An error has occurred.')\n \n match_history = api.get_match_history(profile_data['region'], profile_data['name'], profile_data['tag'], profile_data['puuid'], 'competitive')\n\n comp_embed = Embed(title='Competitive History for: **{}#{}**'.format(name_tag[0], name_tag[1]), color=0x42f5b0)\n comp_embed.set_author(name='{}#{}'.format(profile_data['name'], profile_data['tag']), icon_url=profile_card['small'])\n\n i = 0\n for match in match_history:\n if len(rr_changes) - 1 < i:\n break\n\n add_game(match, comp_embed, rr_changes[i])\n i += 1\n \n \n\n mmr = api.get_mmr(profile_data['region'], name_tag[0], name_tag[1])\n\n if not mmr:\n return await ctx.reply('An error has occurred.')\n\n mmr_data = mmr['data']\n seasons = mmr_data['by_season']\n\n total_stats_embed = Embed(title='', color=0x42f5b0)\n total_data = calculate_total_mmr_stats(seasons)\n\n total_stats_embed.add_field(name='Ranked Total Wins', value='```diff\\n+ {}```'.format(total_data['wins']), inline=True)\n total_stats_embed.add_field(name='Ranked Total Losses', value='```diff\\n- {}```'.format(total_data['losses']), inline=True)\n total_stats_embed.add_field(name='Ranked Winrate', value='```fix\\n{:.2f}%```'.format((total_data['wins'] / total_data['games']) * 100), inline=True)\n \n await ctx.send(embed=comp_embed)\n await ctx.send(embed=total_stats_embed)\n\n@commands.cooldown(1, 20, commands.BucketType.user)\n@bot.command(name='profile', aliases=['user', 'player'])\nasync def profile(ctx, *args):\n profile_text = ' '.join(args)\n await ctx.reply('Fetching Profile `{}` ...'.format(profile_text))\n\n if not search(valorant_name_regex, profile_text):\n return await ctx.reply('The valorant profile must be in the format `name#tag`')\n\n name_tag = profile_text.split('#')\n profile = api.get_profile(name_tag[0], name_tag[1])\n if not profile:\n print(profile)\n return await ctx.reply('An error has occurred.')\n \n profile_data = profile['data']\n profile_card = profile_data['card']\n\n profile_embed = Embed(title='Stats for: **{}#{}**'.format(profile_data['name'], profile_data['tag']), color=0xF24D4E)\n \n profile_embed.set_thumbnail(url=profile_card['small'])\n profile_embed.add_field(name='Level', value='**```fix\\n{}```**'.format(profile_data['account_level']), inline=True)\n profile_embed.add_field(name='Region', value='```\\n{}```'.format(profile_data['region'].upper()), inline=True)\n profile_embed.set_author(name='{}#{}'.format(profile_data['name'], profile_data['tag']), icon_url=profile_card['small'])\n profile_embed.set_footer(text='Last updated {}'.format(profile_data['last_update']))\n\n mmr = api.get_mmr(profile_data['region'], name_tag[0], name_tag[1])\n\n if not mmr:\n return await ctx.reply('An error has occurred.')\n\n mmr_data = mmr['data']\n current_data = mmr_data['current_data']\n current_rating = current_data['ranking_in_tier']\n current_rank = current_data['currenttierpatched']\n last_game_rating_change = current_data['mmr_change_to_last_game']\n seasons = mmr_data['by_season']\n\n add_empty_field(profile_embed)\n profile_embed.add_field(name='Current Rank', value='**```yml\\n{}```**'.format(current_rank), inline=True)\n profile_embed.add_field(name='Current RR', value='```yml\\n{}```'.format(current_rating), inline=True)\n profile_embed.add_field(name='Latest Game', value='```diff\\n{}{}```'.format(positive_or_negative(last_game_rating_change), last_game_rating_change), inline=True) \n\n total_data = calculate_total_mmr_stats(seasons)\n\n profile_embed.add_field(name='Ranked Total Wins', value='```diff\\n+ {}```'.format(total_data['wins']), inline=True)\n profile_embed.add_field(name='Ranked Total Losses', value='```diff\\n- {}```'.format(total_data['losses']), inline=True)\n profile_embed.add_field(name='Ranked Winrate', value='```fix\\n{:.2f}%```'.format((total_data['wins'] / total_data['games']) * 100), inline=True)\n\n i = 0\n for key in seasons:\n i += 1\n add_act(key.upper(), seasons[key], profile_embed)\n if i == 2:\n break\n\n await ctx.send(embed=profile_embed)\n\n\n@bot.event\nasync def on_command_error(ctx, error):\n if isinstance(error, commands.CommandOnCooldown):\n embed = Embed(title='You cannot use this command yet! ⌚',description='Try again in **{:.2f} seconds**'.format(error.retry_after), color=0x001b3b)\n await ctx.send(embed=embed)\n else:\n print(error)\n\n@bot.event\nasync def on_ready():\n print('Ready!')\n await bot.change_presence(activity=Activity(type=ActivityType.listening, name='{}help'.format(config['prefix'])))\n\nbot.run(config['token'])","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"162910738","text":"from __future__ import print_function\nimport torch\nimport torch.nn as nn \nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport numpy as np\n\nNCLASSES = 10\n\ndef NORM(x):\n return 1.0*x/NCLASSES - 0.5\ndef UNORM(x):\n return (x + 0.5)*NCLASSES\n\ndef gen_data(sequence_length=50, batch_size=1):\n data = np.concatenate((np.random.choice(2, (batch_size, sequence_length, 1), True, (0.9, 0.1)), \n NORM(np.random.choice(NCLASSES, (batch_size, sequence_length, 1)))), axis=2)\n data[:, 0, 0] = 1\n gt = np.zeros((batch_size, sequence_length), dtype=data.dtype)\n for b in range(batch_size):\n for t in range(sequence_length):\n gt[b, t] = data[b, t, 1] if data[b, t, 0] else gt[b, t-1]\n return data, gt\n\n\nclass SimpleLatch(nn.Module):\n def __init__(self):\n super(SimpleLatch, self).__init__()\n self.forget = nn.Linear(2, 1)\n self.input = nn.Linear(2, 1)\n self.block = nn.Linear(2, 1)\n self.output = nn.Linear(2, 1)\n self.sig = nn.Sigmoid()\n self.tanh = nn.Tanh()\n\n def forward(self, input):\n outputs = []\n c_t = Variable(torch.zeros(input.size(0), 1).double(), requires_grad=True)\n\n for input_t in input.chunk(input.size(1), dim=1):\n input_t = input_t.squeeze(1)\n fg = self.sig(self.forget(input_t))\n ig = self.sig(self.input(input_t))\n bg = self.tanh(self.block(input_t))\n og = self.sig(self.output(input_t))\n c_t = c_t*fg\n bg = bg*ig\n c_t = bg + c_t\n oo = og*self.tanh(c_t)\n outputs += [oo.unsqueeze(1)]\n outputs = torch.stack(outputs, 1).squeeze(2)\n return outputs\n\n\ndef train_em_up(latch):\n criterion = nn.L1Loss()\n optimizer = optim.Adam(latch.parameters(), lr=1e-2)\n for i in range(1000):\n data, gt = gen_data(batch_size=256, sequence_length=50)\n data = Variable(torch.from_numpy(data).double(), requires_grad=True)\n gt = Variable(torch.from_numpy(gt).double(), requires_grad=False)\n out = latch(data)\n loss = criterion(out, gt)\n print('ITER[%d] loss: %f' % (i, loss.data.numpy()[0]))\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n \ndef test_em(latch):\n data, gt = gen_data()\n data = Variable(torch.from_numpy(data).double(), requires_grad=False)\n gt = Variable(torch.from_numpy(gt).double(), requires_grad=False)\n out = latch(data)\n for t in range(data.size(1)):\n print(\"[%3d] %d %d -> %5.2f (%d)\" % (t, int(data.data.numpy()[0, t, 0]), int(UNORM(data.data.numpy()[0, t, 1])), UNORM(out.data.numpy()[0, t]), int(UNORM(gt.data.numpy()[0, t]))))\n\n\nif __name__ == '__main__':\n # set ramdom seed to 0\n np.random.seed(1)\n torch.manual_seed(0)\n # build the model\n latch = SimpleLatch()\n latch.double()\n latch.train()\n train_em_up(latch)\n latch.eval()\n test_em(latch)\n \n","sub_path":"archive-2018/notes/DeepLearningInPracticeSummer2017/code/LSTMs/lstm_ex.py","file_name":"lstm_ex.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"577537267","text":"# -*- coding: utf-8 -*-\nfrom __future__ import annotations\nfrom typing import List, Tuple\n\nfrom fcatools.dyadic.dyadic_association_rule import DyadicAssociationRule\n\nclass TriadicAssociationRule:\n def __init__(self, left_side, right_side, condition, support, confidence):\n self.left_side = left_side\n self.right_side = right_side\n self.condition = condition\n self.support = support\n self.confidence = confidence\n\n def __str__(self):\n return f'({list(self.left_side)} -> {list(self.right_side)}) {list(self.condition)} (sup: {self.support}, conf: {self.confidence})'\n\n def __repr__(self):\n return f'TriadicAssociationRule({self.left_side}, {self.right_side}, {self.condition}, {self.support}, {self.confidence})'\n\n @staticmethod\n def calculate_bacars_from_dyadic_rules(\n dyadic_rules: List[DyadicAssociationRule],\n separator: str\n ) -> Tuple[List[TriadicAssociationRule], List[TriadicAssociationRule]]:\n implication_bacars = []\n association_bacars = []\n\n for dyadic_rule in dyadic_rules.copy():\n attrs = frozenset({})\n conditions = frozenset({})\n dyadic_rule.generator -= frozenset({'ø'})\n for i in dyadic_rule.generator:\n attr_cond = i.split(separator)\n attrs |= {attr_cond[0]}\n conditions |= {attr_cond[1]}\n\n if (len(attrs) * len(conditions)) == len(dyadic_rule.generator):\n bacars = TriadicAssociationRule.__bacars_algorithm(\n attrs,\n conditions,\n dyadic_rule.potential_cons,\n dyadic_rule.support,\n dyadic_rule.confidence,\n separator\n )\n\n if len(bacars) > 0 and bacars[0].confidence == 1.0:\n implication_bacars += bacars\n else:\n association_bacars += bacars\n\n return implication_bacars, association_bacars\n\n @staticmethod\n def calculate_bcaars_from_dyadic_rules(\n dyadic_rules: List[DyadicAssociationRule],\n separator: str\n ) -> Tuple[List[TriadicAssociationRule], List[TriadicAssociationRule]]:\n implication_bcaars = []\n association_bcaars = []\n\n for dyadic_rule in dyadic_rules.copy():\n attrs = frozenset({})\n conditions = frozenset({})\n dyadic_rule.generator -= frozenset({'ø'})\n for i in dyadic_rule.generator:\n attr_cond = i.split(separator)\n attrs |= {attr_cond[0]}\n conditions |= {attr_cond[1]}\n\n if (len(attrs) * len(conditions)) == len(dyadic_rule.generator):\n bcaars = TriadicAssociationRule.__bcaars_algorithm(\n attrs,\n conditions,\n dyadic_rule.potential_cons,\n dyadic_rule.support,\n dyadic_rule.confidence,\n separator\n )\n\n if len(bcaars) > 0 and bcaars[0].confidence == 1.0:\n implication_bcaars += bcaars\n else:\n association_bcaars += bcaars\n\n return implication_bcaars, association_bcaars\n\n @staticmethod\n def __bacars_algorithm(al, ml, rhs, support, confidence, separator) -> List[TriadicAssociationRule]:\n mr = frozenset({})\n c = []\n for e in rhs:\n attrs = {e.split(separator)[0]}\n attrs = attrs - (attrs - al)\n if len(attrs) > 0:\n c.append(e)\n\n if len(c) > 0:\n for e in c:\n modus = e.split(separator)[1]\n count = 0\n for i in c:\n if modus == i.split(separator)[1]:\n count += 1\n\n if count == len(al):\n mr |= {modus}\n\n if len(mr) != 0:\n return [TriadicAssociationRule(ml, mr, al, support, confidence)]\n else:\n return []\n\n @staticmethod\n def __bcaars_algorithm(al, ml, rhs, support, confidence, separator) -> List[TriadicAssociationRule]:\n ar = frozenset({})\n c = []\n for e in rhs:\n conditions = {e.split(separator)[1]}\n conditions = conditions - (conditions - ml)\n if len(conditions) > 0:\n c.append(e)\n\n if len(c) > 0:\n for e in c:\n attrs = e.split(separator)[0]\n count = 0\n for i in c:\n if attrs == i.split(separator)[0]:\n count += 1\n\n if count == len(ml):\n ar |= {attrs}\n\n if len(ar) != 0:\n return [TriadicAssociationRule(al, ar, ml, support, confidence)]\n else:\n return []\n","sub_path":"src/fcatools/triadic/triadic_association_rule.py","file_name":"triadic_association_rule.py","file_ext":"py","file_size_in_byte":4893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"210077443","text":"\"\"\" \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nTest a learner. (c) 2015 Tucker Balch \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nCopyright 2018, Georgia Institute of Technology (Georgia Tech) \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nAtlanta, Georgia 30332 \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nAll Rights Reserved \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nTemplate code for CS 4646/7646 \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nGeorgia Tech asserts copyright ownership of this template and all derivative \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nworks, including solutions to the projects assigned in this course. Students \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nand other users of this template code are advised not to share it with others \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nor to make it available on publicly viewable websites including repositories \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nsuch as github and gitlab. This copyright statement should not be removed \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nor edited. \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nWe do grant permission to share solutions privately with non-students such \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nas potential employers. However, sharing with other current or future \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nstudents of CS 7646 is prohibited and subject to being investigated as a \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nGT honor code violation. \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n-----do not edit anything above this line--- \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n\"\"\" \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n\nimport numpy as np \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nimport math\nimport sys\nimport pandas as pd\nimport matplotlib\nmatplotlib.use(\"TKAgg\")\nimport matplotlib.pyplot as plt\nimport LinRegLearner as lrl\nimport DTLearner as dt\nimport RTLearner as rt\nimport BagLearner as bg\nimport time\n\n\ndef gtid():\n return 902831571 # replace with your GT ID number\n\n\ndef experiment1_figure1():\n inf = open(\"Data/Istanbul.csv\")\n data_exp1 = np.genfromtxt(inf, delimiter=\",\")\n data_exp1 = data_exp1[1:, 1:]\n\n # compute how much of the data is training and testing\n train_rows_exp1 = int(0.6 * data_exp1.shape[0])\n test_rows_exp1 = data_exp1.shape[0] - train_rows_exp1\n\n # separate out training and testing data\n trainX_exp1 = data_exp1[:train_rows_exp1, 0:-1]\n trainY_exp1 = data_exp1[:train_rows_exp1, -1]\n testX_exp1 = data_exp1[train_rows_exp1:, 0:-1]\n testY_exp1 = data_exp1[train_rows_exp1:, -1]\n\n # create list of rmse\n in_sample_rmse = []\n out_sample_rmse = []\n leaf_index = np.arange(1, 51)\n\n # Iterate through various leaf sizes and record the rmse values\n for leaf_size in leaf_index:\n learner_exp1 = dt.DTLearner(leaf_size=leaf_size)\n learner_exp1.addEvidence(trainX_exp1, trainY_exp1)\n predY_exp1 = learner_exp1.query(trainX_exp1) # get the predictions\n insample_rmse = math.sqrt(((trainY_exp1 - predY_exp1) ** 2).sum() / trainY_exp1.shape[0])\n in_sample_rmse.append(insample_rmse)\n predY_exp1 = learner_exp1.query(testX_exp1)\n outsample_rmse = math.sqrt(((testY_exp1 - predY_exp1) ** 2).sum() / testY_exp1.shape[0])\n out_sample_rmse.append(outsample_rmse)\n\n # Generate the plots\n fig, axis = plt.subplots(figsize=(12, 8))\n df = pd.DataFrame({\"In-Sample RMSE\": in_sample_rmse, \"Out-Sample RMSE\": out_sample_rmse}, index=leaf_index)\n df.plot(ax=axis, title=\"RMSE vs Leaf Size for DTLearner\")\n axis.set_xlabel(\"Leaf Size\")\n axis.set_ylabel(\"RMSE\")\n plt.xticks(np.arange(0, 51, 5))\n plt.axvline(x=10, color='gray', linestyle='--')\n plt.axvline(x=19, color='gray', linestyle='--')\n plt.legend([\"In-Sample RMSE\", \"Out-Sample RMSE\", \"Leaf-Size=10\", \"Leaf-Size=19\"], loc='lower right')\n plt.tight_layout()\n plt.savefig(\"exp1-fig1.png\")\n\n\ndef experiment2_figure1():\n inf = open(\"Data/Istanbul.csv\")\n data_exp2 = np.genfromtxt(inf, delimiter=\",\")\n data_exp2 = data_exp2[1:, 1:]\n\n # compute how much of the data is training and testing\n train_rows_exp2 = int(0.6 * data_exp2.shape[0])\n test_rows_exp1 = data_exp2.shape[0] - train_rows_exp2\n\n # separate out training and testing data\n trainX_exp2 = data_exp2[:train_rows_exp2, 0:-1]\n trainY_exp2 = data_exp2[:train_rows_exp2, -1]\n testX_exp2 = data_exp2[train_rows_exp2:, 0:-1]\n testY_exp2 = data_exp2[train_rows_exp2:, -1]\n\n # create list of rmse\n in_sample_rmse = []\n out_sample_rmse = []\n leaf_index = np.arange(1, 51)\n\n # Iterate through various leaf sizes and record the rmse values\n for leaf_size in leaf_index:\n learner_exp2 = bg.BagLearner(learner=dt.DTLearner, kwargs={\"leaf_size\":leaf_size}, bags=20)\n learner_exp2.addEvidence(trainX_exp2, trainY_exp2)\n predY_exp2 = learner_exp2.query(trainX_exp2) # get the predictions\n insample_rmse = math.sqrt(((trainY_exp2 - predY_exp2) ** 2).sum() / trainY_exp2.shape[0])\n in_sample_rmse.append(insample_rmse)\n predY_exp2 = learner_exp2.query(testX_exp2)\n outsample_rmse = math.sqrt(((testY_exp2 - predY_exp2) ** 2).sum() / testY_exp2.shape[0])\n out_sample_rmse.append(outsample_rmse)\n\n # Generate the plots\n fig, axis = plt.subplots(figsize=(12, 8))\n df = pd.DataFrame({\"In-Sample RMSE\": in_sample_rmse, \"Out-Sample RMSE\": out_sample_rmse}, index=leaf_index)\n df.plot(ax=axis, title=\"RMSE vs Leaf Size for BagLearner with 20 Bags using DTLearner\")\n axis.set_xlabel(\"Leaf Size\")\n axis.set_ylabel(\"RMSE\")\n plt.xticks(np.arange(0, 51, 5))\n plt.yticks(np.arange(0.000, 0.009, 0.0005))\n # plt.axvline(x=10, color='gray', linestyle='--')\n # plt.axvline(x=19, color='gray', linestyle='--')\n plt.legend([\"In-Sample RMSE\", \"Out-Sample RMSE\"], loc='lower right')\n plt.tight_layout()\n plt.savefig(\"exp2-fig1.png\")\n\n\ndef experiment2_figure2():\n inf = open(\"Data/Istanbul.csv\")\n data_exp2 = np.genfromtxt(inf, delimiter=\",\")\n data_exp2 = data_exp2[1:, 1:]\n\n # compute how much of the data is training and testing\n train_rows_exp2 = int(0.6 * data_exp2.shape[0])\n test_rows_exp1 = data_exp2.shape[0] - train_rows_exp2\n\n # separate out training and testing data\n trainX_exp2 = data_exp2[:train_rows_exp2, 0:-1]\n trainY_exp2 = data_exp2[:train_rows_exp2, -1]\n testX_exp2 = data_exp2[train_rows_exp2:, 0:-1]\n testY_exp2 = data_exp2[train_rows_exp2:, -1]\n\n # create list of rmse\n in_sample_rmse = []\n out_sample_rmse = []\n bag_index = np.arange(1, 21)\n\n # Iterate through various bag sizes and record the rmse values\n for bag_size in bag_index:\n learner_exp2 = bg.BagLearner(learner=dt.DTLearner, kwargs={\"leaf_size\":1}, bags=bag_size)\n learner_exp2.addEvidence(trainX_exp2, trainY_exp2)\n predY_exp2 = learner_exp2.query(trainX_exp2) # get the predictions\n insample_rmse = math.sqrt(((trainY_exp2 - predY_exp2) ** 2).sum() / trainY_exp2.shape[0])\n in_sample_rmse.append(insample_rmse)\n predY_exp2 = learner_exp2.query(testX_exp2)\n outsample_rmse = math.sqrt(((testY_exp2 - predY_exp2) ** 2).sum() / testY_exp2.shape[0])\n out_sample_rmse.append(outsample_rmse)\n\n # Generate the plots\n fig, axis = plt.subplots(figsize=(12, 8))\n df = pd.DataFrame({\"In-Sample RMSE\": in_sample_rmse, \"Out-Sample RMSE\": out_sample_rmse}, index=bag_index)\n df.plot(ax=axis, title=\"RMSE vs Bag Size at Constant Leaf-Size of 1 for BagLearner using DTLearner\")\n axis.set_xlabel(\"Bag Size\")\n axis.set_ylabel(\"RMSE\")\n plt.xticks(np.arange(1, 21, 1))\n plt.yticks(np.arange(0.000, 0.009, 0.0005))\n # plt.axvline(x=10, color='gray', linestyle='--')\n # plt.axvline(x=19, color='gray', linestyle='--')\n plt.legend([\"In-Sample RMSE\", \"Out-Sample RMSE\"], loc='upper right')\n plt.tight_layout()\n plt.savefig(\"exp2-fig2.png\")\n\n\ndef experiment3_figure1():\n inf = open(\"Data/Istanbul.csv\")\n data_exp3 = np.genfromtxt(inf, delimiter=\",\")\n data_exp3 = data_exp3[1:, 1:]\n\n # compute how much of the data is training and testing\n train_rows_exp3 = int(0.6 * data_exp3.shape[0])\n test_rows_exp3 = data_exp3.shape[0] - train_rows_exp3\n\n # separate out training and testing data\n trainX_exp3 = data_exp3[:train_rows_exp3, 0:-1]\n trainY_exp3 = data_exp3[:train_rows_exp3, -1]\n testX_exp3 = data_exp3[train_rows_exp3:, 0:-1]\n testY_exp3 = data_exp3[train_rows_exp3:, -1]\n trainY_exp3_mean = np.mean(trainY_exp3)\n testY_exp3_mean = np.mean(testY_exp3)\n\n # create list of r2 scores - 1 - (ss_res/ss_tot)\n # Formula for R2 Score - Credits : https://en.wikipedia.org/wiki/Coefficient_of_determination\n in_sample_r2score_dt = []\n out_sample_r2score_dt = []\n in_sample_r2score_rt = []\n out_sample_r2score_rt = []\n leaf_index = np.arange(1, 21)\n\n # Iterate through various bag sizes and record the rmse values\n for leaf_size in leaf_index:\n learner_exp3_dt = dt.DTLearner(leaf_size=leaf_size)\n learner_exp3_rt = rt.RTLearner(leaf_size=leaf_size)\n learner_exp3_dt.addEvidence(trainX_exp3, trainY_exp3)\n learner_exp3_rt.addEvidence(trainX_exp3, trainY_exp3)\n\n # In - Sample Calculations - DTLearner\n predY_exp3_dt = learner_exp3_dt.query(trainX_exp3) # get the predictions\n ss_res_dt = ((trainY_exp3 - predY_exp3_dt) ** 2).sum()\n ss_tot_dt = ((trainY_exp3 - trainY_exp3_mean) ** 2).sum()\n r2score_dt = 1 - (ss_res_dt/ss_tot_dt)\n in_sample_r2score_dt.append(r2score_dt)\n\n # In - Sample Calculation - RTLearner\n predY_exp3_rt = learner_exp3_rt.query(trainX_exp3) # get the predictions\n ss_res_rt = ((trainY_exp3 - predY_exp3_rt) ** 2).sum()\n ss_tot_rt = ((trainY_exp3 - trainY_exp3_mean) ** 2).sum()\n r2score_rt = 1 - (ss_res_rt / ss_tot_rt)\n in_sample_r2score_rt.append(r2score_rt)\n\n # Out - Sample Calculations - DTLearner\n predY_exp3_dt = learner_exp3_dt.query(testX_exp3) # get the predictions\n ss_res_dt = ((testY_exp3 - predY_exp3_dt) ** 2).sum()\n ss_tot_dt = ((testY_exp3 - testY_exp3_mean) ** 2).sum()\n r2score_dt = 1 - (ss_res_dt / ss_tot_dt)\n out_sample_r2score_dt.append(r2score_dt)\n\n # Out - Sample Calculations - RTLearner\n predY_exp3_rt = learner_exp3_rt.query(testX_exp3) # get the predictions\n ss_res_rt = ((testY_exp3 - predY_exp3_rt) ** 2).sum()\n ss_tot_rt = ((testY_exp3 - testY_exp3_mean) ** 2).sum()\n r2score_rt = 1 - (ss_res_rt / ss_tot_rt)\n out_sample_r2score_rt.append(r2score_rt)\n\n # Generate the plots\n fig, axis = plt.subplots(figsize=(12, 8))\n df = pd.DataFrame({\"In-Sample R2Score - DTLearner\": in_sample_r2score_dt,\n \"Out-Sample R2Score - DTLearner\": out_sample_r2score_dt,\n \"In-Sample R2Score - RTLearner\": in_sample_r2score_rt,\n \"Out-Sample R2Score - RTLearner\": out_sample_r2score_rt}, index=leaf_index)\n\n df.plot(ax=axis, title=\"R-Square(R2 Score) vs LeafSize Comparison for RTLearner & DTLearner\")\n axis.set_xlabel(\"Leaf Size\")\n axis.set_ylabel(\"R2 Score\")\n plt.xticks(np.arange(1, 21, 1))\n plt.yticks(np.arange(0.000, 1.100, 0.1))\n plt.legend([\"In-Sample R2Score - DTLearner\", \"Out-Sample R2Score - DTLearner\",\n \"In-Sample R2Score - RTLearner\", \"Out-Sample R2Score - RTLearner\"], loc='upper right')\n plt.tight_layout()\n plt.savefig(\"exp3-fig1.png\")\n\n\ndef experiment3_figure2():\n inf = open(\"Data/Istanbul.csv\")\n data_exp3 = np.genfromtxt(inf, delimiter=\",\")\n data_exp3 = data_exp3[1:, 1:]\n\n # create list of time values\n time_taken_dt = []\n time_taken_rt = []\n size_index = np.arange(1, data_exp3.shape[0], 20) # Create an index of how much data to split\n\n # Iterate through various leaf sizes and record the rmse values\n for size in size_index:\n learner_exp3_dt = dt.DTLearner(leaf_size=1)\n learner_exp3_rt = rt.RTLearner(leaf_size=1)\n trainX_exp3 = data_exp3[:size, 0:-1]\n trainY_exp3 = data_exp3[:size, -1]\n\n # Calculate time taken to learn - DTLearner\n start_time = time.time()\n learner_exp3_dt.addEvidence(trainX_exp3, trainY_exp3)\n end_time = time.time()\n time_taken = end_time - start_time\n time_taken_dt.append(time_taken)\n\n # Calculate time taken to learn - RTLearner\n start_time = time.time()\n learner_exp3_rt.addEvidence(trainX_exp3, trainY_exp3)\n end_time = time.time()\n time_taken = end_time - start_time\n time_taken_rt.append(time_taken)\n\n\n # Generate the plots\n fig, axis = plt.subplots(figsize=(12, 8))\n df = pd.DataFrame({\"Time-Taken DTLearner\": time_taken_dt, \"Time-Taken RTLearner\": time_taken_rt}, index=size_index)\n df.plot(ax=axis, title=\"Comparison of time taken to train between DTLearner and RTLearner\")\n axis.set_xlabel(\"Size of Training Set\")\n axis.set_ylabel(\"Time-Taken(secs)\")\n plt.yticks(np.arange(0.00, 0.40, 0.02))\n plt.xticks(np.arange(0, data_exp3.shape[0], 50))\n plt.legend([\"Time-Taken DTLearner\", \"Time-Taken RTLearner\"], loc='upper left')\n plt.tight_layout()\n plt.savefig(\"exp3-fig2.png\")\n\n\nif __name__ == \"__main__\":\n\n np.random.seed(gtid()) # do this only once\n\n # Credits - Piazza Post # 578\n if len(sys.argv) != 2:\n print(\"Usage: python testlearner.py \")\n sys.exit(1)\n inf = open(sys.argv[1])\n if sys.argv[1] == \"Data/Istanbul.csv\":\n data = np.genfromtxt(inf, delimiter=\",\")\n data = data[1:, 1:]\n else:\n data = np.array([list(map(float, s.strip().split(','))) for s in inf.readlines()])\n\n # compute how much of the data is training and testing \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n train_rows = int(0.6* data.shape[0]) \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n test_rows = data.shape[0] - train_rows \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n\n # separate out training and testing data \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n trainX = data[:train_rows, 0:-1]\n trainY = data[:train_rows, -1]\n testX = data[train_rows:, 0:-1]\n testY = data[train_rows:, -1]\n\n # print(f\"{testX.shape}\")\n # print(f\"{testY.shape}\")\n\n # create a learner and train it \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n # learner = lrl.LinRegLearner(verbose = True) # create a LinRegLearner\n # learner = dt.DTLearner(leaf_size=1, verbose=False)\n # learner = rt.RTLearner(leaf_size=1, verbose=False)\n learner = bg.BagLearner(learner=dt.DTLearner, kwargs={\"leaf_size\":1}, bags=1)\n learner.addEvidence(trainX, trainY) # train it\n # print(learner.author())\n\n # evaluate in sample \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n predY = learner.query(trainX) # get the predictions \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n rmse = math.sqrt(((trainY - predY) ** 2).sum()/trainY.shape[0]) \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n # print()\n # print(\"In sample results\")\n # print(f\"RMSE: {rmse}\")\n c = np.corrcoef(predY, y=trainY) \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n # print(f\"corr: {c[0,1]}\")\n\n # evaluate out of sample \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n predY = learner.query(testX) # get the predictions \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n rmse = math.sqrt(((testY - predY) ** 2).sum()/testY.shape[0]) \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n # print()\n # print(\"Out of sample results\")\n # print(f\"RMSE: {rmse}\")\n c = np.corrcoef(predY, y=testY) \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n # print(f\"corr: {c[0,1]}\")\n\n # Code for generating plots used in report\n experiment1_figure1()\n experiment2_figure1()\n experiment2_figure2()\n experiment3_figure1()\n experiment3_figure2()\n\n","sub_path":"ML4T_2019Fall/assess_learners/testlearner.py","file_name":"testlearner.py","file_ext":"py","file_size_in_byte":16298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"166720037","text":"import sys \nsys.setrecursionlimit(10**6)\ndef solution(n):\n def dfs(n):\n global cnt \n if n == 0:\n return \n if n % 2 == 0:\n dfs(n//2)\n else:\n cnt+=1\n dfs(n-1)\n\n\n global cnt \n cnt = 0\n if n == 1 or n== 2:\n return 1\n dfs(n)\n return cnt\n\nN = 5000\n\nprint(solution(N))","sub_path":"프로그래머스/lv2/12980. 점프와 순간 이동/점프와 순간 이동.py","file_name":"점프와 순간 이동.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"123298081","text":"import pandas as pd\nfrom xgboost import XGBClassifier\n\nfrom sklearn.model_selection import train_test_split, KFold\nfrom sklearn.metrics import accuracy_score\nfrom xgboost import plot_importance\nfrom matplotlib import pyplot\n\ncolumns = [\"Height(in)\", \"Weight(lbs)\", \"40Yard\", \"Bench Press\", \n \"Vert Leap(in)\", \"Broad Jump(in)\", \"Shuttle\", \"3Cone\",\n \"Rushes\", \"Yards\", \"ypc\", \"Hlt Yds\", \"Hlt.Yds.carry\",\n \"hlt.yds.opp\", \"BlockSuccessRate\", \"HltOpps\",\n \"BMI\", \"ArmLength\", \"HandSize\", \"breakout\", \n \"BreakoutAge\", \"CollegeDominator\", \"CollegeTargetShare\"]\n\n\nkFold = KFold(n_splits=10, random_state=7)\n\ndf = pd.read_csv(\"rbTrain17.csv\", header=0)\n\nx = df[columns].values\ny = df[\"rb1PPR\"].values\n\nfor train_index, test_index in kFold.split(x):\n\tmodel = XGBClassifier()\n\tx_train, x_test = x[train_index], x[test_index]\n\ty_train, y_test = y[train_index], y[test_index]\n\n\tmodel.fit(x_train, y_train)\n\n\ty_pred = model.predict(x_test)\n\n\taccuracy = accuracy_score(y_test, y_pred)\n\n\tprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n\n\tplot_importance(model)\n\tpyplot.show()","sub_path":"program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"535476267","text":"import cv2\nimport numpy as np \nimport sqlite3\nimport os\nfrom PIL import Image, ImageDraw, ImageFont\n\nconn = sqlite3.connect('database.db')\nc = conn.cursor()\n\nfname = \"recognizer/trainingData.yml\"\nif not os.path.isfile(fname):\n print(\"Please train the data first\")\n exit(0)\n\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\ncap = cv2.VideoCapture(0)\nrecognizer = cv2.face.LBPHFaceRecognizer_create()\n#recognizer = cv2.face.FisherFaceRecognizer_create()\nrecognizer.read(fname)\n\nwhile True:\n ret, img = cap.read()\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n cv2.equalizeHist(gray,gray)\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n for (x,y,w,h) in faces:\n \n cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)\n #print(\"w:%d,h:%d\" % (w,h))\n \n #if w < 150 or h < 150:\n # img_ex = cv2.resize(img, (2*cols, 2*rows), interpolation=cv2.INTER_CUBIC)\n \n face = gray[y:y+h,x:x+w]\n if w < 150 or h < 150:\n face = cv2.resize(face, (300, 300), interpolation=cv2.INTER_CUBIC)\n print(\"w:%d,h:%d\" % (w,h))\n \n ids,confidence = recognizer.predict(face)\n c.execute(\"select name from users where id = (?);\", (ids,))\n result = c.fetchall()\n name = result[0][0]\n if confidence < 50:\n #cv2.putText(img, name, (x+2,y+h-5), cv2.FONT_HERSHEY_SIMPLEX, 1, (150,255,0),2)\n print(\"w:%d,h:%d\" % (w,h))\n result = \"confidence:%.2f, %s\" % (confidence, name)\n cv2_im = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n pil_im = Image.fromarray(cv2_im)\n draw = ImageDraw.Draw(pil_im)\n font = ImageFont.truetype(\"simhei.ttf\", 20, encoding=\"utf-8\")\n draw.text((x+2,y+h-5), result, (0, 0, 255), font=font)\n img = cv2.cvtColor(np.array(pil_im), cv2.COLOR_RGB2BGR)\n #else:\n #cv2.putText(img, 'No Match', (x+2,y+h-5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255),2)\n #print(\"confidence:%.2f\" % (confidence))\n cv2.imshow('Face Recognizer',img)\n k = cv2.waitKey(30) & 0xff\n if k == 27:\n break\n\ncap.release()\ncv2.destroyAllWindows()","sub_path":"detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"5207798","text":"import os\nfrom collections import OrderedDict\nfrom textwrap import dedent\nimport warnings\n\nimport numpy\nimport pandas\nfrom shapely.geometry import Point, Polygon\nimport geopandas\n\nfrom pygridtools import misc\nfrom pygridtools import validate\n\n\ndef _warn_filterfxn(filterfxn):\n msg = '`filterfxn` no longer supported. Use the `query` method of the resulting dataframe.'\n if filterfxn:\n warnings.warn(msg)\n\n\ndef read_boundary(gisfile, betacol='beta', reachcol=None, sortcol=None,\n upperleftcol=None, filterfxn=None):\n \"\"\" Loads boundary points from a GIS File.\n\n Parameters\n ----------\n gisfile : string\n Path to the GIS file containaing boundary points.\n Expected schema of the file...\n\n - order: numeric sort order of the points\n - beta: the 'beta' parameter used in grid generation to define\n turning points\n\n betacol : string (default='beta')\n Column in the attribute table specifying the beta parameter's\n value at each point.\n sortcol : optional string or None (default)\n Column in the attribute table specifying the sort order of the\n points.\n reachcol : optional string or None (default)\n Column in the attribute table specifying the names of the\n reaches of the river/esturary system.\n upperleftcol : optional string or None (default)\n Column in the attribute table toggling if the a point should be\n consider the upper-left corner of the system. Only one row of\n this column should evaluare to True.\n filterfxn : function or lambda expression or None (default)\n Removed. Use the `query` method of the result.\n\n Returns\n -------\n gdf : geopandas.GeoDataFrame\n A GeoDataFrame of the boundary points with the following columns:\n\n - x (easting)\n - y (northing)\n - beta (turning parameter)\n - order (for sorting)\n - reach\n - upperleft\n\n \"\"\"\n\n def _get_col_val(df, col, default=None):\n if col is not None:\n return df[col]\n else:\n return default\n\n _warn_filterfxn(filterfxn)\n gdf = (\n geopandas.read_file(gisfile)\n .assign(x=lambda df: df['geometry'].x)\n .assign(y=lambda df: df['geometry'].y)\n .assign(beta=lambda df: _get_col_val(df, betacol, 0))\n .assign(order=lambda df: _get_col_val(df, sortcol, df.index))\n .assign(reach=lambda df: _get_col_val(df, reachcol, 'main'))\n .assign(upperleft=lambda df: _get_col_val(df, upperleftcol, False))\n .fillna(0)\n .sort_values(by=['order'])\n )\n\n return gdf.loc[:, ['x', 'y', 'beta', 'upperleft', 'reach', 'order', 'geometry']]\n\n\ndef read_polygons(gisfile, filterfxn=None, squeeze=True, as_gdf=False):\n \"\"\" Load polygons (e.g., water bodies, islands) from a GIS file.\n\n Parameters\n ----------\n gisfile : string\n Path to the gisfile containaing boundary points.\n filterfxn : function or lambda expression or None (default)\n Removed. Use the `as_gdf` and the `query` method of the resulting\n GeoDataFrame.\n squeeze : optional bool (default = True)\n Set to True to return an array if only 1 record is present.\n Otherwise, a list of arrays will be returned.\n as_gdf : optional bool (default = False)\n Set to True to return a GeoDataFrame instead of arrays.\n\n Returns\n -------\n boundary : array or list of arrays, or GeoDataFrame\n\n Notes\n -----\n Multipart geometries are not supported. If a multipart geometry is\n present in a record, only the first part will be loaded.\n\n Z-coordinates are also not supported. Only x-y coordinates will be\n loaded.\n\n \"\"\"\n _warn_filterfxn(filterfxn)\n gdf = geopandas.read_file(gisfile)\n if as_gdf:\n return gdf\n else:\n data = [numpy.array(g.boundary.coords) for g in gdf['geometry']]\n if len(data) == 1 and squeeze:\n data = data[0]\n return data\n\n\ndef read_grid(gisfile, icol='ii', jcol='jj', othercols=None, expand=1,\n as_gdf=False):\n if othercols is None:\n othercols = []\n\n grid = (\n geopandas.read_file(gisfile)\n .rename(columns={icol: 'ii', jcol: 'jj'})\n .set_index(['ii', 'jj'])\n .sort_index()\n )\n if as_gdf:\n final_cols = othercols + ['geometry']\n return grid[final_cols]\n else:\n final_cols = ['easting', 'northing'] + othercols\n if (grid.geom_type != 'Point').any():\n msg = \"can only read points for now when not returning a geodataframe\"\n raise NotImplementedError(msg)\n\n return grid.assign(easting=grid['geometry'].x, northing=grid['geometry'].y)[final_cols]\n\n\ndef write_points(X, Y, crs, outputfile, river=None, reach=0, elev=None):\n \"\"\" Saves grid-related attributes of a pygridgen.Gridgen object to a\n GIS file with geomtype = 'Point'.\n\n Parameters\n ----------\n X, Y : numpy (masked) arrays, same dimensions\n Attributes of the gridgen object representing the x- and y-coords.\n crs : string\n A geopandas/proj/fiona-compatible string describing the coordinate\n reference system of the x/y values.\n outputfile : string\n Path to the point-geometry GIS file to which the data will be written.\n river : optional string (default = None)\n The river to be listed in the GIS files's attribute table.\n reach : optional int (default = 0)\n The reach of the river to be listed in the GIS file's attribute\n table.\n elev : optional array or None (defauly)\n The elevation of the grid cells. Array dimensions must be 1 less than\n X and Y.\n\n Returns\n -------\n geopandas.GeoDataFrame\n\n \"\"\"\n\n # check that X and Y are have the same shape, NaN cells\n X, Y = validate.equivalent_masks(X, Y)\n\n # check elev shape\n elev = validate.elev_or_mask(X, elev, 'elev', offset=0)\n\n # start writting or appending to the output\n row = 0\n geodata = []\n for ii in range(X.shape[1]):\n for jj in range(X.shape[0]):\n # check that nothing is masked (outside of the river)\n if not (X.mask[jj, ii]):\n row += 1\n\n # build the coords\n coords = (X[jj, ii], Y[jj, ii])\n\n # build the attributes\n record = OrderedDict(\n id=int(row), river=river, reach=reach,\n ii=int(ii + 2), jj=int(jj + 2), elev=float(elev[jj, ii]),\n ii_jj='{:02d}_{:02d}'.format(ii + 2, jj + 2),\n geometry=Point(coords)\n )\n\n geodata.append(record)\n\n gdf = geopandas.GeoDataFrame(geodata, crs=crs, geometry='geometry')\n gdf.to_file(outputfile)\n return gdf\n\n\ndef write_cells(X, Y, mask, crs, outputfile, river=None, reach=0,\n elev=None, triangles=False):\n \"\"\" Saves a GIS file of quadrilaterals representing grid cells.\n\n Parameters\n ----------\n X, Y : numpy (masked) arrays, same dimensions\n Attributes of the gridgen object representing the x- and y-coords.\n mask : numpy array or None\n Array describing which cells to mask (exclude) from the output.\n Shape should be N-1 by M-1, where N and M are the dimensions of\n `X` and `Y`.\n crs : string\n A geopandas/proj/fiona-compatible string describing the coordinate\n reference system of the x/y values.\n outputfile : string\n Path to the point GIS file to which the data will be written.\n river : optional string (default = None)\n The river to be listed in the GIS file's attribute table.\n reach : optional int (default = 0)\n The reach of the river to be listed in the GIS file's attribute\n table.\n elev : optional array or None (defauly)\n The elevation of the grid cells. Shape should be N-1 by M-1,\n where N and M are the dimensions of `X` and `Y` (like `mask`).\n triangles : optional bool (default = False)\n If True, triangles can be included\n\n Returns\n -------\n geopandas.GeoDataFrame\n\n \"\"\"\n\n # check X, Y shapes\n Y = validate.elev_or_mask(X, Y, 'Y', offset=0)\n\n # check elev shape\n elev = validate.elev_or_mask(X, elev, 'elev', offset=0)\n\n # check the mask shape\n mask = validate.elev_or_mask(X, mask, 'mask', offset=1)\n\n X = numpy.ma.masked_invalid(X)\n Y = numpy.ma.masked_invalid(Y)\n ny, nx = X.shape\n\n row = 0\n geodata = []\n for ii in range(nx - 1):\n for jj in range(ny - 1):\n if not (numpy.any(X.mask[jj:jj + 2, ii:ii + 2]) or mask[jj, ii]):\n row += 1\n Z = elev[jj, ii]\n # build the array or coordinates\n coords = misc.make_poly_coords(\n xarr=X[jj:jj + 2, ii:ii + 2],\n yarr=Y[jj:jj + 2, ii:ii + 2],\n zpnt=Z, triangles=triangles\n )\n\n # build the attributes\n record = OrderedDict(\n id=row, river=river, reach=reach,\n ii=ii + 2, jj=jj + 2, elev=Z,\n ii_jj='{:02d}_{:02d}'.format(ii + 2, jj + 2),\n geometry=Polygon(shell=coords)\n )\n\n # append to file is coordinates are not masked\n # (masked = beyond the river boundary)\n if coords is not None:\n geodata.append(record)\n\n gdf = geopandas.GeoDataFrame(geodata, crs=crs, geometry='geometry')\n gdf.to_file(outputfile)\n return gdf\n","sub_path":"pygridtools/iotools.py","file_name":"iotools.py","file_ext":"py","file_size_in_byte":9704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"269086471","text":"import pandas as pd\r\nimport pickle\r\nimport csv\r\n\r\ndef dict_assemble(save_format):\r\n businesses_df = pd.read_json('business.json', lines = True, encoding = \"utf-8\")\r\n\r\n iterator = 0\r\n\r\n restaurant_dict = dict()\r\n food_dict = dict()\r\n\r\n for row in businesses_df.itertuples():\r\n if row.is_open == 1 and 'Restaurants' in row.categories:\r\n iterator += 1\r\n business_name = row.name\r\n address = row.address\r\n city = row.city\r\n stars = row.stars\r\n categories = row.categories\r\n latitude = row.latitude\r\n longitude = row.longitude\r\n UID = iterator\r\n for cuisine in categories:\r\n if cuisine in food_dict:\r\n food_dict[cuisine].append(UID)\r\n else:\r\n food_dict[cuisine] = [UID]\r\n restaurant_dict[UID] = [business_name, address, city, stars, (longitude, latitude)]\r\n print(UID)\r\n if save_format == 'csv':\r\n restaurant_headers = restaurant_dict.keys()\r\n food_headers = food_dict.keys()\r\n with open(\"restaurant.csv\", \"w\", encoding = \"utf-8\") as f:\r\n writer = csv.writer(f)\r\n writer.writerow(restaurant_headers)\r\n writer.writerows(zip(restaurant_dict.values()))\r\n with open(\"food.csv\", \"w\", encoding = \"utf-8\") as g:\r\n writer = csv.writer(g)\r\n writer.writerow(food_headers)\r\n writer.writerows(zip(food_dict.values()))\r\n elif save_format == 'pickle':\r\n with open('restaurant.pickle', 'wb') as f:\r\n pickle.dump(restaurant_dict, f)\r\n with open('food.pickle', 'wb') as g:\r\n pickle.dump(food_dict, g)\r\n \r\n return \"Finished\"\r\n\r\n\r\n \r\n \r\n \r\n","sub_path":"business_dataframe.py","file_name":"business_dataframe.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"484187025","text":"# Task DEMO_B, 28.01.2019\n\ndata = input().split()\ndata = [int(data[x]) for x in range(len(data))]\n\nn, m = data\n\nk = 0\n\nfor i in range(n, m + 1):\n temp = i\n while temp % 2 == 0:\n temp = temp / 2\n while temp % 3 == 0:\n temp = temp / 3\n while temp % 5 == 0:\n temp = temp / 5\n\n if temp == 1:\n k += 1\n\nprint(k)","sub_path":"demo_b/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"397737142","text":"#-*-coding:utf8-*-\n__author__ = '万壑'\n\nimport threading\ndef job1():\n global A,lock\n lock.acquire()\n for i in range(30):\n A += 1\n print('job1', str(A))\n lock.release()\n\ndef job2():\n global A,lock\n lock.acquire()\n for i in range(10):\n A += 100\n print('job2', str(A))\n lock.release()\n\nif __name__ == '__main__':\n A = 0\n lock = threading.Lock()\n thread1 = threading.Thread(target=job1)\n thread2 = threading.Thread(target=job2)\n thread1.start()\n thread2.start()","sub_path":"thread/thread_lock.py","file_name":"thread_lock.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"634664653","text":"import torch\nimport torch.nn as nn\nfrom torchsummary import summary\nimport sys\n\nimport config\nfrom datasets import EdgeDetectionDataset, BinarizationDataset, CornerDetectionDataset\nfrom data import get_data_for_edge_detection, get_data_for_binarization, get_dataloader\nfrom models import ConvNet\nfrom train import train\n\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\n\nif __name__ == '__main__':\n if sys.argv[1] == 'canny':\n train_files, valid_files, test_files = get_data_for_edge_detection(config.DATA_DIR_EDGE)\n dataset = EdgeDetectionDataset\n\n elif sys.argv[1] == 'niblack':\n train_files, valid_files, test_files = get_data_for_binarization(config.DATA_DIR_BIN1, config.DATA_DIR_BIN2)\n dataset = BinarizationDataset\n\n elif sys.argv[1] == 'harris':\n pass\n\n train_loader = get_dataloader(dataset, train_files, config.BATCH_SIZE)\n valid_loader = get_dataloader(dataset, valid_files, config.BATCH_SIZE)\n test_loader = get_dataloader(dataset, test_files, config.BATCH_SIZE)\n\n model = ConvNet(in_channels=config.IN_CHANNELS,\n out_channels=config.OUT_CHANNELS,\n kernel_size=config.KERNEL_SIZE,\n stride=config.STRIDE,\n padding=config.PADDING).to(config.DEVICE)\n\n optimizer = torch.optim.Adam(model.parameters())\n loss = nn.BCELoss()\n\n print('Model:')\n print(model)\n\n print('Parameters of the model:')\n print(summary(model, (1, 64, 64)))\n\n print('Starting training:')\n history = train(model, optimizer, loss, train_loader, valid_loader, config.EPOCHS, config.DEVICE)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"326543900","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 22 09:19:58 2019\n\n@author: tom verguts\nchecking how dirac delta function behaves\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nlow, high = 0.00001, 1\nn_support = 100\ndelta = np.linspace(high, low, num = n_support)\ndirac = np.zeros(len(delta))\nfor delta_loop in range(len(delta)):\n dirac[delta_loop] = delta[delta_loop]*(1/delta[delta_loop])*np.log(1/delta[delta_loop])\n\nplt.plot(delta, dirac)","sub_path":"AY 2018 - 2019/dirac_delta.py","file_name":"dirac_delta.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"528929387","text":"import codecs\r\nimport re\r\n\r\nabs_root = \"./\"\r\n\r\n\r\ndef load_w2v(w2v_file, embedding_dim):\r\n fp = codecs.open(w2v_file, 'r', 'utf-8')\r\n w2v = []\r\n word_dict = dict()\r\n cnt = 0\r\n flag = True\r\n\r\n while flag:\r\n line = fp.readline()\r\n if not line:\r\n flag = False\r\n else:\r\n line = str(line)\r\n line = line.split()\r\n if len(line) != embedding_dim + 1:\r\n print('a bad word embedding'+str(line))\r\n continue\r\n w2v.append([float(v) for v in line[1:]])\r\n print(str(line[0]))\r\n word_dict[str(line[0])] = cnt\r\n cnt += 1\r\n print('shape of new word2vec library:', len(w2v))\r\n return word_dict, w2v\r\n\r\n\r\ndef merge_txt_files(files, destination):\r\n fo = codecs.open(destination, 'w', 'utf-8')\r\n for name in files:\r\n fi = codecs.open(name, \"r\", 'utf-8')\r\n while True:\r\n content = fi.read()\r\n if not content:\r\n break\r\n fo.write(content)\r\n fi.close()\r\n fo.close()\r\n\r\n\r\ndef load_inputs_data(input_file):\r\n word_list = []\r\n lines = codecs.open(input_file, \"r\", 'utf-8').readlines()\r\n for i in range(0, len(lines)):\r\n words = lines[i].lower().split()\r\n for w in words:\r\n if w not in word_list:\r\n word_list.append(w)\r\n return word_list\r\n\r\n\r\ndef generate_new_embedding_file(word_list, word_dict, w2v, newfile_name):\r\n new_file = codecs.open(newfile_name, 'w', \"'utf-8'\")\r\n\r\n for w in word_list:\r\n if w in word_dict:\r\n tmp = str(w)\r\n for k in w2v[word_dict[w]]:\r\n tmp = tmp + \" \" + str(k)\r\n tmp = tmp + \"\\n\"\r\n new_file.write(tmp)\r\n new_file.close()\r\n\r\n\r\nfile_list = [\".//data/nuclear/nuclear_dataset.txt\"]\r\n\r\nmerged_file = abs_root + \"//embedding_files//new_merged_content.txt\"\r\nw2v_file = abs_root + \"//embedding_files/glove.840B.300d.txt\"\r\nnew_file_name = abs_root + \"//embedding_files//new_embedding_file.txt\"\r\n\r\nembedding_dim = 300\r\n\r\nmerge_txt_files(file_list, merged_file)\r\nprint(\"Merge Finished\")\r\n\r\nword_list = load_inputs_data(merged_file)\r\nprint(len(word_list))\r\n\r\nword_dict, w2v = load_w2v(w2v_file, embedding_dim)\r\nprint(\"Load w2v file Finished\")\r\n\r\ngenerate_new_embedding_file(word_list, word_dict, w2v, new_file_name)\r\n\r\n\r\n\"\"\"do some filter after initial word2vec \"\"\"\r\nfp = codecs.open(new_file_name, 'r', 'utf-8')\r\nfp_new = codecs.open(new_file_name+\"filtered\", 'w', 'utf-8')\r\nlines = fp.readlines()\r\nfor i in lines:\r\n if (re.search(\"^[0-9][0-9]\\:\", i) is None) and (re.search(\"^[0-9]+\\s\", i) is None) \\\r\n and (re.search(\"^[0-9]+\\,[0-9]+\\s\", i) is None):\r\n fp_new.write(i)\r\n\r\n","sub_path":"generate_word_embedding_file.py","file_name":"generate_word_embedding_file.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"236195620","text":"\"\"\"\n------------------------------------------------------------------------\nAssignment 8, Task 2 - Letter comparisons\n------------------------------------------------------------------------\nAuthor: Nicolas Mills\nID: 180856100\nEmail: mill6100@mylaurier.ca\n__updated__ = 2019-03-21\n------------------------------------------------------------------------\n\"\"\"\nfrom functions import comparison_total, do_comparisons, \\\nletter_table\nfrom BST_linked import BST\nfrom Letter import Letter\n\nbst_1 = BST()\nbst_2 = BST()\nbst_3 = BST()\n\nDATA1 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nDATA2 = \"MFTCJPWADHKNRUYBEIGLOQSVXZ\"\nDATA3 = \"ETAOINSHRDLUCMPFYWGBVKJXZQ\"\n\nfor data in DATA1:\n letter = Letter(data)\n bst_1.insert(letter)\nfor data in DATA2:\n letter = Letter(data)\n bst_2.insert(letter)\nfor data in DATA3:\n letter = Letter(data)\n bst_3.insert(letter)\n\nfh = open('otoos610.txt', 'r')\ndo_comparisons(fh, bst_1) \ndo_comparisons(fh, bst_2) \ndo_comparisons(fh, bst_3) \n\ntotal_1 = comparison_total(bst_1)\ntotal_2 = comparison_total(bst_2)\ntotal_3 = comparison_total(bst_3)\n\nprint(\"DATA1 BST: {}\".format(total_1))\nprint(\"DATA2 BST: {}\".format(total_2))\nprint(\"DATA3 BST: {}\".format(total_3))\n","sub_path":"workspace/CP164/mill6100_a08/src/t02.py","file_name":"t02.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"30071442","text":"# Copyright (C) 2019 Caleb Lo\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\n# Machine Learning March Madness\n# Apply ML methods to predict outcome of 2016 NCAA Tournament\nfrom matplotlib import pyplot\nfrom tempfile import TemporaryFile\nfrom gen_kenpom_differential import gen_kenpom_differential\nfrom gen_srs_differential import gen_srs_differential\nfrom support_vector_machine import train_and_test_svm\nimport numpy\nimport itertools\nimport math\n\n\nclass Error(Exception):\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return repr(self.value)\n\n\ndef feature_normalize(x):\n \"\"\" Performs feature normalization.\n Args:\n x: Vector of training data.\n Returns:\n y: Vector of normalized training data.\n Raises:\n An error occurs if the number of training examples is 0.\n \"\"\"\n num_ex = x.shape[0]\n if num_ex == 0: raise Error('num_ex = 0')\n x_mean = numpy.mean(x)\n x_std = numpy.std(x)\n x_scale = (x-x_mean)/x_std\n return x_scale\n\n\ndef plot_data(x, y):\n \"\"\" Plots data.\n Args:\n x: Features to be plotted.\n y: Data labels.\n Returns:\n None.\n \"\"\"\n positive_indices = numpy.where(y == 1)\n negative_indices = numpy.where(y == 0)\n pos = pyplot.scatter(x[positive_indices, 0], x[positive_indices, 1], s=80,\n marker='+', color='k')\n pyplot.hold(True)\n neg = pyplot.scatter(x[negative_indices, 0], x[negative_indices, 1], s=80,\n marker='s', color='y')\n pyplot.legend((pos, neg), ('y = 1', 'y = 0'), loc='lower right')\n pyplot.hold(False)\n pyplot.ylabel('Seed Difference', fontsize=18)\n pyplot.xlabel('Net Point Differential', fontsize=18)\n return None\n\n\ndef plot_decision_boundary(x, y, theta):\n \"\"\" Plots decision boundary.\n Args:\n x: Features that have already been plotted.\n y: Data labels.\n theta: Parameter that determines slope of decision boundary.\n Returns:\n None.\n \"\"\"\n plot_data(x, y)\n pyplot.hold(True)\n y_line_vals = (theta[0]+theta[1]*x[:, 0])/(-1*theta[2])\n pyplot.plot(x[:, 0], y_line_vals, 'b-', markersize=18)\n pyplot.hold(False)\n return None\n\n\ndef gen_train_results(prev_tourney_results):\n \"\"\" Generates matrix of training results by parsing data from previous\n tournaments.\n Args:\n prev_tourney_results: Matrix of previous tournament results that consists\n of these columns:\n Column 1: character denoting season ID\n Column 2: integer denoting ID of date of game\n Column 3: integer denoting ID of winning team\n Column 4: integer denoting score of winning team\n Column 5: integer denoting ID of losing team\n Column 6: integer denoting score of losing team\n Column 7: number of overtime periods\n Returns:\n training_data: Matrix that consists of these columns:\n Column 1: integer denoting season ID\n Column 2: integer denoting ID of team A\n Column 3: integer denoting ID of team B (assume that in\n each row, value in Column 3 exceeds value in Column 2)\n Column 4: 0 if team A lost to team B; otherwise, 1 (assume\n that A and B played in that season's tournament)\n Column(s) of training features will be added by other\n functions\n \"\"\"\n num_prev_tourney_games = prev_tourney_results.shape[0]-1\n training_data = numpy.zeros((num_prev_tourney_games, 4))\n for prev_tourney_game_idx in range(0, num_prev_tourney_games):\n season_id = prev_tourney_results[prev_tourney_game_idx+1, 0]\n winning_team_id = prev_tourney_results[prev_tourney_game_idx+1, 2]\n losing_team_id = prev_tourney_results[prev_tourney_game_idx+1, 4]\n if (winning_team_id < losing_team_id):\n team_A = winning_team_id\n team_B = losing_team_id\n outcome = 1\n else:\n team_A = losing_team_id\n team_B = winning_team_id\n outcome = 0\n training_data[prev_tourney_game_idx, 0] = season_id\n training_data[prev_tourney_game_idx, 1] = team_A\n training_data[prev_tourney_game_idx, 2] = team_B\n training_data[prev_tourney_game_idx, 3] = outcome\n return training_data\n\n\ndef coin_flip(team_ids):\n \"\"\" Generates coin-flip predictions.\n Args:\n team_ids: Vector of team IDs.\n Returns:\n pred_mat: Matrix of coin-flip predictions, where first and second columns\n include IDs of distinct teams; each entry in third column is\n 0.5. Only unordered pairings of teams appear in this matrix.\n \"\"\"\n team_ids_list = team_ids.tolist()\n team_id_pairs = itertools.combinations(team_ids_list, 2)\n team_id_pairs_array = numpy.asarray(list(team_id_pairs))\n coin_flips = 0.5*numpy.ones((team_id_pairs_array.shape[0], 1))\n pred_mat = numpy.concatenate((team_id_pairs_array, coin_flips), axis=1)\n return pred_mat\n\n\ndef gen_raw_submission(file_name, pred_mat, curr_season_id, curr_tourney_teams):\n \"\"\" Generates raw submission file.\n Args:\n file_name: Name of raw submission file.\n pred_mat: Matrix of predictions, where first and second columns include\n IDs of distinct teams; each entry in third column is probability\n that team in first column defeats team in second column. Only\n unordered pairings of teams appear in this matrix.\n curr_season_id: Year of current season\n curr_tourney_teams: IDs of teams in this year's tournament\n Returns:\n None.\n \"\"\"\n num_pairs = pred_mat.shape[0]\n num_tourney_teams = curr_tourney_teams.shape[0]\n num_tourney_pairs = (num_tourney_teams)*(num_tourney_teams-1)/2\n file_mat = numpy.zeros((num_tourney_pairs+1, 2), dtype=object)\n file_mat[0, 0] = \"id\"\n file_mat[0, 1] = \"pred\"\n team_counter = 0\n for pair_idx in range(0, num_pairs):\n id1 = pred_mat[pair_idx, 0].astype(float)\n id2 = pred_mat[pair_idx, 1].astype(float)\n curr_id = \"%d_%d_%d\" % (curr_season_id, id1, id2)\n if (id1 in curr_tourney_teams and id2 in curr_tourney_teams):\n file_mat[team_counter+1, 0] = curr_id\n file_mat[team_counter+1, 1] = str(pred_mat[pair_idx, 2])\n team_counter = team_counter+1\n numpy.savetxt(file_name, file_mat, fmt='%s', delimiter=',')\n\n\ndef parse_raw_submission(raw_submission):\n \"\"\" Parses raw submission input and returns matrix.\n Args:\n raw_submission: Matrix of raw submission input, where first column\n includes entries of the form \"S_A_B\" where A and B are the\n IDs of two teams; second column includes probabilities\n that team A will defeat team B.\n Returns:\n parsed_submission: Matrix with three columns, where first and second\n columns include IDs of above-mentioned teams A and B,\n respectively; third column includes above-mentioned\n probabilities.\n \"\"\"\n raw_games = raw_submission[:, 0]\n num_games = raw_games.shape[0]-1\n id1 = numpy.zeros((num_games, 1))\n id2 = numpy.zeros((num_games, 1))\n for game_index in range(1, num_games+1):\n curr_game = raw_games[game_index]\n curr_game_string = numpy.array2string(curr_game)\n S,tmp_id1,tmp_id2 = curr_game_string.split(\"_\")\n id1[game_index-1] = int(tmp_id1)\n tmp2_id2,tmp3_id2 = tmp_id2.split(\"'\")\n id2[game_index-1] = tmp2_id2\n submit_probs = raw_submission[1:(num_games+1), 1]\n parsed_probs = submit_probs.reshape((num_games, 1))\n parsed_submission = numpy.concatenate((id1, id2, parsed_probs), axis=1)\n return parsed_submission\n\n\ndef evaluate_submission(results, submission, season_ids, bound_extreme):\n \"\"\" Computes predicted binomial deviance between results and submission for\n a set of seasons.\n Args:\n results: Matrix of tournament results, where each row represents a game;\n third and fifth columns include IDs of winning and losing teams,\n respectively.\n submission: Matrix of submissions, where each row represents a game; first\n two columns include IDs of two teams and third column includes\n probability that first team wins.\n season_ids: Array of integers denoting IDs of seasons for submission\n bound_extreme: Scalar that is used to prevent overflow in computations\n Returns:\n log_loss: Predicted binomial deviance.\n \"\"\"\n str_seasons = results[1:, 0]\n seasons = numpy.zeros((str_seasons.shape[0], 1))\n for season_index in range(0, str_seasons.shape[0]):\n seasons[season_index] = str_seasons[season_index]\n winners = results[1:, 2].astype(int)\n losers = results[1:, 4].astype(int)\n submission_team1 = submission[:, 0].astype(float)\n submission_team2 = submission[:, 1].astype(float)\n submission_prob = submission[:, 2].astype(float)\n num_games = results.shape[0]-1\n log_loss_array = numpy.zeros((num_games, 1))\n num_seasons = len(season_ids)\n num_submissions = submission.shape[0]\n num_subs_per_season = num_submissions/num_seasons\n curr_game_index = 0\n for season_index in range(0, num_seasons):\n curr_season = season_ids[season_index]\n start_index = season_index*num_subs_per_season\n end_index = (season_index+1)*num_subs_per_season\n curr_sub_team1 = submission_team1[start_index:end_index]\n curr_sub_team2 = submission_team2[start_index:end_index]\n curr_sub_prob = submission_prob[start_index:end_index]\n season_game_index = numpy.where(seasons == curr_season)\n curr_winners = winners[season_game_index[0]]\n curr_losers = losers[season_game_index[0]]\n curr_num_games = curr_winners.shape[0]\n for game_index in range(0, curr_num_games):\n curr_winner = curr_winners[game_index]\n curr_loser = curr_losers[game_index]\n\n # Find game involving this winner and loser in submission\n if (curr_winner < curr_loser):\n curr_outcome = 1\n winner_index = numpy.where(curr_sub_team1 == curr_winner)\n loser_index = numpy.where(curr_sub_team2 == curr_loser)\n else:\n curr_outcome = 0\n loser_index = numpy.where(curr_sub_team1 == curr_loser)\n winner_index = numpy.where(curr_sub_team2 == curr_winner)\n submission_index = numpy.intersect1d(winner_index[0],\n loser_index[0])\n curr_prob = curr_sub_prob[submission_index].astype(float)\n\n # Bound prediction from extremes if necessary\n if (curr_prob == 1):\n curr_prob = 1-bound_extreme\n elif (curr_prob == 0):\n curr_prob = bound_extreme\n\n # Evaluate per-game log loss\n log_loss_term1 = curr_outcome*math.log(curr_prob)\n log_loss_term2 = (1-curr_outcome)*math.log(1-curr_prob)\n log_loss_array[curr_game_index] = log_loss_term1+log_loss_term2\n curr_game_index = curr_game_index+1\n curr_log_loss = (-1/curr_game_index)*numpy.sum(log_loss_array)\n\n # Compute log loss\n log_loss = (-1/num_games)*numpy.sum(log_loss_array)\n return log_loss\n\n\ndef main():\n \"\"\" Main function\n \"\"\"\n print(\"Loading list of teams.\")\n teams = numpy.genfromtxt(\"teams_2016.csv\", delimiter=\",\")\n team_ids = teams[1:, 0]\n print(\"Loading regular season results.\")\n regular_season_results = (\n numpy.genfromtxt(\"regular_season_results_2016.csv\",\n delimiter=\",\"))\n print(\"Loading tournament results.\")\n tourney_results = numpy.genfromtxt(\"tourney_results_prev_2016.csv\",\n delimiter=\",\")\n print(\"Loading current tournament results.\")\n curr_tourney_results = numpy.genfromtxt(\"tourney_results_2016.csv\",\n delimiter=\",\")\n print(\"Loading KenPom data.\")\n kenpom_data = numpy.genfromtxt(\"kenpom_2016.csv\", delimiter=\",\")\n\n # Generate training results\n training_mat = gen_train_results(tourney_results)\n\n # Initialize parameters\n bound_extreme = 0.0000000000000020278\n curr_const = 0.001\n curr_season_id = 2016\n feat_norm_flag = 0\n num_splits = 10\n train_ratio = 0.75\n year_flag = 1\n\n # Compute SRS differential between teams A and B for each season\n print(\"Computing SRS differential...\")\n srs_diff_mat_list = gen_srs_differential(regular_season_results,\n team_ids, training_mat,\n curr_season_id, curr_const,\n year_flag)\n srs_diff_mat = srs_diff_mat_list['srs_diff_mat']\n\n # Set training features and labels\n srs_idx1 = numpy.where(srs_diff_mat[:, 4] != curr_const)\n srs_idx = srs_idx1[0]\n if (feat_norm_flag == 1):\n feature_srs_scale = feature_normalize(srs_diff_mat[srs_idx, 4])\n else:\n feature_srs_scale = srs_diff_mat[srs_idx, 4]\n x_mat = numpy.reshape(feature_srs_scale, (feature_srs_scale.shape[0], 1))\n label_vec = srs_diff_mat[srs_idx, 3]\n\n # Set current season testing features and labels\n srs_diff_curr_season = srs_diff_mat_list['curr_season_mat']\n if (feat_norm_flag == 1):\n curr_feature_srs_scale = feature_normalize(srs_diff_curr_season[:, 3])\n else:\n curr_feature_srs_scale = srs_diff_curr_season[:, 3]\n x_curr_mat = numpy.reshape(curr_feature_srs_scale,\n (curr_feature_srs_scale.shape[0], 1))\n\n # Compute KenPom differential between teams A and B for each season\n print(\"Computing KenPom differential...\")\n kenpom_diff_mat_list = gen_kenpom_differential(kenpom_data, team_ids,\n training_mat,\n curr_season_id, curr_const,\n year_flag)\n kenpom_diff_mat = kenpom_diff_mat_list['kenpom_diff_mat']\n kenpom_idx1 = numpy.where(kenpom_diff_mat[:, 4] != curr_const)\n kenpom_idx = kenpom_idx1[0]\n if (feat_norm_flag == 1):\n feature_kenpom_scale = feature_normalize(kenpom_diff_mat[kenpom_idx, 4])\n else:\n feature_kenpom_scale = kenpom_diff_mat[kenpom_idx, 4]\n kenpom_x_mat = numpy.reshape(feature_kenpom_scale,\n (feature_kenpom_scale.shape[0], 1))\n kenpom_diff_curr_season = kenpom_diff_mat_list['curr_season_mat']\n if (feat_norm_flag == 1):\n curr_feature_kenpom_scale = (\n feature_normalize(kenpom_diff_curr_season[:, 3]))\n else:\n curr_feature_kenpom_scale = kenpom_diff_curr_season[:, 3]\n kenpom_x_curr_mat = numpy.reshape(curr_feature_kenpom_scale,\n (curr_feature_kenpom_scale.shape[0], 1))\n kenpom_label_vec = kenpom_diff_mat[kenpom_idx, 3]\n num_kenpom_games = kenpom_x_mat.shape[0]\n num_games = x_mat.shape[0]\n x_comb_mat = numpy.c_[x_mat[(num_games-num_kenpom_games):num_games, :],\n kenpom_x_mat]\n x_curr_mat = numpy.c_[x_curr_mat, kenpom_x_curr_mat]\n\n # Randomize train/test splits\n numpy.random.seed(10)\n test_array = numpy.zeros((num_splits, 1))\n init_x_curr_mat = x_curr_mat\n for split_idx in range(0, num_splits):\n # print(\"\")\n train_idx = numpy.random.choice(x_comb_mat.shape[0],\n train_ratio*x_comb_mat.shape[0],\n replace=False)\n test_idx = numpy.setdiff1d(numpy.arange(x_comb_mat.shape[0]), train_idx)\n train_mat = x_comb_mat[train_idx, :]\n train_label = kenpom_label_vec[train_idx]\n x_test_mat = x_comb_mat[test_idx, :]\n test_label = kenpom_label_vec[test_idx]\n\n # Use SVM for training and testing\n svm_list = train_and_test_svm(train_mat, train_label, x_test_mat,\n x_curr_mat)\n test_prob = svm_list['test_prob']\n curr_prob = svm_list['curr_prob']\n\n # Compute evaluation function of test data\n num_test_games = test_label.shape[0]\n log_loss_array = numpy.zeros((num_test_games, 1))\n for game_index in range(0, num_test_games):\n curr_outcome = test_label[game_index]\n curr_game_prob = test_prob[game_index]\n\n # Bound prediction from extremes if necessary\n if (curr_game_prob == 1):\n curr_game_prob = 1-bound_extreme\n elif (curr_game_prob == 0):\n curr_game_prob = bound_extreme\n\n # Evaluate per-game log loss\n log_loss_term1 = curr_outcome*math.log(curr_game_prob)\n log_loss_term2 = (1-curr_outcome)*math.log(1-curr_game_prob)\n log_loss_array[game_index] = log_loss_term1+log_loss_term2\n test_log_loss = (-1/num_test_games)*numpy.sum(log_loss_array)\n test_array[split_idx] = test_log_loss\n\n # Aggregate probabilities for current season\n if (split_idx == 0):\n curr_array = curr_prob\n else:\n curr_array = numpy.c_[curr_array, curr_prob]\n print(\"\")\n print(\"Average test binomial deviance = %.5f\" % numpy.mean(test_array))\n\n # Compute weighted probabilities for current season\n print(\"\")\n curr_avg_prob = numpy.mean(curr_array, axis=1)\n\n # Generate raw submission file\n curr_file_name = \"curr_submission_2016.csv\"\n init_pred_mat = coin_flip(team_ids)\n curr_pred_mat = numpy.c_[init_pred_mat[:, 0:2], curr_avg_prob]\n curr_tourney_winners = curr_tourney_results[1:, 2].astype(int)\n curr_tourney_losers = curr_tourney_results[1:, 4].astype(int)\n curr_tourney_teams = numpy.union1d(curr_tourney_winners,\n curr_tourney_losers)\n curr_first_four_losers = numpy.array([1192, 1380, 1409, 1435])\n curr_tourney_teams = numpy.union1d(curr_tourney_teams,\n curr_first_four_losers)\n gen_raw_submission(curr_file_name, curr_pred_mat, curr_season_id,\n curr_tourney_teams)\n\n # Load raw submission file\n print(\"Loading curr submission file.\")\n curr_raw_submission = numpy.genfromtxt(curr_file_name, dtype=None,\n delimiter=\",\")\n\n # Parse raw submission file\n curr_submission = parse_raw_submission(curr_raw_submission)\n\n # Compute evaluation function of submission\n curr_log_loss = evaluate_submission(curr_tourney_results, curr_submission,\n [curr_season_id], bound_extreme)\n print(\"Current binomial deviance = %.5f\" % curr_log_loss)\n\n# Call main function\nif __name__ == \"__main__\":\n main()\n","sub_path":"ml_march_madness_2016.py","file_name":"ml_march_madness_2016.py","file_ext":"py","file_size_in_byte":19773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"15212772","text":"'''\n\nhttp://projecteuler.net/problem=1\n\n'''\n\nimport numpy as np\n\nnum1 = 3\nnum2 = 5\n\nnmin = 1\nnmax = 1000\nstep = 1\n\nnums = np.arange(nmin, nmax+1., step)\n\nsome_array = []\n\ndef mult_sum(num1, num2, nmin, nmax, step):\n\tfor i, pos in enumerate(nums):\n\t\tif (i%num1 ==0 or i%num2 == 0):\n\t\t\tsome_array.append(i)\n\tx = sum(some_array)\n\treturn some_array, x\n\nsome_array, x = mult_sum(num1, num2, nmin, nmax, step) \n\n\n","sub_path":"p_.euler_01.py","file_name":"p_.euler_01.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"184466798","text":"#\n# Created on July 8, 2019\n#\n# @author: Julian Fortune\n# @Description: Functions for testing and validating the voice activity algorithm.\n#\n\nimport sys, time, glob, os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport librosa\nimport random\nimport webrtcvad\n\nfrom speechLibrary import featureModule, speechAnalysis, audioModule\n\nsys.path.append(\"../validation/rVADfast_py_2.0/\")\nimport rVAD_fast\n\nnp.set_printoptions(threshold=sys.maxsize)\n\ndef compareVoiceActivityToParticipants():\n audioDirectory = \"../media/Participant_Audio_30_Sec_Chunks/*.wav\"\n speechAnalyzer = speechAnalysis.SpeechAnalyzer()\n\n transcript = []\n\n totalNumberOfVoiceActivityInstances = 0\n totalNumberOfCorrectlyDetectedVoiceActivityInstances = 0\n totalNumberOfFalseAlarms = 0\n\n with open(\"../media/Participant_Audio_30_Sec_Chunks_Transcripts/voice_activity.txt\") as transcriptFile:\n lines = transcriptFile.readlines()\n for row in lines:\n transcript.append(row.strip().split(', '))\n\n for line in transcript:\n name = line[0]\n\n if name[0] != \"#\":\n actualVoiceActivity = [int(element) for element in line[1:31]]\n\n for filePath in sorted(glob.iglob(audioDirectory)):\n fileName = os.path.basename(filePath)[:-4]\n\n if fileName == name:\n audio = audioModule.Audio(filePath=filePath)\n if audio.numberOfChannels != 1:\n audio.makeMono()\n\n rawVoiceActivity = speechAnalyzer.getVoiceActivityFromAudio(audio)\n\n # voiceActivityBufferSize = int(100 / speechAnalyzer.voiceActivityStepSize)\n # voiceActivityBuffered = featureModule.createBufferedBinaryArrayFromArray(voiceActivity == 1, voiceActivityBufferSize)\n\n frameSizeInSeconds = 1\n frameSizeInSteps = int(frameSizeInSeconds / (speechAnalyzer.featureStepSize / 1000))\n voiceActivity = []\n\n for frame in range (0, int(len(audio.data) / audio.sampleRate / (frameSizeInSeconds))):\n voiceActivityValue = int(max(rawVoiceActivity[frame * frameSizeInSteps:frame * frameSizeInSteps + frameSizeInSteps]))\n voiceActivity.append(voiceActivityValue)\n\n if voiceActivityValue == 1:\n if actualVoiceActivity[frame] == 0:\n totalNumberOfFalseAlarms += 1\n if actualVoiceActivity[frame] == 1:\n totalNumberOfCorrectlyDetectedVoiceActivityInstances += 1\n\n if voiceActivity != actualVoiceActivity:\n print(name, \"x\")\n print(actualVoiceActivity)\n print(voiceActivity)\n else:\n print(name, \"✓\")\n print(sum(rawVoiceActivity))\n\n totalNumberOfVoiceActivityInstances += int(sum(actualVoiceActivity))\n\n\n precision = totalNumberOfCorrectlyDetectedVoiceActivityInstances / (totalNumberOfCorrectlyDetectedVoiceActivityInstances + totalNumberOfFalseAlarms)\n recall = totalNumberOfCorrectlyDetectedVoiceActivityInstances / totalNumberOfVoiceActivityInstances\n\n fMeasure = 2 * precision * recall / (precision + recall)\n\n print(\" Actual | Seconds with voice activity:\", totalNumberOfVoiceActivityInstances)\n print(\" Algorithm | Correct detectsions:\", totalNumberOfCorrectlyDetectedVoiceActivityInstances, \"Precision:\", precision, \"Recall:\", recall, \"F-measure\", fMeasure)\n\ndef voiceActivityRuns():\n filePath = \"../media/Participant_Audio/p10_ol.wav\"\n name = os.path.basename(filePath)[:-4]\n\n speechAnalyzer = speechAnalysis.SpeechAnalyzer()\n\n audio = audioModule.Audio(filePath=filePath)\n if audio.numberOfChannels != 1:\n audio.makeMono()\n\n voiceActivity = speechAnalyzer.getVoiceActivityFromAudio(audio)\n print(\"Total voice activity:\", sum(voiceActivity))\n\n runs = 0\n voiceActivityPresent = False\n for frame in voiceActivity:\n if not voiceActivityPresent and frame == 1:\n voiceActivityPresent = True\n runs += 1\n if voiceActivityPresent and frame == 0:\n voiceActivityPresent = False\n print(\"Total number of segments of voice activity:\", runs)\n\ndef tunerVAD():\n thresholdValues = np.arange(1, 2.1, 0.1)\n print(\"threshold values:\", thresholdValues)\n\n audioDirectory = \"../media/validation_participant_audio/\"\n speechAnalyzer = speechAnalysis.SpeechAnalyzer()\n\n results = []\n\n for threshold in thresholdValues:\n print(threshold)\n\n transcript = []\n\n totalNumberOfVoiceActivityInstances = 0\n totalNumberOfCorrectlyDetectedVoiceActivityInstances = 0\n totalNumberOfFalseAlarms = 0\n\n with open(audioDirectory + \"/voice_activity.txt\") as transcriptFile:\n lines = transcriptFile.readlines()\n for row in lines:\n transcript.append(row.strip().split(', '))\n\n # linesToCheck = list(range(0,len(transcript)))\n # random.shuffle(linesToCheck)\n #\n # print(linesToCheck[:10])\n #\n # for lineIndex in linesToCheck[:20]:\n # line = transcript[lineIndex]\n for line in transcript:\n name = line[0]\n\n if name[0] != \"#\":\n actualVoiceActivity = [int(element) for element in line[1:31]]\n\n # Find the match audio file\n for filePath in sorted(glob.iglob(audioDirectory + \"*.wav\")):\n fileName = os.path.basename(filePath)[:-4]\n\n if fileName == name:\n print(fileName)\n\n audio = audioModule.Audio(filePath=filePath)\n if audio.numberOfChannels != 1:\n audio.makeMono()\n\n rVADVoiceActivity = rVAD_fast.voiceActivity(finwav= filePath,\n vadThres=threshold)\n\n rVADVoiceActivityBins = []\n\n frameSizeInSeconds = 1\n frameSizeInSteps = int(frameSizeInSeconds / (speechAnalyzer.featureStepSize / 1000))\n voiceActivity = []\n\n originalNumberOfFalseAlarms = totalNumberOfFalseAlarms\n\n for frame in range (0, int(len(audio.data) / audio.sampleRate / (frameSizeInSeconds))):\n start = frame * frameSizeInSteps\n end = frame * frameSizeInSteps + frameSizeInSteps\n\n rVADVoiceActivityValue = int(max(rVADVoiceActivity[start:end]))\n rVADVoiceActivityBins.append(rVADVoiceActivityValue)\n\n if rVADVoiceActivityValue == 1:\n if actualVoiceActivity[frame] == 0:\n totalNumberOfFalseAlarms += 1\n if actualVoiceActivity[frame] == 1:\n totalNumberOfCorrectlyDetectedVoiceActivityInstances += 1\n\n print(\" actual \", end=\"\")\n for element in actualVoiceActivity:\n if element == 0:\n print(\"-\", end=\"\")\n else:\n print(\"█\", end=\"\")\n print()\n print(\" rVAD \", end=\"\")\n for element in rVADVoiceActivityBins:\n if element == 0:\n print(\"-\", end=\"\")\n else:\n print(\"█\", end=\"\")\n print()\n\n totalNumberOfVoiceActivityInstances += int(sum(actualVoiceActivity))\n\n precision = totalNumberOfCorrectlyDetectedVoiceActivityInstances / (totalNumberOfCorrectlyDetectedVoiceActivityInstances + totalNumberOfFalseAlarms)\n recall = totalNumberOfCorrectlyDetectedVoiceActivityInstances / totalNumberOfVoiceActivityInstances\n\n fMeasure = 2 * precision * recall / (precision + recall)\n\n print(\" Actual | Seconds with voice activity:\", totalNumberOfVoiceActivityInstances)\n print(\" Algorithm | Correct detectsions:\", totalNumberOfCorrectlyDetectedVoiceActivityInstances, \"False alarms:\", totalNumberOfFalseAlarms, \"Precision:\", precision, \"Recall:\", recall, \"F-measure\", fMeasure)\n\n results.append([threshold, fMeasure])\n\n\ndef testWebRTCVAD(wavFile):\n sampleRateForDownsampling = [8000, 16000, 32000, 48000][2]\n windowSize = 10 # MS\n\n vad = webrtcvad.Vad()\n\n audio = audioModule.Audio(filePath= wavFile)\n audio.makeMono()\n\n print(audio.data.shape)\n\n audio.data = librosa.core.resample(audio.data, audio.sampleRate, sampleRateForDownsampling)\n audio.sampleRate = sampleRateForDownsampling\n\n print(audio.data.shape)\n\n windowSizeInSamples = int(audio.sampleRate / 1000 * windowSize)\n\n # # Pad the end of the array\n # audio.data = np.pad(data, (0, int(windowSizeInSamples - stepSizeInSamples)), mode='constant')\n\n # Create frames using optimized algorithm\n framedData = librosa.util.frame(audio.data,\n frame_length=windowSizeInSamples,\n hop_length=windowSizeInSamples)\n\n print(framedData.shape)\n\n voiceActivity = []\n\n for frame in framedData:\n print(frame.shape)\n frameData = frame.copy(order='C')\n binData = wavio._array2wav(frame, 2)\n print(binData)\n voiceActivity = [1 if vad.is_speech(f, vad.is_speech(binData, audio.sampleRate)) else 0 for f in frames]\n\n return np.array(voiceActivity)\n\ndef main():\n tunerVAD()\n\nmain()\n","sub_path":"voiceActivityTesting.py","file_name":"voiceActivityTesting.py","file_ext":"py","file_size_in_byte":9946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"34109087","text":"import os, sys\nimport pycurl \nimport StringIO \nimport ast\nimport urllib2\nimport json\nimport datetime\nimport pprint\nfrom HTMLParser import HTMLParser\n\n\nclass HTMLParserRuns(HTMLParser):\n \"\"\"\n parses pages with formatting like\n https://cmsweb.cern.ch/dqm/offline/data/browse/ROOT/OfflineData/Run2017/StreamExpress/0003019xx/\n >>> parser = HTMLParserRuns()\n >>> parser.feed(content)\n >>> pprint.pprint(parser.get_run_linktimestamps())\n \"\"\"\n links = []\n timestamps = []\n BASE_URL = \"https://cmsweb.cern.ch\"\n cur_tag = None\n def handle_starttag(self, tag, attrs):\n self.cur_tag = tag\n if tag == \"a\":\n self.links.append(dict(attrs)[\"href\"])\n\n def handle_data(self, data):\n if self.cur_tag == \"td\":\n if \"UTC\" in data:\n self.timestamps.append(datetime.datetime.strptime(data.strip(), \"%Y-%m-%d %H:%M:%S %Z\"))\n\n def get_run_links(self):\n new_links = []\n for link in self.links:\n if \"/000\" not in link: continue\n new_links.append(self.BASE_URL + link)\n return new_links\n\n def get_run_timestamps(self):\n return self.timestamps\n\n def get_run_linktimestamps(self):\n \"\"\"\n return list of pairs of (link to run, UTC timestamp)\n Note that timestamp should be compared to datetime.datetime.utcnow() to see \n if the folder has been updated\n \"\"\"\n new_pairs = []\n for link,ts in zip(self.get_run_links(), self.get_run_timestamps()):\n if \".root\" in link and \"DQMIO\" not in link: continue\n new_pairs.append([link,ts])\n return new_pairs\n\n def clear(self):\n self.links = []\n self.timestamps = []\n\ndef get_proxy_file():\n cert_file = '/tmp/x509up_u%s' % str(os.getuid())\n return cert_file\n\ndef curl_progress(total_to_download, total_downloaded, total_to_upload, total_uploaded):\n if total_to_download:\n to_print = progress_bar(1.0*total_downloaded/total_to_download)\n sys.stdout.write(\"\\r\"+to_print)\n sys.stdout.flush()\n\ndef hsv_to_rgb(h, s, v):\n if s == 0.0: v*=255; return [v, v, v]\n i = int(h*6.)\n f = (h*6.)-i; p,q,t = int(255*(v*(1.-s))), int(255*(v*(1.-s*f))), int(255*(v*(1.-s*(1.-f)))); v*=255; i%=6\n if i == 0: return [v, t, p]\n elif i == 1: return [q, v, p]\n elif i == 2: return [p, v, t]\n elif i == 3: return [p, q, v]\n elif i == 4: return [t, p, v]\n elif i == 5: return [v, p, q]\n\ndef progress_bar(fraction, width=40, do_color=True, do_unicode=True,override_color=[]):\n fraction = min(max(fraction, 0.), 1.)\n nfilled = int(fraction * width)\n color_open, color_close = \"\", \"\"\n filled = \"#\"*nfilled\n unfilled = \"-\"*(width-nfilled)\n if do_unicode:\n filled = unichr(0x2589).encode('utf-8') * nfilled\n unfilled = unichr(0x2594+24).encode('utf-8')*(width-nfilled)\n\n if do_color:\n if override_color:\n rgb = override_color\n else:\n rgb = hsv_to_rgb(1.0 / 3.6 * fraction, 0.9, 0.9)\n color_open = \"\\033[38;2;%i;%i;%im\" % tuple(rgb)\n color_close = \"\\033[0m\"\n return \"|{0}{1}{2}{3}| [{4:.1f}%]\".format(color_open,filled, color_close,unfilled,100.0*fraction)\n\ndef get_url_with_cert(url):\n b = StringIO.StringIO() \n c = pycurl.Curl() \n cert = get_proxy_file()\n c.setopt(pycurl.WRITEFUNCTION, b.write) \n c.setopt(pycurl.CAPATH, '/etc/grid-security/certificates') \n c.unsetopt(pycurl.CAINFO)\n c.setopt(pycurl.SSLCERT, cert)\n c.setopt(pycurl.URL, url) \n c.perform() \n content = b.getvalue()\n return content\n\ndef get_file_with_cert(url, fname_out):\n c = pycurl.Curl() \n cert = get_proxy_file()\n c.setopt(pycurl.CAPATH, '/etc/grid-security/certificates') \n c.setopt(pycurl.URL, url)\n c.setopt(pycurl.SSLCERT, cert)\n c.setopt(pycurl.FOLLOWLOCATION, 1)\n c.unsetopt(pycurl.CAINFO)\n c.setopt(pycurl.NOPROGRESS, 0)\n c.setopt(pycurl.PROGRESSFUNCTION, curl_progress)\n c.setopt(pycurl.MAXREDIRS, 5)\n c.setopt(pycurl.NOSIGNAL, 1)\n with open(fname_out, \"w\") as fhout:\n c.setopt(c.WRITEFUNCTION, fhout.write)\n c.perform()\n\ndef fetch():\n print(\"Fetching DQM files...\")\n # content = get_url_with_cert(\"https://cmsweb.cern.ch/dqm/offline/data/browse/ROOT/OfflineData/Run2017/SingleMuon/0003019xx/\")\n # old_content = get_url_with_cert(\"https://cmsweb.cern.ch/dqm/offline/data/browse/ROOT/OfflineData/Run2017/SingleMuon/0003022xx/\")\n content = get_url_with_cert(\"https://cmsweb.cern.ch/dqm/offline/data/browse/ROOT/OfflineData/Run2017/SingleMuon/\")\n # print get_url_with_cert(\"https://cmsweb.cern.ch/dqm/offline/data/browse/ROOT/OfflineData/Run2017/StreamExpress/\")\n # print get_url_with_cert(\"https://cmsweb.cern.ch/dqm/offline/data/browse/ROOT/OfflineData/Run2017/StreamExpress/0003019xx/\")\n\n parser = HTMLParserRuns()\n parser.feed(content)\n allRuns = parser.get_run_linktimestamps()\n curdate = datetime.datetime.utcnow()\n\n toParse = []\n\n # Check for new runs\n for link in allRuns:\n linkdate = link[1]\n if linkdate.month == curdate.month and linkdate.day == curdate.day:\n toParse.append(link[0])\n\n # Parse new runs for new root files\n for url in toParse:\n print(url)\n new_content = get_url_with_cert(url)\n new_parser = HTMLParserRuns()\n new_parser.clear()\n new_parser.feed(new_content)\n parsedLst = new_parser.get_run_linktimestamps()\n\n for new_link in parsedLst:\n fname = new_link[0].split(\"DQM\")[1].split(\"_\")[2].split(\"R000\")[1]\n linkdate = new_link[1]\n\n if linkdate.month == curdate.month and linkdate.day == curdate.day:\n fname = new_link[0].split(\"DQM\")[1].split(\"_\")[2].split(\"R000\")[1]\n print(\"\\nNew file found: {0}\\nFile date: {1} Current date: {2}\\n\".format(fname, linkdate, curdate))\n print(\"url: {0}\".format(new_link[0]))\n get_file_with_cert(new_link[0], \"root_files/{0}.root\".format(fname))\n\n print(\"\\n\")\n\n\nif __name__=='__main__':\n fetch()\n","sub_path":"fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":6109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"339060921","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport tests.users as u\nfrom urllib.parse import urlencode\nfrom controller import helper as h\nfrom tests.testcase import APITestCase\nfrom controller.punc.tool.diff import Diff\nfrom controller.punc.base import ReelHandler\n\n\nclass TestToolApi(APITestCase):\n def setUp(self):\n super(TestToolApi, self).setUp()\n # 创建几个专家用户(权限足够),用于审校流程的测试\n self.add_first_user_as_admin_then_login()\n self.add_users_by_admin(\n [dict(email=r[0], name=r[2], password=r[1]) for r in [u.expert1, u.expert2, u.expert3]],\n '标点专家,文字专家'\n )\n self.reset_tasks_and_data()\n\n def tearDown(self):\n super(TestToolApi, self).tearDown()\n\n def test_tool_diff(self):\n reel_name = 'J25nB171'\n reel = self._app.db.reel.find_one({'reel_name': reel_name})\n ori_txt = reel.get('ori_txt')\n txt = '測試,文本,比對' + ori_txt[6:]\n segments = Diff.diff(txt, ori_txt, clear_junk=False)[0]\n html = ReelHandler.segments2html(segments, plain_txt=True)\n self.assertTrue(html)\n","sub_path":"tests/punc/test_punc_api.py","file_name":"test_punc_api.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"560452267","text":"from django.urls import path\nfrom . import views\nfrom .views import Category1List,Category1Detail\n\nurlpatterns =[\n path('', views.apiOverview,name=\"api-overview\"),\n path('categories-list', Category1List.as_view(), name=\"categories-list\"),\n path('categorie-detail//', Category1Detail.as_view(), name=\"categories-detail\"),\n path('expense-list', views.expenseList, name=\"expense-list\"),\n\n path('expense-detail//', views.expenseDetail, name=\"expense-detail\"),\n path('expense-create/', views.expenseCreate, name=\"expense-create\"),\n path('expense-update//', views.expenseUpdate, name=\"expense-update\"),\n path('expense-delete//', views.expenseDelete, name=\"expense-delete\"),\n]\n","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"320408087","text":"\"\"\"\nDescription\n\n快速排序的核心思想是使用元素的值对数组进行划分。实现其非递归方案。\n\n\nInput\n\n输入的每一行表示一个元素为正整数的数组,所有值用空格隔开,第一个值为数值长度,其余为数组元素值。\n\n\nOutput\n\n输出的每一行为排序结果,用空格隔开,末尾不要空格。\n\n\nSample Input 1\n\n13 24 3 56 34 3 78 12 29 49 84 51 9 100\nSample Output 1\n\n3 3 9 12 24 29 34 49 51 56 78 84 100\n\"\"\"\nimport sys\ndef fast_sort(list,left,right):\n if left > right:\n return\n i=left\n j=right\n temp=list[left]\n while i!=j:\n while list[j]>=temp and i 0, or a prior over the log of just the diagonal elements, if `rank` == 0.\n\n \"\"\"\n super(MultitaskGaussianLikelihood, self).__init__()\n\n if rank == 0:\n self.register_parameter(\n name=\"log_task_noises\", parameter=torch.nn.Parameter(torch.zeros(n_tasks)), prior=task_prior\n )\n else:\n self.register_parameter(\n name=\"task_noise_covar_factor\", parameter=torch.nn.Parameter(torch.randn([n_tasks, rank]))\n )\n if task_prior is not None:\n self.register_derived_prior(\n name=\"MultitaskErrorCovariancePrior\",\n prior=task_prior,\n parameter_names=(\"task_noise_covar_factor\", \"log_noise\"),\n transform=_eval_covar_matrix,\n )\n self.n_tasks = n_tasks\n\n def forward(self, input):\n \"\"\"\n Adds the log task noises to the diagonal of the covariance matrix of the supplied\n :obj:`gpytorch.random_variables.GaussianRandomVariable` or\n :obj:`gpytorch.random_variables.MultitaskGaussianRandomVariable`, in case of\n `rank` == 0. Otherwise, adds a rank `rank` covariance matrix to it.\n\n To accomplish this, we form a new :obj:`gpytorch.lazy.KroneckerProductLazyTensor` between :math:`I_{n}`,\n an identity matrix with size equal to the data and a (not necessarily diagonal) matrix containing the task\n noises :math:`D_{t}`.\n\n We also incorporate a shared `log_noise` parameter from the base\n :class:`gpytorch.likelihoods.GaussianLikelihood` that we extend.\n\n The final covariance matrix after this method is then :math:`K + D_{t} \\otimes I_{n} + \\sigma^{2}I_{nt}`.\n\n Args:\n input (:obj:`gpytorch.random_variables.MultitaskGaussianRandomVariable`): Random variable whose covariance\n matrix is a :obj:`gpytorch.lazy.LazyTensor` we intend to augment.\n Returns:\n :obj:`gpytorch.random_variables.MultitaskGaussianRandomVariable`: A new random variable whose covariance\n matrix is a :obj:`gpytorch.lazy.LazyTensor` with :math:`D_{t} \\otimes I_{n}` and :math:`\\sigma^{2}I_{nt}`\n added.\n \"\"\"\n mean, covar = input.representation()\n eye_lv = DiagLazyTensor(torch.ones(covar.size(-1) // self.n_tasks, device=self.log_noise.device))\n if hasattr(self, \"log_task_noises\"):\n task_var_lv = DiagLazyTensor(self.log_task_noises.exp())\n else:\n task_var_lv = RootLazyTensor(self.task_noise_covar_factor)\n covar_kron_lv = KroneckerProductLazyTensor(task_var_lv, eye_lv)\n noise = covar + covar_kron_lv\n noise = add_diag(noise, self.log_noise.exp())\n return input.__class__(mean, noise)\n\n def log_probability(self, input, target):\n raise NotImplementedError(\"Variational inference with Multitask Gaussian likelihood is not yet supported\")\n","sub_path":"gpytorch/likelihoods/multitask_gaussian_likelihood.py","file_name":"multitask_gaussian_likelihood.py","file_ext":"py","file_size_in_byte":4456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"490095473","text":"# https://github.com/WFCD/warframe-status\n# https://docs.warframestat.us\n\nfrom src import config\nfrom src.cogs import (cetus, fissure, invasion, rivens, sortie)\nimport discord\nfrom discord.ext import commands\n\n# Bot setup\nbot = commands.Bot(command_prefix='!')\nbot.remove_command('help')\ntoken = config.DISCORD_TOKEN\ncetus.setup(bot)\nfissure.setup(bot)\ninvasion.setup(bot)\nrivens.setup(bot)\nsortie.setup(bot)\n\n\n@bot.event\nasync def on_ready():\n print('Bot Online!')\n\n\n@bot.event\nasync def on_command_error(ctx, error):\n if isinstance(error, commands.CommandNotFound):\n await ctx.send(\"Invalid command. Enter !help for commands.\")\n\n\n@bot.command()\nasync def help(ctx):\n embed = discord.Embed(title='Command List:')\n embed.add_field(name='!cycle', value='Show status of current Cetus day/night cycle.', inline=False)\n embed.add_field(name='!atcycle ',\n value='Activate alert notification for the next Cetus day/night cycle.\\n'\n ' 1-30 minutes before the next cycle || 5 minute default.',\n inline=False)\n embed.add_field(name='!rmcycle', value='Stop being alerted for the next Cetus day/night cycle.', inline=False)\n embed.add_field(name='!fissures ', value='Show current void fissure missions based on'\n ' .\\n'\n ' Lith, Meso, Neo, or Axi\\n'\n ' Capture, Survival, Extermination,'\n ' Excavation, Defense, Mobile Defense,'\n ' Rescue, Interception, Sabotage, Spy',\n inline=False)\n embed.add_field(name='!atfissures ', value='Activate alert notification for specific '\n 'Void Fissures. \\n '\n , inline=False)\n embed.add_field(name='!rmfissures', value='Stop being alerted for Void Fissures.', inline=False)\n embed.add_field(name='!invasions', value='Show all current Invasions.', inline=False)\n embed.add_field(name='!atinvasions ', value='Activate alert notification for Invasions'\n ' containing \\n to alert for '\n '(ex: \"Strun\" will look for any Strun pieces)', inline=False)\n embed.add_field(name='!rminvasions', value='Stop being alerted for Invasion rewards.', inline=False)\n embed.add_field(name='!sorties', value='Show current sortie missions.', inline=False)\n embed.add_field(name='!riven ', value='Show average prices for a riven. '\n ' riven', inline=False)\n await ctx.send(embed=embed)\n\n\nbot.run(token)\n","sub_path":"src/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"535260269","text":"file = open(\"./test.txt\", \"a+\", 1)\r\nprint(\"file name:\", file.name)\r\nprint(\"file.closed\", file.closed)\r\nprint(\"file.mode\", file.mode)\r\n\r\nfor var in range(1, 10):\r\n file.write(\"this is a test file!\\n\")\r\n\r\nfile.close()\r\n\r\nfile1 = open(\"./test.txt\", \"r+\", 1)\r\nstr = file1.read(10)\r\nprint(\"读取的文件内容:\", str)\r\n\r\nposition = file1.tell()\r\nprint(\"文件当前位置:\", position)\r\n\r\nfile1.seek(0, 0)\r\nstr = file1.read(10)\r\nprint(\"文件重新读取内容:\", str)\r\n","sub_path":"base/io/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"566163137","text":"# CS 61A Spring 2014\n# Name:\n# Login:\n\nfrom ucb import main\n\nletters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',\n 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',\n 'u', 'v', 'w', 'x', 'y', 'z']\nbad_num_letters = \"Wrong number of letters.\"\nnot_a_word = \"Not a valid word.\"\nwin_message = \"Congratulations! You win!\"\n\n\ndef make_word_from_string(s):\n \"\"\"Creates an instance of the word ADT from the string s.\n \"\"\"\n lst_2=[]\n for i in range(len(s)):\n lst_2=lst_2+[s[i]]\n return [s,lst_2]\n\ndef make_word_from_list(lst):\n \"\"\"Creates an instance of the word ADT from the list of characters lst.\n \"\"\"\n string=''\n for i in range(len(lst)):\n string=string+lst[i]\n return [string,lst]\n\ndef get_string(word):\n \"\"\"Returns the string representation of word.\n \n >>> get_string(make_word_from_string('hello'))\n 'hello'\n >>> get_string(make_word_from_list(['w', 'o', 'r', 'l', 'd']))\n 'world'\n \"\"\"\n return word[0]\n\ndef get_list(word):\n \"\"\"Returns the list of characters representation of word.\n \n >>> get_list(make_word_from_string('hello'))\n ['h', 'e', 'l', 'l', 'o']\n >>> get_list(make_word_from_list(['w', 'o', 'r', 'l', 'd']))\n ['w', 'o', 'r', 'l', 'd']\n \"\"\"\n return word[1]\n\n\n\ndef num_common_letters(goal_word, guess):\n \"\"\"Returns the number of letters in goal_word that are also in guess.\n As per the rules of the game, goal_word cannot have any repeated\n letters, but guess is allowed to have repeated letters.\n goal_word and guess are assumed to be of the same length.\n goal_word and guess are both instances of the word ADT.\n\n >>> mwfs, mwfl = make_word_from_string, make_word_from_list\n >>> num_common_letters(mwfs('steal'), mwfs('least'))\n 5\n >>> num_common_letters(mwfs('steal'), mwfl(['s', 't', 'e', 'e', 'l']))\n 4\n >>> num_common_letters(mwfl(['s', 't', 'e', 'a', 'l']), mwfs('thief'))\n 2\n >>> num_common_letters(mwfl(['c', 'a', 'r']), mwfl(['p', 'e', 't']))\n 0\n \"\"\"\n#Get Length of word\n length=len(get_string(goal_word))\n \n #Letters I've Seen\n letters_seen=[]\n for el in letters:\n for i in range(length):\n if el in get_string(guess)[i] and el not in letters_seen:\n letters_seen=letters_seen+[get_string(guess)[i]]\n \n num=0\n for i in range(len(letters_seen)):\n if letters_seen[i] in get_string(goal_word):\n num+=1\n else:\n num=num\n\n return num\n\n # #counter\n # num=0\n # for el in letters:\n # for i in range(length): #checks each letter \n # for j in range(length): #checks if any letter in goal/guess is the same\n # if get_list(goal_word)[i]==el and get_list(guess)[j]==el: #Does not check repeated case\n # num +=1\n\n # return num\n\n\ndef make_word_master(goal_word):\n \"\"\"Takes in the word to be guessed and returns a function which\n takes in a guess and does what the word master does, that is:\n If the guess is of incorrect length, it returns bad_num_letters.\n If the guess is correct, it returns win_message\n Otherwise, it returns the number of letters in common.\n\n >>> mwfs = make_word_from_string\n >>> foo = make_word_master(mwfs('least'))\n >>> foo(mwfs('water'))\n 3\n >>> foo(mwfs('player')) == bad_num_letters\n True\n >>> foo(mwfs('steel'))\n 4\n >>> foo(mwfs('steal'))\n 5\n >>> foo(mwfs('aaaaa')) == not_a_word\n True\n >>> foo(mwfs('least')) == win_message\n True\n \"\"\"\n def len_check(s):\n if len(get_string(goal_word)) != len(get_string(s)):\n return bad_num_letters\n elif is_valid_guess(s)==False:\n return not_a_word\n elif get_string(goal_word)==get_string(s):\n return win_message\n else:\n return num_common_letters(goal_word, s)\n return len_check\n\n\n\ndef subsets(lst, n):\n \"\"\"Returns all subsets of lst of size exactly n in any order.\n lst is a Python list, and n is a non-negative integer.\n\n >>> three_subsets = subsets(list(range(5)), 3)\n >>> three_subsets.sort() # Uses syntax we don't know yet to sort the list.\n >>> for subset in three_subsets:\n ... print(subset)\n [0, 1, 2]\n [0, 1, 3]\n [0, 1, 4]\n [0, 2, 3]\n [0, 2, 4]\n [0, 3, 4]\n [1, 2, 3]\n [1, 2, 4]\n [1, 3, 4]\n [2, 3, 4]\n \"\"\"\n # n is the size of the sublist\n # lst is the numbers in which you can choose from\n\n #Help from Andrews extra lecture\n #subset([],4)-->[]\n #subset([1,2,3],0)-->[[]]\n #subset([],0)--> [[]]\n\n #lst-->[1,2,3]\n #n-->2\n\n #first,rest=lst[0],lst[1:]\n #n-=1\n\n #subset(rest,n)-->[[2,3]] #without first\n #subset(rest,n-1)-->[[2][3]] #with one\n #insert 1 ----> [[1,2], [1,3]]\n\n #most important\n if n==0:\n return [[]]\n if lst==[]:\n return []\n elif n==1:\n return [ [x] for x in lst ] #if n==1, return 0,1,2,3,4\n elif n==len(lst):\n return [lst]\n else:\n return subsets(lst[1:], n) + [ [lst[0]] + x for x in subsets(lst[1:], n-1) ]\n\n #So much help from the GSI\n\n\n\ndef compatible(guess, score, letter_list):\n \"\"\"Returns True if it is possible for the word to get the score,\n assuming that the true word only contains letters from\n letter_list.\n Precondition: len(word) == len(letter_list)\n\n >>> mwfs = make_word_from_string\n >>> compatible(mwfs('steal'), 5, ['l', 'e', 'a', 's', 't'])\n True\n >>> compatible(mwfs('blanket'), 6, ['a', 'b', 'e', 'l', 'n', 'r', 't'])\n True\n >>> compatible(mwfs('cool'), 4, ['c', 'o', 'l', 'd'])\n False\n >>> \n False\n \"\"\"\n if num_common_letters(guess,make_word_from_string(letter_list))==score:\n return True\n else:\n return False\n\n\n\ndef filter_subsets(word, score, possible_subsets):\n \"\"\"Returns the subsets for which word would get the given score.\n\n >>> word = make_word_from_string('steal')\n >>> sub1 = ['a', 'b', 'e', 'l', 's']\n >>> sub2 = ['b', 'e', 'l', 't', 'z']\n >>> sub3 = ['s', 't', 'e', 'a', 'l']\n >>> sub4 = ['b', 'l', 'e', 's', 't']\n >>> filter_subsets(word, 4, [sub1, sub2, sub3, sub4])\n [['a', 'b', 'e', 'l', 's'], ['b', 'l', 'e', 's', 't']]\n \"\"\"\n solutions=[]\n for subset in possible_subsets:\n if num_common_letters(word,make_word_from_string(subset))==score:\n solutions=solutions+[subset]\n return solutions\n\n\n\ndef make_deductions(possible_subsets, letters):\n \"\"\"Infers which letters must be in the word to be guessed, and\n which letters must not be in the word.\n A letter must be in the word if it is in every possible subset.\n A letter is not in the word if it is not in any possible subset.\n\n >>> letters = ['a', 'b', 'c', 'd', 'e', 'f']\n >>> subsets = [['a', 'b', 'c'], ['b', 'a', 'e'], ['e', 'a', 'c']]\n >>> present, not_present = make_deductions(subsets, letters)\n >>> present\n ['a']\n >>> not_present\n ['d', 'f']\n \"\"\"\n present = []\n not_present = []\n counter=0\n \n for el in letters:\n for i in range(len(possible_subsets)):\n if el in possible_subsets[i]:\n counter+=1\n if counter==len(possible_subsets):\n present+=[el]\n counter=0\n elif counter==0:\n not_present+=[el]\n counter=0\n else:\n counter=0\n return present, not_present\n\n\n\n # for element in letters: #Checks all the letters\n # for subset in subsets: #Checks all the subsets in the subset\n # for j in range(len(subsets)): #Checks all subsets\n # for i in range(len(subsets[1])): #Checks all subelements\n # if element is subsets[j][i]: #if the element is in the subset with element\n # counter+=1\n # if counter==len(subsets): #If it is in all subsets\n # counter=0\n # present+=[element]\n # else:\n # counter=0\n\n # for j in range(len(subsets)):\n # for i in range(len(subsets)):\n # if element is subsets[j][i]:\n # counter+=1\n # if counter==0:\n # not_present+=[element]\n # counter=0\n # else:\n # counter=0\n # return present, not_present\n\n\n\n\n\n # for elements in letters:\n # for subset in subsets:\n # if elements not in subset:\n # for index in range(len(subsets)):\n # if elements in subsets[index]\n # not_present+=[elements]\n # else:\n # for index in range(len(subsets)):\n # if elements in subsets[index]:\n # counter+=1\n # if counter==len(subsets):\n # present+=[elements]\n\n\ndef print_deductions(possible_subsets):\n present, not_present = make_deductions(possible_subsets, letters)\n if present:\n print('The following letters must be present:', present)\n if not_present:\n print('The following letters must not be present:', not_present)\n if present == [] and not_present == []:\n print('No deductions can be made at this time. Try some more words.')\n\nimport random\n\nwords = open('validguesses.txt', 'r')\nguesser_words = [word.strip() for word in words]\nmaster_words = [word for word in guesser_words if len(word) == len(set(word))]\n\ndef is_valid_guess(word):\n \"\"\"Returns True if word is a valid word that can be guessed.\n \"\"\"\n return get_string(word) in guesser_words\n\ndef is_valid_goal_word(word):\n \"\"\"Returns True if word is a valid goal word.\n Similar to is_valid_guess, but must also not have repetitions.\n \"\"\"\n return get_string(word) in master_words\n\ndef choose_random_word():\n return make_word_from_string(random.choice(master_words))\n\nimport sys\n\n@main\ndef play_game(word=\"\"):\n \"\"\"\n Call this function with no arguments to play with a random word,\n or a word between 4 and 7 letters to play with your own word.\n \"\"\"\n if not word:\n word = choose_random_word()\n elif not is_valid_goal_word(word):\n return not_a_word\n print('Playing with a', len(get_string(word)), 'letter word.')\n word_master = make_word_master(word)\n possible_subsets = subsets(letters, len(get_string(word)))\n result = ''\n while result != win_message:\n print('Enter a word to get its score, h for a hint, or q to quit.')\n next_string = sys.stdin.readline().strip().lower()\n if next_string == 'q':\n print('The word was', get_string(word))\n return\n\n if next_string == 'h':\n print_deductions(possible_subsets)\n else:\n guess = make_word_from_string(next_string)\n result = word_master(guess)\n if type(result) == type(''):\n print(result)\n else:\n possible_subsets = filter_subsets(guess, result, possible_subsets)\n print('The word', next_string, 'has', result, 'letters in common')\n\n\n","sub_path":"all_data/cs61a/untarred2/44.py","file_name":"44.py","file_ext":"py","file_size_in_byte":11122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"478577251","text":"import json\n\n#Script written by Kang Breder\n#This script outputs a string on the console.\n\nfirstName = \"[Kang]\"\nlastName = \"[Breder]\"\ninternshipId = \"[HNG-03939]\"\nlanguage = \"[Python]\"\nemail = \"kangbreder@gmail.com\"\n\nprint(\"Hello World, this is % s % s with HNGi7 ID % s using % s for stage 2 task. % s\" \n% (firstName, lastName, internshipId, language, email))","sub_path":"testScripts/kangbreder.py","file_name":"kangbreder.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"74664506","text":"from torch import nn\nfrom torch.nn import init\nimport numpy as np\n\n\nclass RNDModel(nn.Module):\n def __init__(self, input_size, output_size):\n super(RNDModel, self).__init__()\n\n self.input_size = input_size\n self.output_size = output_size\n self.predictor = nn.Sequential(\n nn.Linear(self.input_size[0], 32),\n nn.Sigmoid(),\n nn.Linear(32, 32),\n nn.ReLU(),\n nn.Linear(32, self.output_size[0])\n )\n\n self.target = nn.Sequential(\n nn.Linear(self.input_size[0], 32),\n nn.Sigmoid(),\n nn.Linear(32, 32),\n nn.ReLU(),\n nn.Linear(32, self.output_size[0])\n )\n for p in self.modules():\n if isinstance(p, nn.Conv2d):\n init.orthogonal_(p.weight, np.sqrt(2))\n p.bias.data.zero_()\n\n if isinstance(p, nn.Linear):\n init.orthogonal_(p.weight, np.sqrt(2))\n p.bias.data.zero_()\n\n for param in self.target.parameters():\n param.requires_grad = False\n\n def forward(self, next_obs):\n target_feature = self.target(next_obs)\n predict_feature = self.predictor(next_obs)\n\n return predict_feature, target_feature\n","sub_path":"rnd.py","file_name":"rnd.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"2704225","text":"import pygame as pg\n\nfrom .player import Player\n\nclass EntityGroup(pg.sprite.Group):\n def __init__(self):\n super().__init__()\n self.renderables = []\n\n def getProximityObjects(self,target,proximity):\n # Returns a list of proximity objects EXCEPT the target object\n sprites = self.renderables\n return tuple(spr for spr in sprites if proximity.colliderect(spr.rect) and spr != target)\n\n def update(self,world,dt):\n # Adds objects into fov if they are collidables\n for spr in self.renderables:\n proximity = pg.Rect(spr.rect.x - 32, spr.rect.y, 128, 128)\n spr.fov = self.getProximityObjects(spr,proximity) + tuple(world.getCollidableTiles(proximity))\n spr.update(dt)\n\n\n def draw(self,surface,camera):\n '''\n\n :param surface: pygame.Surface\n :param camera: camera object\n :return: None\n\n draws the sprite based on camera position using:\n sprite position[x,y] - camera_position[x,y]\n\n '''\n\n sprites = self.sprites()\n surface_blit = surface.blit\n\n # Sorts renderables by y position in ascending order\n self.renderables = sorted([spr for spr in sprites if camera.isVisible(spr.rect.center) or isinstance(spr, Player)], key = lambda spr: spr.rect.bottom)\n\n for spr in self.renderables:\n # Draws sprite\n self.spritedict[spr] = surface_blit(spr.image, camera.apply(spr))\n spr.draw(surface,camera)\n\n self.lostsprites = []\n","sub_path":"gameobject/objectgroup.py","file_name":"objectgroup.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"178460861","text":"# https://leetcode.com/submissions/detail/155003210/\nclass Solution(object):\n # @return an integer\n def solveNQueens(self, n):\n \"\"\"\n :type n: int\n :rtype: List[List[str]]\n \"\"\"\n def dfs(curr, cols, main_diag, anti_diag, result):\n row, n = len(curr), len(cols)\n if row == n:\n result.append(map(lambda x: '.'*x + \"Q\" + '.'*(n-x-1), curr))\n return\n for i in xrange(n):\n if cols[i] or main_diag[row+i] or anti_diag[row-i+n]:\n continue\n cols[i] = main_diag[row+i] = anti_diag[row-i+n] = True\n curr.append(i)\n dfs(curr, cols, main_diag, anti_diag, result)\n curr.pop()\n cols[i] = main_diag[row+i] = anti_diag[row-i+n] = False\n \n cols = [False]* n\n main_diag = [False]*(2*n)\n anti_diag = [False]*(2*n)\n result = []\n dfs([], cols, main_diag, anti_diag, result)\n return result\n\"\"\"\nShiity one\n\"\"\"\nclass Solution(object):\n def solveNQueens(self, n):\n \"\"\"\n :type n: int\n :rtype: List[List[str]]\n \"\"\"\n res = []\n possible_combo = []\n col = list(range(n))\n for combo in itertools.permutations(col):\n if(n == len(list(set(combo[i] + i for i in range(n)))) == \n len(list(set(combo[i] - i for i in range(n))))):\n # possible_combo.append(combo)\n one_res = []\n for pos in combo:\n init = ['.'] * n\n init[pos] = 'Q'\n one_res.append(''.join(init))\n res.append(one_res)\n return res\n \n","sub_path":"priori_to_2021/nQueensWithGraph.py","file_name":"nQueensWithGraph.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"159168315","text":"import sys\nimport os\nsys.path.append(os.path.dirname(os.path.dirname(__file__)))\n\nfrom flask import request, jsonify\nfrom eve import Eve\nfrom eve.auth import TokenAuth\n\nfrom login import login\n\n\nclass TokenAuth(TokenAuth):\n\n def check_auth(self, token, allowed_roles, resource, method):\n accounts = app.data.driver.db['accounts']\n token = request.cookies.get('token')\n if token:\n return accounts.find_one({'token': token})\n return False\n\napp = Eve(settings='app_settings.py')\n\n\n@app.route('%s/login' % app.api_prefix, methods=['GET', 'POST'])\ndef url_login(*args):\n try:\n token = login(request, app)\n except Exception as e:\n token = \"\"\n response = jsonify(token=token)\n response.headers.add('Access-Control-Allow-Origin', '*')\n if token:\n response.set_cookie('token', value=token)\n else:\n response.set_cookie('token', '', expires=0)\n return response\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n","sub_path":"auth/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"423337462","text":"from activity.model_manager import *\nfrom utils.model_manager import *\nfrom friend.model_manager import *\nfrom general_notice.model_manager import *\nfrom verify.model_manager import *\nfrom utils.utils import *\nfrom utils.model_utils import *\n\n\nTEST_ACCOUNT1 = '18299991111'\nTEST_ACCOUNT2 = '18299991112'\nTEST_ACCOUNT3 = '18299991113'\nTEST_ACCOUNT4 = '18299991114'\nTEST_PASSWORD = 'locate123'\nTEST_AVATAR_URL = 'www.bananachocalatemilk.com/static/default.jpg'\nTEST_NICKNAME = 'test_account'\nTEST_TOKEN = 'c8e582ba3f783681b1a47641a62c6fc8'\nTEST_TOKEN2 = 'c8e582ba3f783681b1a47641a62c6fc7'\nTEST_TOKEN3 = 'c8e582ba3f783681b1a47641a62c6fc6'\nTEST_TOKEN4 = 'c8e582ba3f783681b1a47641a62c6fc5'\nTEST_LATITUDE = 119.01\nTEST_LONGITUDE = 119.11\nTEST_HEADING = 100.1\nTEST_SPEED = 60.23\nTEST_ACTIVITY_ID = 170209\nTEST_ACTIVITY_NAME = 'test_name'\nTEST_DEFAULT_ACTIVITY_NAME = 'Travel'\nTEST_DESTINATION = 'Los Angles'\nTEST_DESTINATION2 = 'New York'\n\n\ndef create_two_users():\n create_user(TEST_ACCOUNT1, TEST_TOKEN)\n create_user(TEST_ACCOUNT2, TEST_TOKEN2)\n\n\ndef create_user(account=TEST_ACCOUNT1, token=TEST_TOKEN):\n return UserManager().create(account=account,\n password=TEST_PASSWORD,\n nickname=TEST_NICKNAME,\n avatar_url=TEST_AVATAR_URL,\n token=token,\n position_list='[{\"latitude\":99.01, \"longitude\":99.11, \"heading\": 100.01, \"speed\": 60.0},{\"latitude\":100.01, \"longitude\":100.11, \"heading\": 100.11, \"speed\": 50.0}]')\n\n\ndef create_activity(creator):\n activity = ActivityManager().create(members=to_json([creator.get(DB_ID)]),\n administrator=creator.get(DB_ID),\n name=TEST_DEFAULT_ACTIVITY_NAME,\n activity_id=TEST_ACTIVITY_ID)\n UserManager().set({ACTIVITY_ID: TEST_ACTIVITY_ID}, id=creator.get(DB_ID))\n return activity\n\n\ndef get_activity():\n return ActivityManager().filter(activity_id=TEST_ACTIVITY_ID)[0]\n\n\ndef create_activity_with_two_users():\n user1 = get_user_by_token(TEST_TOKEN)\n user2 = get_user_by_token(TEST_TOKEN2)\n activity = ActivityManager().create(members=to_json([user1.get(DB_ID), user2.get(DB_ID)]),\n administrator=user1.get(DB_ID),\n name=TEST_DEFAULT_ACTIVITY_NAME,\n leader=user1.get(DB_ID),\n activity_id=TEST_ACTIVITY_ID)\n user = get_user_by_token(TEST_TOKEN)\n user2 = get_user_by_token(TEST_TOKEN2)\n manager = UserManager()\n manager.set({ACTIVITY_ID: TEST_ACTIVITY_ID}, id=user.get(DB_ID))\n manager.set({ACTIVITY_ID: TEST_ACTIVITY_ID}, id=user2.get(DB_ID))\n return activity\n\n\ndef print_split_line():\n print('>>>>>>>>>>>>>>>>>>>>>>>>>>')\n\n\ndef clear_database():\n ActivityManager().delete_all()\n UserManager().delete_all()\n InviteActivityRequestManager().delete_all()\n JoinActivityRequestManager().delete_all()\n FriendCoupleManager().delete_all()\n FriendNoticeManager().delete_all()\n VerifiedUserManager().delete_all()\n","sub_path":"src/Server/utils/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"212753589","text":"from pandas import DataFrame, read_csv;\n\nimport numpy as np;\nimport pandas as pd;\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\ncar_prices = pd.read_csv('CarPrice_Assignment.csv')\n\n#############derive the company name##############\n\ncar_prices[\"company_name\"] = car_prices.CarName.str.split(\" \").str.get(0)\n\n#### Rename the cars which does not have proper names\ncar_prices.loc[car_prices[\"company_name\"] == \"toyouta\", \"company_name\"] = \"toyota\"\ncar_prices.loc[car_prices[\"company_name\"] == \"porcshce\", \"company_name\"] = \"porsche\"\ncar_prices.loc[car_prices[\"company_name\"] == \"vokswagen\", \"company_name\"] = \"volkswagen\"\ncar_prices.loc[car_prices[\"company_name\"] == \"vw\", \"company_name\"] = \"volkswagen\"\ncar_prices.loc[car_prices[\"company_name\"] == \"maxda\", \"company_name\"] = \"mazda\"\ncar_prices.loc[car_prices[\"enginetype\"] == \"dohcv\", \"enginetype\"] = \"dohc\"\n\n\ncar_prices[\"company_name\"] = car_prices[\"company_name\"].str.upper();\n\n###########binary categorical variables\ncar_prices['fueltype'] = car_prices['fueltype'].map({'gas': 1, 'diesel': 0})\ncar_prices['aspiration'] = car_prices['aspiration'].map({'std': 1, 'turbo': 0})\ncar_prices['doornumber'] = car_prices['doornumber'].map({'two': 2, 'four': 4})\ncar_prices['enginelocation'] = car_prices['enginelocation'].map({'front': 1, 'rear': 0})\n\n\n#######create dummy variable for carbody column ##########\n\n## If all are zero, then it means that its convertible\ncar_body_dummies = pd.get_dummies(car_prices['carbody'], drop_first=True)\ncar_prices = pd.concat([car_prices,car_body_dummies],axis=1)\ncar_prices.drop(['carbody'],axis=1,inplace=True)\n\n\n#######create dummy variable for drivewheel column ##########\n\n## If all are zero, then it means that its 4wd\ncar_drive_wheels = pd.get_dummies(car_prices['drivewheel'], drop_first=True)\ncar_prices = pd.concat([car_prices,car_drive_wheels],axis=1)\ncar_prices.drop(['drivewheel'],axis=1,inplace=True)\n\n\n#######create dummy variable for enginetype column ##########\n\n## If all are zero, then it means that its dohc\ncar_enginetypes = pd.get_dummies(car_prices['enginetype'], drop_first=True)\ncar_prices = pd.concat([car_prices,car_enginetypes],axis=1)\ncar_prices.drop(['enginetype'],axis=1,inplace=True)\n\n\n#######create dummy variable for cylindernumber column ##########\n\n## If all are zero, then it means that its eight\ncar_cylindernumber = pd.get_dummies(car_prices['cylindernumber'], drop_first=True)\ncar_prices = pd.concat([car_prices,car_cylindernumber],axis=1)\ncar_prices.drop(['cylindernumber'],axis=1,inplace=True)\n\n\n#######create dummy variable for fuelsystem column ##########\n\n## If all are zero, then it means that its 1bbl\ncar_fuelsystem = pd.get_dummies(car_prices['fuelsystem'], drop_first=True)\ncar_prices = pd.concat([car_prices,car_fuelsystem] ,axis=1)\ncar_prices.drop(['fuelsystem'],axis=1,inplace=True)\n\n#######create dummy variable for company_name column ##########\n\n## If all are zero, then it means that its ALFA-ROMERO\ncar_company_name = pd.get_dummies(car_prices['company_name'], drop_first=True)\ncar_prices = pd.concat([car_prices,car_company_name] ,axis=1)\ncar_prices.drop(['company_name'],axis=1,inplace=True)\n\n\ncar_prices.drop(['car_ID'],axis=1,inplace=True)\ncar_prices.drop(['CarName'],axis=1,inplace=True)\n\nprint(car_prices.head())\n\ndef normalize (x):\n return ((x-np.mean(x))/(max(x) - min(x)))\n\ncar_prices = car_prices.apply(normalize)\n\ny = car_prices['price']\n\nX = car_prices[['symboling', 'fueltype', 'aspiration', 'doornumber', 'enginelocation', 'wheelbase', 'carlength', 'carwidth',\n 'carheight', 'curbweight', 'enginesize', 'boreratio', 'stroke', 'compressionratio', 'horsepower', 'peakrpm', 'citympg',\n 'highwaympg', 'hardtop', 'hatchback', 'sedan', 'wagon', 'fwd', 'rwd', 'l', 'ohc', 'ohcf', 'ohcv', 'rotor', 'five',\n 'four', 'six', 'three', 'twelve', 'two', '2bbl', '4bbl', 'idi','mfi', 'mpfi', 'spdi', 'spfi', 'AUDI', 'BMW', 'BUICK',\n 'CHEVROLET', 'DODGE', 'HONDA', 'ISUZU', 'JAGUAR', 'MAZDA','MERCURY', 'MITSUBISHI', 'NISSAN', 'PEUGEOT', 'PLYMOUTH',\n 'PORSCHE', 'RENAULT', 'SAAB', 'SUBARU', 'TOYOTA', 'VOLKSWAGEN','VOLVO']]\n\nprint(X.head())\n\n\n#random_state is the seed used by the random number generator, it can be any integer.\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7 ,test_size = 0.3, random_state=100)\n\n\nfrom sklearn.feature_selection import RFE\nfrom sklearn.linear_model import LinearRegression\nlm = LinearRegression()\nrfe = RFE(lm, 15)\nrfe = rfe.fit(X_train, y_train)\nprint(rfe.support_)\nprint(rfe.ranking_)\n\nprint(X_train.columns[rfe.support_])\ncol = X_train.columns[rfe.support_]\nX_train_rfe = X_train[col]\n\n#function for calculating VIF\ndef vif_cal(input_data, dependent_col):\n vif_df = pd.DataFrame( columns = ['Var', 'Vif'])\n x_vars=input_data.drop([dependent_col], axis=1)\n xvar_names=x_vars.columns\n for i in range(0,xvar_names.shape[0]):\n y=x_vars[xvar_names[i]]\n x=x_vars[xvar_names.drop(xvar_names[i])]\n rsq=sm.OLS(y,x).fit().rsquared\n vif=round(1/(1-rsq),2)\n vif_df.loc[i] = [xvar_names[i], vif]\n return vif_df.sort_values(by = 'Vif', axis=0, ascending=False, inplace=False)\n\n\n## Basically here I have copy-pasted columns from rfe.support_ variable\nfinal_car_prices = car_prices[['enginelocation', 'carwidth', 'curbweight', 'enginesize',\n 'boreratio', 'stroke', 'rotor', 'five', 'four', 'three',\n 'twelve', 'two', 'BMW', 'PEUGEOT', 'PORSCHE', 'price']]\n\n\n# plt.figure(figsize = (16,10)) # Size of the figure\n# sns.heatmap(final_car_prices.corr(), annot = True)\n\nimport statsmodels.api as sm\n\n###########################Model 1#################\nX_train_rfe = sm.add_constant(X_train_rfe)\n\nlm1 = sm.OLS(y_train, X_train_rfe).fit()\n\nprint(lm1.summary())\n\nprint(vif_cal(input_data=final_car_prices, dependent_col=\"price\"))\n\n\n\n###########################Model 2 ################\nX_train_rfe = X_train_rfe.drop('rotor', 1)\n\nlm2 = sm.OLS(y_train, X_train_rfe).fit()\n\nprint(lm2.summary())\n\nprint(vif_cal(input_data=final_car_prices.drop([\"rotor\"], axis=1), dependent_col=\"price\"))\n\n\n###########################Model 3 ################\nX_train_rfe = X_train_rfe.drop('enginesize', 1)\n\nlm3= sm.OLS(y_train, X_train_rfe).fit()\n\nprint(lm3.summary())\n\nprint(vif_cal(input_data=final_car_prices.drop([\"enginesize\", \"rotor\"], axis=1), dependent_col=\"price\"))\n\n# ###########################Model 4 ################\nX_train_rfe = X_train_rfe.drop('four', 1)\n\nlm4= sm.OLS(y_train, X_train_rfe).fit()\n\nprint(lm4.summary())\n\nprint(vif_cal(input_data=final_car_prices.drop([\"enginesize\", \"four\", \"rotor\"], axis=1), dependent_col=\"price\"))\n\n# ###########################Model 5 ################\nX_train_rfe = X_train_rfe.drop(['five'], axis=1)\n\nlm5= sm.OLS(y_train, X_train_rfe).fit()\n\nprint(lm5.summary())\n\nprint(vif_cal(input_data=final_car_prices.drop([\"enginesize\", \"four\", \"rotor\", \"five\"], axis=1), dependent_col=\"price\"))\n\n\n# ###########################Model 6 ################\nX_train_rfe = X_train_rfe.drop('stroke', 1)\n\nlm6= sm.OLS(y_train, X_train_rfe).fit()\n\nprint(lm6.summary())\n\nprint(vif_cal(input_data=final_car_prices.drop([\"enginesize\", \"four\", \"rotor\", \"five\", \"stroke\"], axis=1), dependent_col=\"price\"))\n\n# ###########################Model 7 ################\nX_train_rfe = X_train_rfe.drop('two', 1)\n\nlm7= sm.OLS(y_train, X_train_rfe).fit()\n\nprint(lm7.summary())\n\nprint(vif_cal(input_data=final_car_prices.drop([\"enginesize\", \"four\", \"rotor\", \"carwidth\", \"boreratio\", \"stroke\", \"two\"], axis=1), dependent_col=\"price\"))","sub_path":"linear_regression_back.py","file_name":"linear_regression_back.py","file_ext":"py","file_size_in_byte":7565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"297440129","text":"import re\r\nimport argparse\r\nfrom datetime import datetime\r\n\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n\r\ndef get_number_of_pages():\r\n r = requests.get(f\"https://fabtcg.com/decklists/?page=1\")\r\n soup = BeautifulSoup(r.text, 'html.parser')\r\n last = int(soup.findAll(\"a\", {\"class\": \"page-link starling\"})[-1]['href'].partition(\"=\")[-1])\r\n return last\r\n\r\n\r\ndef get_page(page):\r\n r = requests.get(f\"https://fabtcg.com/decklists/?page={page}\")\r\n soup = BeautifulSoup(r.text, 'html.parser')\r\n \r\n df = pd.read_html(f\"https://fabtcg.com/decklists/?page={page}\", flavor='bs4')[0]\r\n \r\n table = soup.find('table')\r\n links = {}\r\n for tr in table.findAll(\"tr\"):\r\n trs = tr.findAll(\"td\")\r\n for each in trs:\r\n try:\r\n a_text = re.sub('\\s+',' ', each.find('a').contents[0])\r\n a_link = each.find('a')['href']\r\n links[a_text] = a_link\r\n except:\r\n pass\r\n\r\n def fetch_deck_url(row):\r\n try:\r\n deck = links[row['Decklist']]\r\n except:\r\n deck = None\r\n\r\n return deck\r\n\r\n def fetch_event_url(row):\r\n try:\r\n event = links[row['Event']]\r\n except:\r\n event = None\r\n\r\n return event\r\n \r\n df['deck_link'] = df.apply(fetch_deck_url, axis=1)\r\n df['event_link'] = df.apply(fetch_event_url, axis=1)\r\n df['Date'] = pd.to_datetime(df['Date'])\r\n \r\n return df\r\n\r\ndef get_all_pages():\r\n dfs = []\r\n for i in range(1, get_number_of_pages()):\r\n dfs.append(get_page(i))\r\n \r\n return pd.concat(dfs).reset_index(drop=True)\r\n\r\n\r\n\r\nreleases = {\r\n 'CRU': ('2020-08-28', datetime.now().strftime(\"%Y-%m-%d\")),\r\n 'ARC': ('2020-03-27', '2020-08-28'),\r\n 'WTR': ('1970-01-01', '2020-03-27'),\r\n 'ALL': ('1970-01-01', datetime.now().strftime(\"%Y-%m-%d\")),\r\n}\r\n\r\n\r\ndef get_meta(df, date_tuple, tournament_format):\r\n return df[\r\n (df['Format'] == tournament_format) \r\n & (df['Date'] >= date_tuple[0])\r\n & (df['Date'] < date_tuple[1])\r\n ]\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--card-db', '-c', help='File path to card csv')\r\n parser.add_argument('--release', '-r', help='Identifier string of set. E.g. WTR, ARC, ALL.')\r\n parser.add_argument('--output', '-o', help='Path to output file.')\r\n\r\n args = parser.parse_args()\r\n \r\n df = get_all_pages()\r\n card_df = pd.read_csv(args.card_db).drop(['image', 'resource', 'name'], axis=1)\r\n meta_df = get_meta(df, date_tuple=releases[args.release], tournament_format=\"CC\")\r\n meta_df.to_csv(args.output, index=False)","sub_path":"fab_meta/scripts/tournament_scraper.py","file_name":"tournament_scraper.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"388493142","text":"fruit = {\n \"Orange\":\"Orange juicy citrus fruit\",\n \"Apple\":\"Red juicy friend\",\n \"Lemon\":\"Sour citrus fruit\",\n \"Lime\":\"Green sour fruit\"\n }\n\n# print(fruit.items())\nf_tuple = tuple(fruit.items())\n# print(f_tuple)\n\nfor snack in f_tuple:\n item, description = snack\n print(item + \" is \" + description)\n \nprint(dict(f_tuple))\nordered_key = list(fruit.keys())\nordered_key.sort()\nfor f in ordered_key:\n print(f + \" - \" + fruit[f])\n\nordered_key = sorted(list(fruit.keys()))\nfor f in ordered_key:\n print(f + \" - \" + fruit[f])\n\nfor f in sorted(fruit.keys()):\n print(f + \" - \" + fruit[f])\n\nfor val in fruit.values():\n print(val)\n\nprint('-' * 40)\nfor i in range(10):\n for snack in fruit:\n print(snack + \" is \" + fruit[snack])\n print('-' * 40 )\n\nwhile True:\n dict_keys = input(\"Please enter a fruit: \")\n if dict_keys == \"quit\":\n break\n if dict_keys in fruit:\n description = fruit.get(dict_keys)\n print(description)\n else:\n print(\"We don't have a \" + dict_keys)\n\nprint(fruit)\nprint(fruit[\"Lemon\"])\nfruit[\"Pair\"] = \"An odd shaped apple that is green\"\nprint(fruit)\ndel fruit[\"Lemon\"]\nprint(fruit)\nfruit.clear()\nprint(fruit)","sub_path":"2021/Code/Python/UDEMY/pythonMasterclass/dictionaryPractice.py","file_name":"dictionaryPractice.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"470685038","text":"import datetime\nfrom core.ops import github, events, issues\n\n\ndef collect():\n events_in_progress = events.list_currently_in_progress()\n\n for event in events_in_progress:\n for team in event.teams:\n for user in team.users:\n github_issues = github.get_issues(user.github_token, event.start)\n for gi in github_issues:\n issues.create(gi[\"html_url\"], gi[\"number\"],\n gi[\"title\"], gi[\"assignee\"][\"login\"],\n _parse_datetime(gi[\"closed_at\"]), _parse_labels(gi[\"labels\"]), team, event,\n _parse_datetime(gi[\"created_at\"]), _parse_datetime(gi[\"updated_at\"]))\n\n\ndef _parse_labels(labels):\n if len(labels) == 0:\n return []\n\n label_list = [l[\"name\"] for l in labels]\n\n return label_list\n\n\ndef _parse_datetime(dt):\n return datetime.datetime.strptime(dt, github.github_date_format)","sub_path":"core/tasks/issue_collector.py","file_name":"issue_collector.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"300368367","text":"import tensorflow as tf \nimport pandas as pd \nimport numpy as np \nfrom hdfs3 import HDFileSystem\nimport matplotlib as plt\nfrom tensorflow import keras\nimport sklearn\n\nhdfs = HDFileSystem(\"localhost\", port=9000)\nwith hdfs.open(\"/user/lojze/input/california_housing_train.csv\") as f:\n df_train = pd.read_csv(f)\n\nwith hdfs.open(\"/user/lojze/input/california_housing_test.csv\") as f:\n df_test = pd.read_csv(f)\n\ndf_train = df_train.reindex(np.random.permutation(df_train.index))\ndf_train = sklearn.utils.shuffle(df_train)\n\ndf_test = df_test.reindex(np.random.permutation(df_test.index))\ndf_test = sklearn.utils.shuffle(df_test).drop_duplicates()\n\ndf_val = df_train.tail(2000).drop_duplicates()\ndf_train = df_train.head(15000).drop_duplicates()\n\ndef get_features(df):\n features = df[[\n 'longitude',\n 'latitude',\n 'housing_median_age',\n 'total_rooms',\n 'total_bedrooms',\n 'population',\n 'households',\n 'median_income']]\n features['rooms_per_person'] = features['total_rooms']/features['population']\n return features\n\ndef get_target(df):\n target = pd.DataFrame()\n target['median_house_value'] = df['median_house_value']/10000.0\n return target\n\ndef get_dataset(features, target, batch_size):\n features = features.values\n features = np.reshape(features, (features.shape[0],1,features.shape[1]))\n target = target.values\n target = np.reshape(target, (target.shape[0],1,target.shape[1]))\n ds = tf.data.Dataset.from_tensor_slices((features, target))\n ds.batch(batch_size).repeat()\n return ds\n\nfeatures_train = get_features(df_train)\ntarget_train = get_target(df_train)\nds_train = get_dataset(features_train, target_train, batch_size=30)\nfeatures_val = get_features(df_val)\ntarget_val = get_target(df_val)\nds_val = get_dataset(features_val,target_val, batch_size=30)\nfeatures_test = get_features(df_test)\ntarget_test = get_target(df_test)\nds_test = get_dataset(features_test, target_test, batch_size=30)\n\n\ninputs = keras.layers.Input(shape=(9,))\nlayer = keras.layers.Dense(40, kernel_initializer='uniform', kernel_regularizer=tf.keras.regularizers.l1(l=0.01), kernel_constraint=keras.constraints.max_norm(2.))(inputs)\nactivation = keras.layers.ELU(1.5)(layer)\n\nlayer = keras.layers.Dense(50, kernel_initializer='uniform', kernel_regularizer=tf.keras.regularizers.l1(l=0.01))(activation)\nlayer = keras.layers.Dropout(0.2)(layer)\nactivation = keras.layers.ELU(1.5)(layer)\n\nlayer = keras.layers.Dense(60, kernel_initializer='uniform', kernel_regularizer=tf.keras.regularizers.l1(l=0.01))(activation)\nactivation = keras.layers.ELU(1.5)(layer)\n\nlayer = keras.layers.Dense(45, kernel_initializer='uniform', kernel_regularizer=tf.keras.regularizers.l1(l=0.01))(activation)\nactivation = keras.layers.ELU(1.5)(layer)\npredictions = keras.layers.Dense(1)(activation)\n\nmodel = keras.Model(inputs = inputs, outputs = predictions)\n\noptimizer = keras.optimizers.Adam(lr=1e-3, clipnorm=0.5)\n\ndef step_decay_schedule(initial_lr=1e-3, decay_factor=0.75, step_size=10):\n '''\n Wrapper function to create a LearningRateScheduler with step decay schedule.\n '''\n def schedule(epoch):\n return initial_lr * (decay_factor ** np.floor(epoch/step_size))\n return schedule\nlr_sched = step_decay_schedule(initial_lr=1e-3, decay_factor=0.75, step_size=2)\n\nclass LossHistory(keras.callbacks.Callback):\n def on_train_begin(self, logs={}):\n self.losses = []\n\n def on_batch_end(self, batch, logs={}):\n self.losses.append(logs.get('loss'))\n\nhistory = LossHistory()\n\ncallbacks = [\n keras.callbacks.EarlyStopping(patience=3, monitor='val_loss', min_delta=0, mode='auto', baseline=None),\n keras.callbacks.TerminateOnNaN(),\n keras.callbacks.ModelCheckpoint(filepath='/Users/lojze/Documents/mycode/tensorflow/tensorflow-exercise/checkpoint.txt',\n monitor='val_loss', save_best_only=True, mode='auto', period=1, save_weights_only=False),\n keras.callbacks.LearningRateScheduler(schedule=lr_sched),\n keras.callbacks.TensorBoard(log_dir='/Users/lojze/Documents/mycode/tensorflow/tensorflow-exercise/'),\n keras.callbacks.ReduceLROnPlateau(monitor='val_loss', patience=5, factor=0.002, min_lr=1e-5),\n #history\n]\n\nmodel.compile(optimizer=optimizer,\n loss=keras.losses.mean_squared_error,\n metrics=[keras.metrics.mean_squared_error])\n\nmodel.fit(ds_train, epochs=10, steps_per_epoch=500, validation_data=ds_val, validation_steps=60, callbacks=callbacks)\n\nprint(model.evaluate(ds_test, steps=3000))\ntarget_test_values = target_test.values*10000\npred = model.predict(ds_test, steps=3000)*10000\nprint(np.hstack((target_test_values, pred)))\n\n\n\n","sub_path":"keras/keras-exercise/California-house/california-keras.py","file_name":"california-keras.py","file_ext":"py","file_size_in_byte":4700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"409512243","text":"#!/usr/bin/env python3\n\nimport argparse\nimport json\nimport os\nfrom pathlib import Path\nfrom urllib.request import urlretrieve\nimport zipfile\n\nparser = argparse.ArgumentParser(\n description='Finish the installation of a VS code extension for offline use')\nparser.add_argument('extension_name', help='codename of the extension to install')\n\nargs = parser.parse_args()\nname = args.extension_name\nextensions_path = Path.home() / '.vscode' / 'extensions'\nbasepath = [p for p in extensions_path.iterdir() if name in str(p)][0]\npackage_file_path = basepath / 'package.json'\n\nwith open(package_file_path, 'r', encoding='utf-8') as in_file:\n data = json.load(in_file)\n if 'runtimeDependencies' in data:\n for dep in data['runtimeDependencies']:\n if 'linux' in dep['platforms'] and \\\n ('architectures' not in dep or 'x86_64' in dep['architectures']):\n print(f\"Installing {dep['description']}...\")\n filename, _ = urlretrieve(dep['url'])\n install_path = basepath\n if 'installPath' in dep:\n install_path = basepath / dep['installPath']\n if not install_path.exists():\n install_path.mkdir()\n zip_ref = zipfile.ZipFile(filename)\n zip_ref.extractall(install_path)\n zip_ref.close()\n os.unlink(filename)\n lock_file = basepath / 'install.lock'\n lock_file.touch()\n","sub_path":"ansible/roles/oilive/files/postinstall_vscode_ext.py","file_name":"postinstall_vscode_ext.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"635264633","text":"#!/home/cdays/pyweb3/bin/python3\nimport cgitb\nimport json\nimport web3\nimport time\nimport re\nimport cgi\n\nfrom web3 import Web3, HTTPProvider, TestRPCProvider\nfrom solc import compile_source\nfrom web3.contract import ConciseContract\n\nfrom abisol import sol\n\ncgitb.enable()\n\ndef wait_for_receipt(w3, tx_hash, poll_interval):\n while True:\n tx_receipt = w3.eth.getTransactionReceipt(tx_hash)\n if tx_receipt:\n return tx_receipt\n time.sleep(poll_interval)\n\nprint(\"Content-Type: application/json\")\nprint()\n\n# web3.py instance\nw3 = Web3(HTTPProvider('http://localhost:8501'))\nw3.middleware_stack.inject(web3.middleware.geth_poa_middleware, layer=0)\n\ncompiled_sol = compile_source(sol) # Compiled source code\ncontract_interface = compiled_sol[':peerToPeer']\n\nabi = contract_interface['abi']\n\ncontract_address= '0x276736aE5FB11E8539409dE0B213384eF47f9bB9'\ncontract_instance = w3.eth.contract(address=contract_address, abi=abi,ContractFactoryClass=ConciseContract)\n#tx_hash= contract_instance.setGreeting('Lulu', transact={'from': w3.eth.accounts[0]})\n#wait_for_receipt(w3, tx_hash, 1)\ngetre = re.compile('^get')\noutput = {}\naddress = Web3.toChecksumAddress('5d4a482e53573fc9df4ddeac9bbb66bc8361922f')\nfor func in abi:\n try:\n if getre.match(func[\"name\"]):\n output[func[\"name\"]] = eval(\"contract_instance.\"+func[\"name\"]+\"(address)\")\n except:\n pass\nprint(json.dumps(output, indent=3))\n\n","sub_path":"cgi-bin/f.py","file_name":"f.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"560764579","text":"class NumMatrix(object):\n def __init__(self, matrix):\n \"\"\"\n initialize your data structure here.\n :type matrix: List[List[int]]\n \"\"\"\n self.rows = len(matrix);\n self.columns = 0;\n if self.rows > 0:\n self.columns = len(matrix[0]);\n self.matrix = matrix;\n for i in range(self.rows):\n sum = 0;\n for j in range(self.columns):\n sum = sum + matrix[i][j];\n self.matrix[i][j] = sum;\n if i > 0:\n self.matrix[i][j] = self.matrix[i][j] + self.matrix[i - 1][j];\n\n def sumRegion(self, row1, col1, row2, col2):\n \"\"\"\n sum of elements matrix[(row1,col1)..(row2,col2)], inclusive.\n :type row1: int\n :type col1: int\n :type row2: int\n :type col2: int\n :rtype: int\n \"\"\"\n if self.rows == 0 and self.columns == 0:\n return 0;\n temp1 = 0;\n temp2 = 0;\n temp3 = 0;\n if row1 > 0:\n temp1 = self.matrix[row1 - 1][col2];\n if col1 > 0:\n temp2 = self.matrix[row2][col1 - 1];\n if row1 > 0 and col1 > 0:\n temp3 = self.matrix[row1 - 1][col1 - 1];\n return self.matrix[row2][col2] - temp1 - temp2 + temp3;\n\n\n# Your NumMatrix object will be instantiated and called as such:\n# numMatrix = NumMatrix(matrix)\n# numMatrix.sumRegion(0, 1, 2, 3)\n# numMatrix.sumRegion(1, 2, 3, 4)","sub_path":"LeetCode(Python)/304.py","file_name":"304.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"65925674","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.utils import timezone\nfrom comment.models import Comment\nfrom .models import Post, Category\nfrom accounts.models import Blog, CustomUser\nfrom .forms import PostForm, CategoryForm\n\n# Create your views here.\n\n\ndef index(request):\n posts = Post.objects.filter(\n published_date__lte=timezone.now()).order_by('created_date').reverse().select_related(\n \"blog\")[:5]\n\n if 'blog' in request.session:\n del request.session['blog']\n\n if request.user.is_authenticated:\n request.session['own_blogs'] = Blog.objects.filter(\n author_id=request.user).count()\n return render(request, 'blog/index.html', {'articles': posts})\n\n\ndef paging_query(request, queryset, count):\n paginator = Paginator(queryset, count)\n page = request.GET.get('page')\n try:\n page_obj = paginator.page(page)\n except PageNotAnInteger:\n page_obj = paginator.page(1)\n except EmptyPage:\n page_obj = paginator.page(paginator.num_pages)\n return page_obj\n\n\ndef post_list(request, pk):\n posts = Post.objects.filter(\n published_date__lte=timezone.now(), blog_id=pk).order_by('created_date').reverse()\n page_obj = paging_query(request, posts, 10)\n blog = get_object_or_404(Blog, pk=pk)\n user = get_object_or_404(CustomUser, pk=blog.author_id)\n request.session['user'] = user\n request.session['blog'] = blog\n category = Category.objects.filter(blog_id=blog.id)\n request.session['category'] = category\n category.group_by = ['category_id']\n\n return render(request, 'blog/post_list.html',\n {'posts': posts, 'category': category, 'page_obj': page_obj, })\n\n\ndef post_detail(request, pk):\n\n blog = get_object_or_404(Post, pk=pk).blog\n if 'blog'not in request.session:\n request.session['blog'] = blog\n post = get_object_or_404(Post, pk=pk, blog_id=blog.id)\n if post.category_id == 0:\n category = '未分類'\n else:\n category = get_object_or_404(\n Category, pk=post.category_id, blog_id=blog.id)\n comment = Comment.objects.filter(article_id=pk)\n\n return render(request, 'blog/post_detail.html', {'post': post, 'comment': comment, 'category': category})\n\n\ndef Category_Scope(request, pk):\n blogId = request.session['blog'].id\n post = Post.objects.filter(category_id=pk, blog_id=blogId)\n return render(request, 'blog/post_list.html', {'posts': post})\n\n\n@login_required\n@csrf_protect\ndef post_new(request, pk):\n if request.method == \"POST\":\n\n form = PostForm(request.POST, request.FILES)\n if form.is_valid():\n blogs = get_object_or_404(\n Blog, pk=request.session['target_blog'].id)\n post = form.save(commit=False)\n post.author = request.user\n post.blog_id = blogs.id\n\n if request.POST['category_name'] != ''and Category.objects.filter(\n category_name=request.POST['category_name'], blog_id=blogs.id).count() == 0:\n new_category = CategoryForm(request.POST)\n if new_category.is_valid():\n create = new_category.save(commit=False)\n create.holder = request.user\n create.category_name = request.POST['category_name']\n create.blog_id = request.session['target_blog'].id\n create.updated_date = timezone.now()\n create.save()\n post.category_id = get_object_or_404(\n Category, category_name=request.POST['category_name'],\n blog_id=request.session['target_blog'].id).id\n else:\n if request.POST['category_name'] != '':\n post.category_id = get_object_or_404(\n Category, category_name=request.POST['category_name'], blog_id=blogs.id).id\n else:\n post.category_id = request.POST['category_set']\n\n if 'draft_flag'not in request.POST:\n post.published_date = timezone.now()\n\n post.save()\n blogs.published_date = timezone.now()\n blogs.save()\n return redirect('post_list', pk=post.blog_id)\n\n else:\n categories = Category.objects.filter(blog_id=pk)\n target_blog = get_object_or_404(Blog, pk=pk)\n request.session['target_blog'] = target_blog\n form = PostForm()\n return render(request, 'blog/post_edit.html', {'form': form, 'categories': categories})\n\n\n@login_required\n@csrf_protect\ndef post_edit(request, pk):\n post = get_object_or_404(Post, pk=pk)\n if request.method == \"POST\":\n form = PostForm(request.POST, request.FILES, instance=post)\n\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.published_date = timezone.now()\n post.save()\n\n blogs = get_object_or_404(Blog, pk=request.POST['blog_set'])\n blogs.published_date = timezone.now()\n blogs.save()\n return redirect('post_detail', pk=post.pk)\n\n else:\n form = PostForm(instance=post)\n return render(request, 'blog/post_edit.html', {'form': form, 'detail_flag': True})\n\n\n@login_required\ndef post_draft_list(request):\n posts = Post.objects.filter(\n published_date__isnull=True, author_id=request.user.id).order_by('created_date')\n\n return render(request, 'blog/post_draft_list.html', {'posts': posts})\n\n\n@login_required\ndef post_publish(request, pk):\n post = get_object_or_404(Post, pk=pk)\n post.publish()\n return redirect('post_detail', pk=pk)\n\n\n@login_required\ndef post_remove(request, pk):\n post = get_object_or_404(Post, pk=pk)\n post.delete()\n return redirect('post_list', pk=request.session['blog'].id)\n\n\ndef post_login(request):\n return render(request, 'blog/post_login.html')\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"100542920","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\nFILE_PATH = '../data/test.txt'\nDIR = '../graph/testResults/selected/3D'\nSEPARATOR = ' '\nTEST_TYPE_SEPARATOR = '\\n'\n\n\nclass TestResult:\n def __init__(self, alive_qty, max_distance):\n self.alive_qty = alive_qty\n self.max_distance = max_distance\n\n def __repr__(self):\n return \"{{alive_qty:{},max_distance:{}}}\".format(self.alive_qty, self.max_distance)\n\nrules = []\nalive_quantities_list = []\nalive_stds_list = []\nmax_distances_list = []\nmax_distances_stds_list = []\npercentage_list = []\noutputs = []\ndimension = 0\ntotal_rows = 0\ntotal_columns = 0\ntotal_depths = 0\ninitial_rows = 0\ninitial_columns = 0\ninitial_depths = 0\n\n\nfor subdir, dirs, files in os.walk(DIR):\n for file in files:\n filepath = subdir + os.sep + file\n\n alive_qty_list = []\n alive_std_list = []\n max_distance_list = []\n max_distance_std_list = []\n f = open(filepath, 'r')\n line_number = 0\n dimension = f.readline().strip()\n rule = f.readline().strip().split(SEPARATOR)\n total_sizes = f.readline().strip().split(SEPARATOR)\n total_rows = int(total_sizes[0])\n total_columns = int(total_sizes[1])\n if dimension == \"3D\":\n total_depths = int(total_sizes[2])\n initial_sizes = f.readline().strip().split(SEPARATOR)\n initial_rows = int(initial_sizes[0])\n initial_columns = int(initial_sizes[1])\n if dimension == \"3D\":\n initial_depths = int(initial_sizes[2])\n percentage_list = []\n for line in f.readlines():\n if line == \"\\n\":\n line_number = 0\n elif line_number == 0:\n percentage_list.append(float(line))\n line_number += 1\n elif line_number == 1:\n iterationAnalytics = line.split(SEPARATOR)\n alive_qty_list.append([])\n alive_std_list.append([])\n max_distance_list.append([])\n max_distance_std_list.append([])\n alive_qty_list[len(alive_qty_list) - 1].append(float(iterationAnalytics[1]))\n alive_std_list[len(alive_std_list) - 1].append(float(iterationAnalytics[2]))\n max_distance_list[len(max_distance_list) - 1].append(float(iterationAnalytics[3]))\n max_distance_std_list[len(max_distance_std_list) - 1].append(float(iterationAnalytics[4]))\n line_number += 1\n else:\n iterationAnalytics = line.split(SEPARATOR)\n alive_qty_list[len(alive_qty_list) - 1].append(float(iterationAnalytics[1]))\n alive_std_list[len(alive_std_list) - 1].append(float(iterationAnalytics[2]))\n max_distance_list[len(max_distance_list) - 1].append(float(iterationAnalytics[3]))\n max_distance_std_list[len(max_distance_std_list) - 1].append(float(iterationAnalytics[4]))\n line_number += 1\n\n output = []\n for i, percentage in enumerate(percentage_list):\n accum = 0\n for iteration, alive_qty in enumerate(alive_qty_list[i]):\n accum += iteration * alive_qty\n output.append(accum)\n\n rules.append(rule)\n alive_quantities_list.append(alive_qty_list)\n alive_stds_list.append(alive_std_list)\n max_distances_list.append(max_distance_list)\n max_distances_stds_list.append(max_distance_std_list)\n outputs.append(output)\n\npercentage_labels = [str(i*100) + \"%\" for i in percentage_list]\nerrors = []\nfor stds_list in alive_stds_list:\n errors.append([])\n for i in range(len(percentage_list)):\n accum = 0\n for iteration, std in enumerate(stds_list[i]):\n accum += (iteration * std) ** 2\n errors[len(errors)-1].append(np.sqrt(accum))\n\nx = np.arange(len(percentage_labels)) # the label locations\nwidth = 0.25 # the width of the bars\nbars = []\nfig, ax = plt.subplots()\nfor i in range(len(outputs)//2):\n bars.append(ax.bar(x - (i+1)*width, outputs[i], width, log=False, label='{}/{}'.format(rules[i][0], rules[i][1]), yerr=errors[i]))\n\nif len(outputs) % 2 != 0:\n bars.append(ax.bar(x, outputs[len(outputs)//2], width, log=False, label='{}/{}'.format(rules[len(outputs)//2][0], rules[len(outputs)//2][1]), yerr=errors[len(outputs)//2]))\nfor i in range(len(outputs)//2 + 1, len(outputs)):\n bars.append(ax.bar(x + (i-len(outputs)//2)*width, outputs[i], width, log=False, label='{}/{}'.format(rules[i][0], rules[i][1]), yerr=errors[i]))\n\n# Add some text for labels, title and custom x-axis tick labels, etc.\nax.set_ylabel('Output (1e2)')\nax.set_xlabel('Porcentaje inicial')\nif(dimension == \"2D\"):\n plt.title(\"Output en función del input\\n\"\n \"{} - Espacio inicial = {}x{} - Espacio Total = {}x{}\".format(dimension, initial_rows, initial_columns, total_rows, total_columns))\nelse:\n plt.title(\"Output en función del input\\n\"\n \"{} - Espacio inicial = {}x{}x{} - Espacio Total = {}x{}x{}\".format(dimension, initial_rows, initial_columns, initial_depths, total_rows, total_columns, total_depths))\nax.set_xticks(x)\nax.set_xticklabels(percentage_labels)\nyticks = range(0, 10000001, 10000000//5)\nax.set_yticks(yticks)\noutput_labels = [int(i//(10**2)) for i in yticks]\nax.set_yticklabels(output_labels)\n\nrects = ax.patches\nlabels = []\nfor i in outputs:\n for j in i:\n labels.append(\"{}\".format(int(j//(10**2))))\n\nfor rect, label in zip(rects, labels):\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label, ha='center', va='bottom')\n\n# Shrink current axis by 20%\nbox = ax.get_position()\nax.set_position([box.x0, box.y0, box.width * 0.8, box.height])\n\n# Put a legend to the right of the current axis\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\nplt.show()\n","sub_path":"graph/outputGraph.py","file_name":"outputGraph.py","file_ext":"py","file_size_in_byte":5870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"311718674","text":"import unittest\n\nfrom eplasty import field as f\nfrom eplasty import Object\nfrom eplasty.ctx import set_context, start_session, commit, add, get_connection, get_session\nfrom .util import get_test_conn\nfrom eplasty.object import NotFound, TooManyFound\nfrom eplasty.object.exc import LifecycleError\n\ntry:\n from pyramid_eplasty.traverser import Traverser\nexcept ImportError:\n Traverser = None\n\nclass Root(dict):\n __parent__ = None\n __name__ = ''\n\n\n@unittest.skipIf(Traverser is None, 'No pyramid_eplasty, skipping tests')\nclass Test(unittest.TestCase):\n \"\"\"Optional tests for pyramid_eplasty package\"\"\"\n\n def setUp(self):\n \n class Knight(Object):\n set_context(get_test_conn())\n start_session()\n title = f.CharacterVarying(\n length = 5, null = False, default = 'Sir'\n )\n name = f.CharacterVarying(length = 20, null = False)\n nickname = f.CharacterVarying(length = 20, null = True)\n score = f.Integer()\n \n self.Knight = Knight\n self.root = Root()\n Traverser(class_=self.Knight, field='name', session=get_session()).mount(self.root, 'knights')\n \n for ktup in [\n ('Sir', 'Galahad', 'The Pure', 10),\n ('King', 'Arthur', None, 20),\n ('Sir', 'Robin', 'The Brave', 30),\n ('Sir', 'Lancelot', None, 40),\n ]:\n title, name, nickname, score = ktup\n k = Knight(\n title = title,\n name = name,\n nickname = nickname,\n score = score\n )\n add(k)\n \n commit()\n start_session()\n\n def tearDown(self):\n c = get_connection()\n c.cursor().execute('DROP TABLE knights;')\n c.commit()\n\n def test_get(self):\n knight = self.root['knights']['Galahad']\n self.assertEqual(knight.title, 'Sir')\n self.assertEqual(knight.name, 'Galahad')\n self.assertEqual(knight.nickname, 'The Pure')\n self.assertEqual(knight.score, 10)\n\n\n","sub_path":"src/test/test_pyramid.py","file_name":"test_pyramid.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"377070622","text":"'''\nКусок кода с новым методом /getpreds просто засунуть в текущий вебсервис\n'''\n\nfrom flask import Flask\nfrom flask import request\nimport requests as r\nfrom flask.json import jsonify\nimport numpy as np\n\n\nAPP = Flask(__name__)\n\n\ndef make_preds(q, ans):\n '''\n q - это текст вопроса\n ans - это list ответов на него\n return - list с вероятностями принадлежать ответа к троллингу \n (порядок должен быть такой же как в ans)\n '''\n\n # тут нужно вызывать модель вместо заглушки\n return list(np.random.random(len(ans)))\n\n\n\n@APP.route('/getpreds', methods=['POST'])\ndef getpreds():\n\n jdict = request.get_json(force=True)['items']\n answer = {'response': []}\n for pair in jdict:\n q = pair['question']\n ans = pair['answers']\n answer['response'].append({'preds': make_preds(q, ans) })\n return jsonify(answer)\n\n# Запускаем веб-сервис\n\nif __name__=='__main__':\n APP.run()\n '''\n Тестить сервис так. Стандартный вид jsona такой:\n j = {\n 'items': [\n {'question': 'q1', 'answers': ['a11', 'a12', 'a13', 'a14']}\n , {'question': 'q2', 'answers': ['a21', 'a22']}\n , {'question': 'q3', 'answers': ['a31']}\n ]\n }\n a = r.post('http://127.0.0.1:5000/getpreds', json=j)\n print(a.text)\n\n Минимальный json (1 вопрос с 1 ответом)\n j = {\n 'items': [\n {'question': 'ывапывпыв', 'answers': ['ыфвпфвыпвыфп']}\n ]\n }\n a = r.post('http://127.0.0.1:5000/getpreds', json=j)\n print(a.text)\n '''","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"74226832","text":"#!/usr/bin/env python3\n\n# Make sure that arity specifiers of public metafunctions are consistent with their signatures.\n\nimport re\nimport xml.etree.ElementTree as ET\nimport subprocess\n\nsubprocess.call(\"doxygen > /dev/null 2> /dev/null\", shell=True)\n\n\ndef check_file(filename):\n tree = ET.parse(f\"xml/{filename}_8h.xml\")\n root = tree.getroot()\n\n arity_specifiers = gather_arity_specifiers(root)\n\n for metafunction_name, arity in gather_metafunctions(root).items():\n expected_arity = int(arity)\n actual_arity = int(arity_specifiers[metafunction_name])\n assert expected_arity == actual_arity\n\n\ndef gather_metafunctions(root):\n metafunctions = {}\n\n for definition in root.findall(\"./compounddef/sectiondef/memberdef\"):\n macro_name = definition.find(\"name\").text\n is_metalang99_compliant = re.search(\"ML99_[a-z]\", macro_name)\n\n exceptions = {\n \"ML99_call\", \"ML99_callUneval\", \"ML99_fatal\", \"ML99_abort\", \"ML99_tupleGet\", \"ML99_variadicsGet\", \"ML99_seqGet\"}\n is_exceptional = macro_name in exceptions\n\n if (is_metalang99_compliant and not is_exceptional):\n arity = len(list(definition.findall(\"param\")))\n metafunctions[macro_name] = arity\n\n return metafunctions\n\n\ndef gather_arity_specifiers(root):\n arity_specifiers = {}\n\n for definition in root.findall(\"./compounddef/programlisting/codeline/highlight[@class='preprocessor']\"):\n m = re.match(r\"#define(\\w+)_ARITY(\\d)\", \"\".join(definition.itertext()))\n if m is not None:\n metafunction_name = m.groups()[0]\n arity = m.groups()[1]\n arity_specifiers[metafunction_name] = arity\n\n return arity_specifiers\n\n\nfilenames = [\"assert\", \"choice\", \"either\", \"gen\", \"lang\", \"list\",\n \"bool\", \"maybe\", \"nat\", \"ident\", \"tuple\", \"util\", \"variadics\", \"seq\"]\n\nfor filename in filenames:\n check_file(filename)\n","sub_path":"scripts/check-arities.py","file_name":"check-arities.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"105274745","text":"from django import template\nfrom django.db.models import Max\n\nfrom private_message.models import Message\n\nregister = template.Library()\n\n\n@register.inclusion_tag('private_message/_new_messages_header.html')\ndef show_new_messages(user):\n query = 'SELECT * FROM private_message_message WHERE id IN (SELECT MAX(id) ' \\\n 'FROM private_message_message WHERE was_read=FALSE AND to_user_id = {} GROUP BY from_user_id) ' \\\n 'ORDER BY private_message_message.created DESC'.format(user.id)\n messages = Message.objects.raw(query)\n return {'messages': messages, 'messages_count': len(list(messages))}\n","sub_path":"private_message/templatetags/private_message_tags.py","file_name":"private_message_tags.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"306628481","text":"# This is a region plugin for Galaxy Charts and New Frontier, created by the System Plugin Creator Tool\n\n########## GENERAL REGION INFORMATION ##########\n\nName = \"DS9FX Vela\"\nControllingEmpire = \"Federation\"\nSectorNumber = 127\nImagePath = \"\"\nType = \"Single\"\nLocation = [117.77, 25878.07]\nOnlyInQB = 0\nOnlyMult = 0\nIgnoreRDF = 1\nSystemsFiles = [\"Systems.DS9FXVela.DS9FXVela1\"]\nDescription = \"System with no planets containing only a Pulsar.\"\n","sub_path":"scripts/Custom/Systems/Regions/DS9FXVela.py","file_name":"DS9FXVela.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"610191695","text":"# begin initialising the variables needed for cycle\n# start with duration of different parts of the cycle \ncycle_dur = input(\"Enter CYCLE TIME in seconds: \")\ncycle_dur = int(cycle_dur)\nintergreen = input(\"Enter INTERGREEN TIME in seconds: \")\nintergreen = int(intergreen)\ncyc_start_dur = 3\ncyc_end_dur = 4\ntransition_dur = 7 + intergreen\ngreen_split = cycle_dur - cyc_start_dur - transition_dur - cyc_end_dur\nphase_count = 2\n\nperiodA_dur = green_split / 2\nperiodA_dur = int(periodA_dur)\nperiodB_dur = green_split - periodA_dur\nperiodB_dur = int(periodB_dur)\n\n# print value to terminal\nprint(\"\\n\\tCYCLE TIME\\tINTERGREEN\\tGREEN SPLIT\\tPERIOD A\\tPERIOD B\\n\\t\" + str(cycle_dur) + \"\\t\\t\" + str(intergreen) + \"\\t\\t\" + str(green_split) + \"\\t\\t\" + str(periodA_dur) + \"\\t\\t\" + str(periodB_dur) + \"\\n\")\n\n# defines starting values of the statuses of the lights\nsts_A = 'RED'\nsts_B = 'RED'\n\n# define the start/end times of each stage\n# naming convention\n# Xs = section start\n# Xe = section end\n# Sx = Start section\n# Ax = period A section\n# Tx = transition section\n# Bx = period B section\n# Ex = end section\n\nSs = 0\nSe = 3\nAs = Se\nAe = As + periodA_dur\nTs = Ae \nTe = Ts + 7 + intergreen\nBs = Te\nBe = Bs + periodB_dur\nEs = Be\nEe = Es + 4\n# print values to terminal\nprint(\"\\tSs\\tSe\\tAs\\tAe\\tTs\\tTe\\tBs\\tBe\\tEs\\tEe\\n\\t\" + str(Ss) + \"\\t\" + str(Se) + \"\\t\" + str(As) + \"\\t\" + str(Ae) + \"\\t\" + str(Ts) + \"\\t\" + str(Te) + \"\\t\" + str(Bs) + \"\\t\" + str(Be) + \"\\t\" + str(Es) + \"\\t\" + str(Ee) + \"\\n\")\n","sub_path":"Submission-Code/Test-Functions/parameter.py","file_name":"parameter.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"33522081","text":"from multiprocessing import Process, Queue\nimport logging.handlers\nimport os\nfrom Config.config import get_config\nfrom threading import Timer\nimport shutil\nimport re\nimport traceback\nfrom socket import gethostname\nimport time\nimport Queue as Q\nfrom RecordingException import UnequallStampException\n# Currently not support multiple machine pulling from one incoming dir.\n# If need, just add incoming dir in the constructor\n\n\nclass TaskRunner:\n\n entry_regex = '^([01]_\\w{8})_([01]_\\w{8})_(\\d+)'\n pattern = re.compile(entry_regex)\n\n @staticmethod\n def match(directory_name):\n return TaskRunner.pattern.match(directory_name)\n\n @staticmethod\n def get_param(directory_name):\n m = re.search(TaskRunner.entry_regex, directory_name)\n entry_id = m.group(1)\n recorded_id = m.group(2)\n duration = m.group(3)\n param = {'entry_id': entry_id, 'directory': directory_name, 'recorded_id': recorded_id,\n 'duration': duration}\n\n return param\n\n def __init__(self, task, number_of_processes, output_directory, max_task_count):\n self.number_of_processes = number_of_processes\n self.task = task\n self.task_name = task.__name__\n self.polling_interval = get_config('polling_interval_sec', 'int')\n base_directory = get_config('recording_base_dir')\n hostname = gethostname()\n self.failed_tasks_handling_interval = get_config('failed_tasks_handling_interval', 'int')*60 # in minutes\n self.failed_tasks_max_retries = get_config('failed_tasks_max_retries')\n self.task_directory = os.path.join(base_directory, hostname, self.task_name)\n self.error_directory = os.path.join(base_directory, 'error')\n self.failed_tasks_directory = os.path.join(base_directory, hostname, self.task_name, 'failed')\n self.input_directory = os.path.join(base_directory, hostname, self.task_name, 'incoming')\n self.working_directory = os.path.join(base_directory, hostname, self.task_name, 'processing')\n self.output_directory = output_directory\n self.task_queue = Queue(max_task_count)\n self.logger = logging.getLogger(__name__+'-'+self.task_name)\n self.on_startup()\n\n def on_startup(self):\n self.logger.info(\"onStartUp: %s\", self.task_name)\n try:\n if not os.path.exists(self.task_directory): # In case directory not exist\n os.makedirs(self.task_directory)\n\n if not os.path.exists(self.failed_tasks_directory): # In case directory not exist\n os.makedirs(self.failed_tasks_directory)\n\n if not os.path.exists(self.input_directory): # In case directory not exist\n os.makedirs(self.input_directory)\n\n if not os.path.exists(self.working_directory): # In case directory not exist\n os.makedirs(self.working_directory)\n\n if not os.path.exists(self.output_directory): # In case directory not exist\n os.makedirs(self.output_directory)\n\n except os.error as e:\n self.logger.fatal(\"Error %s \\n %s\", str(e), traceback.format_exc())\n\n def move_and_add_to_queue(self, src_dir):\n\n for directory_name in os.listdir(src_dir):\n directory_path = os.path.join(src_dir, directory_name)\n if self.match(directory_name) is not None:\n try:\n if os.path.isdir(directory_path):\n param = self.get_param(directory_name)\n if src_dir != self.working_directory: # if its not the same directory\n shutil.move(directory_path, self.working_directory)\n self.task_queue.put(param, block=False)\n self.logger.info(\"[%s-%s] Add unhanded directory %s from %s to the task queue\", param['entry_id'],\n param['recorded_id'], directory_name, src_dir)\n else:\n self.logger.warn(\"Can't find the content of %s, move it to %s\", directory_path,\n self.error_directory)\n self.safe_move(directory_path, self.error_directory)\n\n except Q.Full:\n self.logger.warn(\"Failed to add new task, queue is full!\")\n\n except Exception as e:\n self.logger.error(\"[%s-%s] Error while try to add task:%s \\n %s\", param['entry_id'], param['recorded_id'],\n str(e), traceback.format_exc())\n\n def work(self, index):\n self.logger.info(\"Worker %s start working\", index)\n while True:\n task_parameter = self.task_queue.get()\n logger_info = task_parameter['entry_id'] + '-' + task_parameter['recorded_id']\n self.logger.info(\"[%s] Task is performed by %d\", logger_info, index)\n try:\n src = os.path.join(self.working_directory, task_parameter['directory'])\n\n job = self.task(task_parameter, logger_info) # operate the function task_job, with argument task_parameters\n job.check_stamp() # raise error if stamp is not valid\n job.run()\n job.check_stamp()\n shutil.move(src, self.output_directory)\n self.logger.info(\"[%s] Task %s completed, Move %s to %s\", logger_info, self.task_name, src,\n self.output_directory)\n except UnequallStampException as e:\n self.logger.error(\"[%s] %s \\n %s\", logger_info, str(e), traceback.format_exc())\n self.safe_move(src, self.error_directory)\n except Exception as e:\n self.logger.error(\"[%s] Failed to perform task :%s \\n %s\", logger_info, str(e), traceback.format_exc())\n retries = self.get_retry_count(src)\n try:\n if retries > 0:\n self.logger.info(\"[%s] Job %s on entry %s has %s retries, move it to failed task directory \",\n logger_info, self.task_name, task_parameter['directory'], retries)\n self.safe_move(src, self.failed_tasks_directory)\n else:\n self.logger.fatal(\"[%s] Job %s on entry %s has no more retries or failed to get it, move entry to \"\n \"failed task directory \", logger_info, self.task_name, task_parameter['directory'])\n self.safe_move(src, self.error_directory)\n except Exception as e:\n self.logger.fatal(\"[%s] Failed to handle failure task %s \\n %s\", logger_info, str(e)\n , traceback.format_exc())\n\n def get_retry_count(self, src):\n try:\n retries_file_path = os.path.join(src, 'retries')\n if not os.path.exists(retries_file_path):\n with open(retries_file_path, \"w\") as retries_file:\n retries_file.write(self.failed_tasks_max_retries)\n return self.failed_tasks_max_retries\n else:\n with open(retries_file_path, \"r+\") as retries_file:\n retries = retries_file.read()\n retries = int(retries) - 1\n retries_file.seek(0)\n retries_file.truncate()\n retries_file.write(str(retries))\n\n return retries\n except Exception as e:\n self.logger.error(\"Failed to get retry count for %s: %s \\n %s\", src, str(e), traceback.format_exc())\n return 0\n\n def add_new_task_handler(self):\n thread = Timer(self.polling_interval, self.add_new_task_handler)\n thread.daemon = True\n thread.start()\n self.move_and_add_to_queue(self.input_directory)\n\n def failed_task_handler(self):\n thread = Timer(self.failed_tasks_handling_interval, self.failed_task_handler)\n thread.daemon = True\n thread.start()\n self.move_and_add_to_queue(self.failed_tasks_directory)\n\n def start(self):\n try:\n self.logger.info(\"Starting %d workers\", self.number_of_processes)\n workers = [Process(target=self.work, args=(i,)) for i in xrange(1, self.number_of_processes+1)]\n for w in workers:\n w.start()\n self.move_and_add_to_queue(self.working_directory)\n self.add_new_task_handler()\n self.failed_task_handler()\n\n except Exception as e:\n self.logger.fatal(\"Failed to start task runner: %s \\n %s \", str(e), traceback.format_exc())\n finally:\n return workers\n\n def safe_move(self, src, dst):\n try:\n try:\n shutil.move(src, dst)\n except shutil.Error as e:\n file_name = os.path.basename(src)\n new_file_name = ''.join([file_name, '_', str(time.time())])\n new_dest = os.path.join(dst, new_file_name)\n self.logger.error(\"Failed to move %s into %s, try to move it as %s\", src, dst, new_dest)\n shutil.move(src, new_dest)\n\n except Exception as e:\n self.logger.error(\"Failed to move %s to %s : %s \\n %s\", src, dst, str(e), traceback.format_exc())\n","sub_path":"liveRecorder/Tasks/TaskRunner.py","file_name":"TaskRunner.py","file_ext":"py","file_size_in_byte":9359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"77846831","text":"from typing import Dict, Tuple, Callable, Iterable, Optional\n\nimport torch\nfrom torch import nn, Tensor\nfrom torch.distributions import Distribution, Normal, MultivariateNormal\nfrom torch.nn import functional as F\n\nfrom utils import with_default_config, get_activation, get_activation_module, get_initializer, matrix_diag\n\n\nclass BaseModel(nn.Module):\n def __init__(self, config: Dict):\n super().__init__()\n self.config = config\n self.device = 'cpu'\n\n def forward(self, x: Tensor) -> Tuple[Distribution, Tensor]:\n # Output: action_dist, value\n raise NotImplementedError\n\n def cuda(self, *args, **kwargs):\n super().cuda(*args, **kwargs)\n self.device = 'cuda'\n\n def cpu(self):\n super().cpu()\n self.device = 'cpu'\n\n\nclass MLPModel(BaseModel):\n def __init__(self, config: Dict):\n super().__init__(config)\n\n torch.manual_seed(0)\n\n default_config = {\n \"input_size\": 24,\n \"num_actions\": 2,\n \"activation\": \"relu\",\n\n \"sigma0\": 1.,\n\n \"hidden_sizes\": (64, 64),\n }\n self.config = with_default_config(config, default_config)\n\n input_size: int = self.config.get(\"input_size\")\n num_actions: int = self.config.get(\"num_actions\")\n hidden_sizes: Tuple[int] = self.config.get(\"hidden_sizes\")\n self.activation: Callable = get_activation(self.config.get(\"activation\"))\n\n layer_sizes = (input_size,) + hidden_sizes\n\n self.hidden_layers = nn.ModuleList([\n nn.Linear(in_size, out_size)\n for in_size, out_size in zip(layer_sizes, layer_sizes[1:])\n ])\n self.policy_mu_head = nn.Linear(layer_sizes[-1], num_actions)\n\n self.v_hidden_layers = nn.ModuleList([\n nn.Linear(in_size, out_size)\n for in_size, out_size in zip(layer_sizes, layer_sizes[1:])\n ])\n\n self.std = nn.Parameter(torch.ones(1, num_actions) * self.config[\"sigma0\"])\n\n self.value_head = nn.Linear(layer_sizes[-1], 1)\n\n def forward(self, x: Tensor) -> Tuple[Distribution, Tensor]:\n\n int_policy = x\n for layer in self.hidden_layers:\n int_policy = layer(int_policy)\n int_policy = self.activation(int_policy)\n\n action_mu = torch.tanh(self.policy_mu_head(int_policy)) # [-1, 1]\n\n int_value = x\n for layer in self.v_hidden_layers:\n int_value = layer(int_value)\n int_value = self.activation(int_value)\n\n value = self.value_head(int_value)\n\n # cov = matrix_diag(self.std)\n # action_distribution = MultivariateNormal(loc=action_mu, covariance_matrix=cov)\n action_distribution = Normal(loc=action_mu, scale=self.std)\n\n return action_distribution, value\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"365143360","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n2023-07-16-gradients-with-ci.py: script to plot the gradient of a range of\nerror grids together with the 95% confidence interval.\n\"\"\"\n\nimport argparse\nfrom itertools import groupby\nfrom pathlib import Path\nfrom typing import Union\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom parse import compile\nfrom pyprojroot import here\nfrom tqdm import tqdm\nimport xarray as xr\n\nimport multiLevelCoSurrogates as mlcs\n\nimport processing as proc\n\ndata_path = here('files/2020-11-05-simple-mfbo/')\nplot_path = here('plots/2023-07-16-gradients-with-ci/', warn=False)\nplot_path.mkdir(exist_ok=True, parents=True)\n\nsubfolder_template = compile('{func_name}-{method}-c{cost_ratio:f}-b{init_budget:d}-i{idx:d}')\nerrorgrid_template = compile('errorgrid_{iteration:d}.nc')\n\n\ndef plot_folder_angles_as_polar(folder: Path, exts, force_regen=False, use_cost_ratio=None):\n if not subfolder_template.parse(folder.name):\n return\n angles, median_angles, budgets = get_budget_and_angles(folder, force_regen=force_regen, use_cost_ratio=use_cost_ratio)\n if not angles:\n return # no .nc files were present\n\n fig, ax = plt.subplots(1, 1, subplot_kw={'projection': 'polar'})\n ax.plot(angles, budgets)\n for ext in exts:\n fig.savefig(plot_path / f'{folder.name}{ext}')\n fig.clear()\n plt.close('all')\n\n\ndef plot_grouped_folder_angles_as_polar(folders, group_name, exts, force_regen=False, use_cost_ratio=None, save_median=False):\n print(f'plotting group {group_name}')\n\n #fig_all, ax_all = plt.subplots(nrows=1, ncols=1, subplot_kw={'projection': 'polar'})\n #fig_med, ax_med = plt.subplots(nrows=1, ncols=1, subplot_kw={'projection': 'polar'})\n fig_ci, ax_ci = plt.subplots(nrows=1, ncols=1)\n #fig_all.suptitle(group_name)\n #fig_med.suptitle(group_name)\n fig_ci.suptitle(group_name)\n\n for idx, folder in tqdm(enumerate(list(folders)), leave=False, desc='Experiment reps'):\n if not subfolder_template.parse(folder.name):\n return\n angles, median_angles, budgets, deg, low, high = get_budget_and_angles(folder, force_regen=force_regen, use_cost_ratio=use_cost_ratio)\n if not angles:\n return # no .nc files were present\n\n #ax_ci.plot(budgets, low, c='blue')\n ax_ci.plot(budgets, deg, c='black')\n ax_ci.fill_between(budgets, low, high, alpha=.15, color='black')\n\n #ax_ci.plot(budgets, high, c='orange')\n\n #ax_all.plot(angles, budgets, lw=.75, c='black', alpha=.9-(idx*.15))\n #if save_median:\n # ax_med.plot(median_angles, budgets, lw=.75, c='black', alpha=.9-(idx*.15))\n\n ax_ci.set_ylim([-5, 125])\n ax_ci.set_xlim([0, max(budgets)])\n ax_ci.hlines([0, 90], 0, max(budgets), color='black', linewidth=.25)\n ax_ci.set_xlabel('Used Budget')\n ax_ci.set_ylabel('Gradient angle')\n #for ax, title in zip([ax_all, ax_med], [\"Using all repetitions\", \"Using only median of repetitions\"]):\n # ax.set_thetalim(thetamin=0, thetamax=120)\n # ax.set_thetagrids([0, 15, 30, 45, 60, 75, 90, 105, 120])\n # ax.set_xlabel('Used budget')\n # ax.set_ylabel('Gradient angle')\n # ax.set_title(title)\n\n for ext in exts:\n fig_ci.savefig(plot_path / f'ci_{group_name.replace(\".\", \"\").replace(\" \", \"_\")}{ext}', bbox_inches='tight')\n #fig_all.savefig(plot_path / f'{group_name.replace(\".\", \"\").replace(\" \", \"_\")}{ext}', bbox_inches='tight')\n #if save_median:\n # fig_med.savefig(plot_path / f'medians_{group_name.replace(\".\", \"\").replace(\" \", \"_\")}{ext}', bbox_inches='tight')\n fig_ci.clear()\n #fig_all.clear()\n #fig_med.clear()\n plt.close('all')\n\n\ndef get_budget_and_angles(folder: Path, force_regen: bool=False, use_cost_ratio: bool=False):\n angles_filename = folder / 'angles.csv'\n if force_regen or not angles_filename.exists():\n df = calculate_angles(folder, use_cost_ratio=use_cost_ratio)\n df.to_csv(angles_filename, index=False)\n else:\n df = pd.read_csv(angles_filename)\n\n return [df[c].values.tolist() for c in ['theta', 'median_theta', 'budgets', 'deg', 'deg_low', 'deg_high']]\n\n\ndef calculate_angles(folder: Path, use_cost_ratio: bool=False):\n budgets = [0]\n match = subfolder_template.parse(folder.name)\n init_budget = match['init_budget']\n cost_ratio = match['cost_ratio'] if use_cost_ratio else None\n df = pd.read_csv(folder / 'log.csv', index_col=0, sep=';')\n budgets.extend((init_budget - df['budget'].values).tolist())\n\n angles = []\n median_angles = []\n for file in tqdm(sorted(folder.iterdir()), leave=False, desc='EG files'):\n if not errorgrid_template.parse(file.name):\n continue\n with xr.open_dataset(file) as ds:\n da = ds['mses'].sel(model='high_hier')\n with da.load() as da:\n angle_summary = mlcs.utils.error_grids.calc_angle(da, cost_ratio=cost_ratio)\n median_summary = mlcs.utils.error_grids.calc_angle(da.median(dim='rep'), cost_ratio=cost_ratio)\n angles.append(angle_summary)\n median_angles.append(median_summary.theta)\n\n # todo: better error handling on why this would happen and how to deal with it\n if len(angles) != len(budgets):\n actual_length = min(len(angles), len(budgets))\n angles = angles[:actual_length]\n median_angles = median_angles[:actual_length]\n budgets = budgets[:actual_length]\n\n df = pd.DataFrame.from_records(angles, columns=mlcs.utils.error_grids.AngleSummary._fields)\n df['median_theta'] = median_angles\n df['budgets'] = budgets\n\n return df\n\n\ndef remove_idx(name: Union[Path, str]) -> str:\n if isinstance(name, Path):\n name = name.name\n return name[:name.find('-i')]\n\n\ndef main(args):\n suffixes = args.exts or proc.suffixes\n folders = []\n for subfolder in sorted(data_path.iterdir()):\n if not subfolder.is_dir():\n continue\n folders.append(subfolder)\n if args.singles:\n plot_folder_angles_as_polar(subfolder, suffixes,\n force_regen=args.force_regen,\n use_cost_ratio=args.cost_ratio)\n\n if args.grouped:\n for name, folder_group in groupby(folders, key=remove_idx):\n plot_grouped_folder_angles_as_polar(folder_group, name, suffixes,\n force_regen=args.force_regen,\n use_cost_ratio=args.cost_ratio,\n save_median=args.save_median)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--exts\", action=\"extend\", nargs=\"+\", type=str,\n help=\"File extensions to use when saving images. Default: [.PNG, .PDF].\")\n parser.add_argument(\"--singles\", action=argparse.BooleanOptionalAction, default=False,\n help=\"Plot every run comparison individually. Default: --no-singles.\")\n parser.add_argument(\"--grouped\", action=argparse.BooleanOptionalAction, default=True,\n help=\"Plot comparison of methods over multiple runs. Default: --grouped.\")\n parser.add_argument('--force-regen', action='store_true',\n help=\"Force regeneration of all caching files. Default: --no-force-regen\")\n parser.add_argument('--cost-ratio', action='store_true', default=True,\n help=\"Include cost-ratio in calculating angles. Default: --cost-ratio\")\n parser.add_argument('--save-median', action='store_true',\n help=\"Also save grouped plots for only median repetition. Default: --no-save-median\")\n args = parser.parse_args()\n\n main(args)\n","sub_path":"scripts/processing/2023-07-16-gradients-with-ci.py","file_name":"2023-07-16-gradients-with-ci.py","file_ext":"py","file_size_in_byte":7772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"522304396","text":"\nimport gym\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.distributions import MultivariateNormal, Categorical\nimport numpy as np \n\nclass DeepSet(nn.Module):\n\n\tdef __init__(self,phi_layers,rho_layers,activation):\n\t\tsuper(DeepSet, self).__init__()\n\t\t\n\t\tself.phi = Phi(phi_layers,activation)\n\t\tself.rho = Rho(rho_layers,activation)\n\n\t\tself.state_dim = phi_layers[0].in_features\n\t\tself.hidden_dim = phi_layers[-1].out_features\n\t\tself.action_dim = rho_layers[-1].out_features\n\n\t# def forward(self,x):\n\t# \t# x is a list of namedtuple with where relative_neighbors is a list\n\t# \tX = torch.zeros((len(x),self.hidden_dim+self.state_dim))\n\t# \tfor step,x_i in enumerate(x):\n\t# \t\trelative_goal = torch.from_numpy(x_i.relative_goal).float() \n\t# \t\trelative_neighbors = x_i.relative_neighbors\n\t# \t\tsumm = torch.zeros((self.hidden_dim))\n\t# \t\tfor relative_neighbor in relative_neighbors:\n\t# \t\t\trelative_neighbor = torch.from_numpy(relative_neighbor).float()\n\t# \t\t\tsumm += self.phi(relative_neighbor)\n\t# \t\tX[step,:] = torch.cat((relative_goal,summ))\n\t# \treturn self.rho(X)\n\n\tdef forward(self,x):\n\t\t# x is a list of namedtuple with where relative_neighbors is a list\n\t\tX = torch.zeros((len(x),self.hidden_dim))\n\t\tfor step,x_i in enumerate(x):\n\t\t\trelative_neighbors = x_i\n\t\t\tsumm = torch.zeros((self.hidden_dim))\n\t\t\tfor relative_neighbor in relative_neighbors:\n\t\t\t\trelative_neighbor = np.array(relative_neighbor, ndmin=1)\n\t\t\t\trelative_neighbor = torch.from_numpy(relative_neighbor).float()\n\t\t\t\tsumm += self.phi(relative_neighbor)\n\t\t\tX[step,:] = summ\n\t\tout = self.rho(X)\n\t\treturn out\n\nclass Phi(nn.Module):\n\n\tdef __init__(self,layers,activation):\n\t\tsuper(Phi, self).__init__()\n\t\tself.layers = layers\n\t\tself.activation = activation\n\tdef forward(self, x):\n\t\tfor layer in self.layers[:-1]:\n\t\t\tx = self.activation(layer(x))\n\t\tx = self.layers[-1](x)\n\t\treturn x\n\n\nclass Rho(nn.Module):\n\tdef __init__(self,layers,activation):\n\t\tsuper(Rho, self).__init__()\n\t\tself.layers = layers\n\t\tself.activation = activation\n\n\tdef forward(self, x):\n\t\tfor layer in self.layers[:-1]:\n\t\t\tx = self.activation(layer(x))\n\t\tx = self.layers[-1](x)\n\t\treturn x\n\n","sub_path":"code/learning/deepset.py","file_name":"deepset.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"420158722","text":"from flask_assets import Environment, Bundle\n\n\n#: application css bundle\n# css_places = Bundle(\"less/places.less\",\n# filters=\"less\", output=\"css/places.css\",\n# debug=False)\n\n#: consolidated css bundle\ncss_all = Bundle(\n\t\t\t\t\t\"css/bootstrap.min.css\", \n\t\t\t\t\t# css_places,\n\t\t\t\t\t\"css/bootstrap-theme.min.css\",\n\t\t\t\t\t\"css/leaflet.css\",\n\t\t\t\t\tfilters=\"cssmin\", output=\"css/places.min.css\",\n\t\t\t\t\t)\n\n#: vendor js bundle\njs_vendor = Bundle(\n\t\t\t\t\t\"js/jquery-1.11.1.min.js\",\n\t\t\t\t\t\"js/bootstrap.min.js\",\n\t\t\t\t\t\"js/underscore-min.js\",\n\t\t\t\t\t\"js/leaflet.js\",\n\t\t\t\t\tfilters=\"jsmin\", output=\"js/vendor.min.js\",\n\t\t\t\t\t)\n\n#: application js bundle\n# js_main = Bundle(\"coffee/*.coffee\", filters=\"coffeescript\", output=\"js/main.js\")\n\n\ndef init_app(app):\n\twebassets = Environment(app)\n\twebassets.register('css_all', css_all)\n\twebassets.register('js_vendor', js_vendor)\n\t# webassets.register('js_main', js_main)\n\twebassets.manifest = 'cache' if not app.debug else False\n\twebassets.cache = not app.debug\n\twebassets.debug = app.debug\n\n","sub_path":"metroplaces/mpassets.py","file_name":"mpassets.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"512308766","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport numpy as np\nfrom flask import Flask, request, render_template\nimport pickle\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\n\napp = Flask(__name__, template_folder='templates', static_url_path='/static')\n\nmodel = pickle.load(open('XGBoost_classification_model2.pkl', 'rb'))\n\n\n@app.route('/')\ndef home():\n try:\n\n return render_template('index.html')\n except BaseException as err:\n print(err)\n\n\n@app.route('/predict', methods=['POST'])\ndef predict():\n location = int(request.form['location'])\n updated_at = int(request.form['updated_at'])\n ID_caller = int(request.form['ID_caller'])\n opened_time = int(request.form['opened_time'])\n Support_group = int(request.form['Support_group'])\n support_incharge = int(request.form['support_incharge'])\n category_ID = int(request.form['category_ID'])\n count_updated = int(request.form['count_updated'])\n ID_status = int(request.form['ID_status'])\n val = []\n\n column_name = ['category_ID', 'ID_status', 'opened_time', 'updated_at', 'Support_group', 'support_incharge',\n 'location', 'count_updated', 'ID_caller']\n val.append(category_ID)\n val.append(ID_status)\n val.append(opened_time)\n val.append(updated_at)\n val.append(Support_group)\n val.append(support_incharge)\n val.append(location)\n val.append(count_updated)\n val.append(ID_caller)\n\n lst = np.array([val])\n scaler = MinMaxScaler()\n scaled_arr = scaler.fit_transform(lst)\n sdf = pd.DataFrame(scaled_arr, columns=column_name)\n\n prediction = model.predict(sdf)\n print(prediction)\n \n if prediction == 0:\n result = \"Low\"\n elif prediction == 1:\n result = 'Medium'\n else:\n result = 'High'\n fin_output = result\n print(fin_output)\n return render_template('index.html', prediction_text=fin_output)\n\n\nif __name__ == \"__main__\":\n app.run(port=5000, debug=True)\n","sub_path":"P31-Classification-Project-Incident Prediction/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"286931158","text":"import pygame\n\n\nclass Water(pygame.sprite.Sprite):\n def __init__(self, x, screen):\n super().__init__()\n\n self.screen = screen\n\n self.image = pygame.image.load('images/water.png').convert_alpha()\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = self.screen.walking_area - 4\n\n def update(self, move):\n self.rect.x -= move\n\n if self.rect.right < 0:\n self.kill()\n\n","sub_path":"HungryCatGame/sprites/water.py","file_name":"water.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"102625233","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n# Author = \"Hui_Yao\"\n\n'''守护进程:\n可通过设置p.deamon = True,将子进程设置成守护进程,守护进程有以下特性:\n 1. 当主进程执行完成后,守护进程也会死亡\n 2. 守护进程不能创建子进程。\n守护进程只可能在主进程的前面执行,不可能在后面执行。\n\n'''\n\nfrom multiprocessing import Process\nimport time\n\ndef mission(name,n):\n print('in the subprocess [{}]'.format(name))\n time.sleep(n)\n\np1 = Process(target=mission,args=(1,1))\np2 = Process(target=mission,args=(2,2))\n\np1.daemon = True\np1.start()\np2.start()\n\nprint('in the main process')\n\n'''\n可以看到,子进程2执行了,但子进程1没执行。\n原因代码向系统发了执行子进程1的信号后,还没来得及执行,主进程已经执行完了,没执行的子进程1就被杀死了。\n(有一种可能性是子进程2一发送信号就被执行了。)\n而子进程2不管主进程是否执行完,都会被执行。\n\n\n'''\n\n\n\n\n","sub_path":"python_note/01_学习总结/06_并发编程/01_进程相关/06_守护进程.py","file_name":"06_守护进程.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"42609826","text":"# str=\"Hello world in this summer\"\n# s1=str.split()\n# print(s1)\n# s2=' '.join(s1[1:])\n# print(s2)\n\n# dic={}\n# dic[\"ans\"]=\"hello\"\n# dic[\"yay\"]=\"world\"\n# if(\"he\" not in dic):\n# print(True)\n# if(\"yay\" in dic):\n# print(True)\n\ndef takeInput():\n ans=input()\n ans1=ans+'1'\n ans2=ans+'2'\n return ans1,ans2\nl1,l2=takeInput()\nprint(l1,\"----------\",l2)","sub_path":"Simple-Assembler/old/practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"453738473","text":"\"\"\"\nfunctions related to running Gemini3D.\nEither locally (laptop or interactive HPC) or creating an HPC batch script based on template.\n\"\"\"\n\nfrom __future__ import annotations\nimport typing as T\nimport os\nimport logging\nimport subprocess\nimport shutil\nfrom pathlib import Path, PurePosixPath\nimport numpy as np\n\nfrom . import find\nfrom .hpc import hpc_batch_detect, hpc_batch_create\nfrom . import model\nfrom . import write\nfrom . import read\nfrom . import wsl\nfrom .utils import git_meta\n\ntry:\n from math import prod\nexcept ImportError:\n # python < 3.8\n from numpy import prod # type: ignore\n\n\ndef runner(pr: dict[str, T.Any]) -> None:\n out_dir = check_outdir(pr[\"out_dir\"])\n\n config_file = find.config(pr[\"config_file\"])\n # load configuration to know what directories to check\n p = read.config(config_file)\n\n # we don't want to overwrite an expensive simulation output\n try:\n find.frame(out_dir, p[\"time\"][0])\n raise FileExistsError(\n f\"new simulation shouldn't have data in output directory: {out_dir}\"\n )\n except FileNotFoundError:\n pass\n\n # %% setup grid and/or initial ionosphere state if needed\n for k in {\"indat_size\", \"indat_grid\", \"indat_file\"}:\n f = out_dir / p[k].expanduser()\n if pr.get(\"force\") or not f.is_file():\n model.setup(p[\"nml\"], out_dir)\n\n # %% estimate simulation RAM use on root MPI node\n ram_use_bytes = memory_estimate(out_dir)\n\n # %% setup Efield if needed\n if \"E0dir\" in p:\n E0dir = out_dir / p[\"E0dir\"]\n if not E0dir.is_dir():\n model.setup(p[\"nml\"], out_dir)\n\n # %% setup precip if needed\n if \"precdir\" in p:\n precdir = out_dir / p[\"precdir\"]\n if not precdir.is_dir():\n model.setup(p[\"nml\"], out_dir)\n\n # build checks\n gemexe = find.gemini_exe(pr.get(\"gemexe\", \"\"))\n logging.info(f\"gemini executable: {gemexe}\")\n\n if os.name == \"nt\" and isinstance(gemexe, PurePosixPath):\n cmd = [\"wsl\", str(gemexe), str(wsl.win_path2wsl_path(out_dir))]\n else:\n cmd = [str(gemexe), str(out_dir)]\n\n # %% attempt dry run, but don't fail in case intended for HPC\n logging.info(\"Gemini dry run command:\")\n logging.info(\" \".join(cmd))\n proc = subprocess.run(cmd + [\"-dryrun\"])\n\n if proc.returncode != 0:\n raise RuntimeError(f\"Gemini dry run failed. {' '.join(cmd)}\")\n\n if pr.get(\"dryrun\"):\n return None\n\n write.meta(out_dir / \"setup_run.json\", git_meta(gemexe.parent), p)\n\n batcher = hpc_batch_detect()\n if batcher:\n job_file = hpc_batch_create(batcher, out_dir, cmd)\n print(\n \"Please examine batch file\",\n job_file,\n \"and when ready submit the job as usual.\",\n )\n return None\n\n try:\n import psutil\n\n avail_memory = psutil.virtual_memory().available\n if avail_memory < 2 * ram_use_bytes:\n logging.warning(\n f\"\"\"\nComputer RAM available: {avail_memory/1e9:.1} GB but simulation needs {ram_use_bytes/1e9:.1}\nGemini3D may run out of RAM on this computer, which may make the run exceedingly slow or fail.\n\"\"\"\n )\n except ImportError:\n pass\n\n print(\"\\nBEGIN Gemini run with command:\")\n print(\" \".join(cmd), \"\\n\")\n ret = subprocess.run(cmd).returncode\n if ret != 0:\n raise RuntimeError(\"Gemini run failed\")\n\n\ndef memory_estimate(path: Path) -> int:\n \"\"\"\n Estimate how must RAM Gemini3D will need.\n The current Gemini MPI architecture assumes the root node will use the most RAM,\n so that is the fundamental constraint.\n This neglects size of executable and library footprint,\n which would be minuscule in simulations larger than 1 GB where we\n are concerned about RAM limits.\n\n Parameters\n ----------\n\n path: pathlib.Path\n path to simgrid.*\n\n Returns\n -------\n\n memory_used: int\n estimated RAM usage (bytes)\n\n \"\"\"\n\n SIZE = 8 # number of bytes for each element: real64 => 8 bytes\n PAD = 2 # factor to assume needed over variable itself (computations, work variables, ...)\n\n gs = read.grid(path, shape=True)\n\n grid_size = 0\n\n for k, v in gs.items():\n if k == \"lx\" or not isinstance(v, (tuple, list, np.ndarray)) or not v:\n continue\n print(k, v, grid_size)\n grid_size += int(prod(v))\n\n LSP = 7\n x1 = gs[\"x1\"][0]\n x2 = gs[\"x2\"][0]\n x3 = gs[\"x3\"][0]\n\n Ns = LSP * x1 * x2 * x3\n Ts = Ns\n\n memory_used = SIZE * (grid_size + (Ns + Ts) * PAD)\n\n return memory_used\n\n\ndef check_compiler():\n fc = os.environ.get(\"FC\")\n fc = shutil.which(fc) if fc else shutil.which(\"gfortran\")\n if not fc:\n raise EnvironmentError(\"Cannot find Fortran compiler e.g. Gfortran\")\n\n\ndef check_mpiexec(mpiexec: str, gemexe: Path) -> str:\n \"\"\"\n check if specified mpiexec exists on this system.\n If not, error as most runs are exceedingly slow with one CPU core.\n \"\"\"\n\n if not mpiexec:\n mpiexec = \"mpiexec\"\n\n mpi_root = os.environ.get(\"MPI_ROOT\", None)\n if mpi_root:\n mpi_root += \"/bin\"\n\n mpiexec = shutil.which(mpiexec, path=mpi_root)\n if not mpiexec:\n raise FileNotFoundError(f\"Cannot find mpiexec {mpiexec}\")\n\n ret = subprocess.run([mpiexec, \"-help\"], capture_output=True, text=True, timeout=5)\n if ret.returncode != 0:\n raise RuntimeError(f\"MPIexec error code {ret.returncode}\\n{ret.stderr}\")\n # %% check that compiler and MPIexec compatible\n if os.name != \"nt\":\n return mpiexec\n\n mpi_msg = ret.stdout.strip()\n ret = subprocess.run(\n [str(gemexe), \"-compiler\"],\n capture_output=True,\n text=True,\n timeout=5,\n )\n if ret.returncode != 0:\n raise RuntimeError(f\"{gemexe} not executable\")\n\n if \"GNU\" in ret.stdout.strip() and \"Intel(R) MPI Library\" in mpi_msg:\n raise EnvironmentError(\"MPIexec from MinGW is not compatible with Intel MPI\")\n\n return mpiexec\n\n\ndef check_outdir(out_dir: str | Path) -> Path:\n out_dir = Path(out_dir).expanduser().resolve()\n if out_dir.is_file():\n raise NotADirectoryError(\n f\"please specify output DIRECTORY, you specified {out_dir}\"\n )\n if not out_dir.is_dir():\n out_dir.mkdir(parents=True, exist_ok=True)\n\n return out_dir\n","sub_path":"src/gemini3d/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":6330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649445584","text":"import logging\nimport os\nimport platform\nimport threading\nfrom contextlib import AsyncExitStack\nfrom dataclasses import dataclass, field\nfrom datetime import datetime, timedelta, timezone, tzinfo\nfrom traceback import format_exc\nfrom typing import Any, Callable, Dict, Iterable, Mapping, Optional, Set, Union\nfrom uuid import uuid4\n\nimport tzlocal\nfrom anyio import create_event, create_task_group, move_on_after\nfrom anyio.abc import Event\n\nfrom ..abc import DataStore, EventHub, EventSource, Executor, Job, Schedule, Task, Trigger\nfrom ..datastores.memory import MemoryScheduleStore\nfrom ..eventhubs.local import LocalEventHub\nfrom ..events import JobSubmissionFailed, SchedulesAdded, SchedulesUpdated\nfrom ..marshalling import callable_to_ref\nfrom ..validators import as_timezone\nfrom ..workers.local import LocalExecutor\n\n\n@dataclass\nclass AsyncScheduler(EventSource):\n schedule_store: DataStore = field(default_factory=MemoryScheduleStore)\n worker: Executor = field(default_factory=LocalExecutor)\n timezone: tzinfo = field(default_factory=tzlocal.get_localzone)\n identity: str = f'{platform.node()}-{os.getpid()}-{threading.get_ident()}'\n logger: logging.Logger = field(default_factory=lambda: logging.getLogger(__name__))\n _event_hub: EventHub = field(init=False, default_factory=LocalEventHub)\n _tasks: Dict[str, Task] = field(init=False, default_factory=dict)\n _async_stack: AsyncExitStack = field(init=False, default_factory=AsyncExitStack)\n _next_fire_time: Optional[datetime] = field(init=False, default=None)\n _wakeup_event: Optional[Event] = field(init=False, default=None)\n _closed: bool = field(init=False, default=False)\n\n def __post_init__(self):\n self.timezone = as_timezone(self.timezone)\n\n async def __aenter__(self):\n await self._async_stack.__aenter__()\n task_group = create_task_group()\n await self._async_stack.enter_async_context(task_group)\n await task_group.spawn(self.run)\n return self\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n await self._async_stack.__aexit__(exc_type, exc_val, exc_tb)\n\n def _get_taskdef(self, func_or_id: Union[str, Callable]) -> Task:\n task_id = func_or_id if isinstance(func_or_id, str) else callable_to_ref(func_or_id)\n taskdef = self._tasks.get(task_id)\n if not taskdef:\n if isinstance(func_or_id, str):\n raise LookupError('no task found with ID {!r}'.format(func_or_id))\n else:\n taskdef = self._tasks[task_id] = Task(id=task_id, func=func_or_id)\n\n return taskdef\n\n def define_task(self, func: Callable, task_id: Optional[str] = None, **kwargs):\n if task_id is None:\n task_id = callable_to_ref(func)\n\n task = Task(id=task_id, **kwargs)\n if self._tasks.setdefault(task_id, task) is not task:\n pass\n\n async def add_schedule(\n self, task: Union[str, Callable], trigger: Trigger, *, id: Optional[str] = None,\n args: Optional[Iterable] = None, kwargs: Optional[Mapping[str, Any]] = None,\n coalesce: bool = True, misfire_grace_time: Union[float, timedelta, None] = None,\n tags: Optional[Iterable[str]] = None\n ) -> str:\n id = id or str(uuid4())\n args = tuple(args or ())\n kwargs = dict(kwargs or {})\n tags = frozenset(tags or ())\n if isinstance(misfire_grace_time, (int, float)):\n misfire_grace_time = timedelta(seconds=misfire_grace_time)\n\n taskdef = self._get_taskdef(task)\n schedule = Schedule(id=id, task_id=taskdef.id, trigger=trigger, args=args, kwargs=kwargs,\n coalesce=coalesce, misfire_grace_time=misfire_grace_time, tags=tags,\n next_fire_time=trigger.next())\n await self.schedule_store.add_or_replace_schedules([schedule])\n self.logger.info('Added new schedule for task %s; next run time at %s', taskdef,\n schedule.next_fire_time)\n return schedule.id\n\n async def remove_schedule(self, schedule_id: str) -> None:\n await self.schedule_store.remove_schedules({schedule_id})\n\n async def _handle_worker_event(self, event: Event) -> None:\n await self._event_hub.publish(event)\n\n async def _handle_datastore_event(self, event: Event) -> None:\n if isinstance(event, (SchedulesAdded, SchedulesUpdated)):\n # Wake up the scheduler if any schedule has an earlier next fire time than the one\n # we're currently waiting for\n if event.earliest_next_fire_time:\n if (self._next_fire_time is None\n or self._next_fire_time > event.earliest_next_fire_time):\n self.logger.debug('Job store reported an updated next fire time that requires '\n 'the scheduler to wake up: %s',\n event.earliest_next_fire_time)\n await self.wakeup()\n\n await self._event_hub.publish(event)\n\n async def _process_schedules(self):\n async with self.schedule_store.acquire_due_schedules(\n self.identity, datetime.now(timezone.utc)) as schedules:\n schedule_ids_to_remove: Set[str] = set()\n schedule_updates: Dict[str, Dict[str, Any]] = {}\n for schedule in schedules:\n # Look up the task definition\n try:\n taskdef = self._get_taskdef(schedule.task_id)\n except LookupError:\n self.logger.error('Cannot locate task definition %r for schedule %r – '\n 'removing schedule', schedule.task_id, schedule.id)\n schedule_ids_to_remove.add(schedule.id)\n continue\n\n # Calculate a next fire time for the schedule, if possible\n try:\n next_fire_time = schedule.trigger.next()\n except Exception:\n self.logger.exception('Error computing next fire time for schedule %r of task '\n '%r – removing schedule', schedule.id, taskdef.id)\n next_fire_time = None\n\n # Queue a schedule update if a next fire time could be calculated.\n # Otherwise, queue the schedule for removal.\n if next_fire_time:\n schedule_updates[schedule.id] = {\n 'next_fire_time': next_fire_time,\n 'last_fire_time': schedule.next_fire_time,\n 'trigger': schedule.trigger\n }\n else:\n schedule_ids_to_remove.add(schedule.id)\n\n # Submit a new job to the executor\n job = Job(taskdef.id, taskdef.func, schedule.args, schedule.kwargs, schedule.id,\n schedule.last_fire_time, schedule.next_deadline, schedule.tags)\n try:\n await self.worker.submit_job(job)\n except Exception as exc:\n self.logger.exception('Error submitting job to worker')\n event = JobSubmissionFailed(datetime.now(self.timezone), job.id, job.task_id,\n job.schedule_id, job.scheduled_start_time,\n formatted_traceback=format_exc(), exception=exc)\n await self._event_hub.publish(event)\n\n # Removed finished schedules\n if schedule_ids_to_remove:\n await self.schedule_store.remove_schedules(schedule_ids_to_remove)\n\n # Update the next fire times\n if schedule_updates:\n await self.schedule_store.update_schedules(schedule_updates)\n\n return await self.schedule_store.get_next_fire_time()\n\n async def run(self):\n async with AsyncExitStack() as stack:\n await stack.enter_async_context(self.schedule_store)\n await stack.enter_async_context(self.worker)\n await self.worker.subscribe(self._handle_worker_event)\n await self.schedule_store.subscribe(self._handle_datastore_event)\n self._wakeup_event = create_event()\n while not self._closed:\n self._next_fire_time = await self._process_schedules()\n\n if self._next_fire_time:\n wait_time = (self._next_fire_time - datetime.now(timezone.utc)).total_seconds()\n else:\n wait_time = float('inf')\n\n self._wakeup_event = create_event()\n async with move_on_after(wait_time):\n await self._wakeup_event.wait()\n\n async def wakeup(self) -> None:\n await self._wakeup_event.set()\n\n async def shutdown(self, force: bool = False) -> None:\n if not self._closed:\n self._closed = True\n await self.wakeup()\n\n async def subscribe(self, callback: Callable[[Event], Any]) -> None:\n await self._event_hub.subscribe(callback)\n","sub_path":"apscheduler/schedulers/async_.py","file_name":"async_.py","file_ext":"py","file_size_in_byte":9131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"168166258","text":"\"\"\"server.\"\"\"\nimport argparse\nimport numpy as np\nfrom bottle import run, route, request\n\n\n@route('/post_file', method='POST')\ndef post_file():\n a = request.params.file_data.split()\n b = [row.split(',') for row in a]\n print(np.array(b))\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='post file test.')\n parser.add_argument('--host', default='0.0.0.0', help='Server address')\n parser.add_argument('--port', default=8080, type=int, help='Server port')\n\n args = parser.parse_args()\n run(host=args.host, port=args.port, debug=False, reloader=False)\n","sub_path":"js/file/post_file/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"387059744","text":"'''\n功能:\n 电费信息爬取与存储\n {输入}已经打开到指定页面的webdriver\n {输出}\n\n============================================================================\npakuzhou,2018-08-05\n'''\n\nimport csv\nimport time\nimport datetime\nfrom selenium import webdriver\n# ---------------------------\nfrom GetLeft import getLeft\n\n\ndef elecCrawler(driver_got):\n elecInfoList = []\n dormInfoList = []\n\n # 从用户表中读取用户宿舍信息\n with open('users.csv','r') as f:\n f_csv = csv.DictReader(f)\n for row in f_csv:\n dormInfo = {}\n # print(row)\n # row = dict(row)\n # print(row)\n # print(type(row))\n dormInfo['xq'] = row['xq']\n dormInfo['lou'] = row['lou']\n dormInfo['room'] = row['room']\n dormInfo['nick'] = row['nick']\n dormInfo['code'] = row['dormCode']\n dormInfoList.append(dormInfo)\n\n # 根据用户宿舍信息爬取电费信息\n for dormInfo in dormInfoList:\n time.sleep(0.4)\n err,elecDic = getLeft(dormInfo,driver_got)\n if err == 0:#查询正常\n elecDic['time'] = datetime.date.today()\n elecDic['dormCode'] = dormInfo['code']\n elecDic['nick'] = dormInfo['nick']\n elecInfoList.append(elecDic)\n else:\n # 此时发生错误为网络问题,等待之后继续\n time.sleep(5)\n\n\n # 将电费信息储存至电费表\n elecHeaders = ['time','nick','dormCode','money','elec']\n with open('elec.csv','a') as f:\n f_csv = csv.DictWriter(f,elecHeaders)\n f_csv.writerows(elecInfoList)\n # 将电费保存至日更电费表\n elecHeaders = ['time','nick','dormCode','money','elec']\n today = str(datetime.date.today())\n with open('./ElecData/'+ today+'.csv','w') as f:\n f_csv = csv.writer(f)\n f_csv.writerow(elecHeaders)\n with open('./ElecData/'+ today+'.csv','a') as f:\n f_csv = csv.DictWriter(f,elecHeaders)\n f_csv.writerows(elecInfoList)\n\nif __name__ == '__main__':\n driver = webdriver.Chrome()\n driver.get('http://elec.xmu.edu.cn/PdmlWebSetup/Pages/SMSMain.aspx')\n\n elecCrawler(driver)\n driver.close()\n","sub_path":"H2X/PacooBot/ElecCrawler.py","file_name":"ElecCrawler.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"202291682","text":"from __future__ import division, absolute_import, print_function\nfrom CPIncomp.WriterObjects import SolutionDataWriter\nfrom CPIncomp import getExampleNames, getPureFluids, getCoefficientFluids,\\\n getDigitalFluids, getSecCoolFluids, getMelinderFluids\nimport sys\nfrom CPIncomp.DataObjects import SolutionData\n\n\nif __name__ == '__main__': \n \n runTest = False \n runFitting = True\n runReports = True\n runSummary = True\n \n writer = SolutionDataWriter()\n doneObjs = []\n \n # To debug single fluids\n if runTest:\n solObjs = []\n from CPIncomp.SecCoolFluids import SecCoolSolutionData,SecCoolIceData,ThermogenVP1869\n from CPIncomp.PureFluids import Texatherm22\n solObjs += [SecCoolSolutionData(sFile='Melinder, Ammonia' ,sFolder='xMass',name='MAM2',desc='Melinder, Ammonia' ,ref='Melinder-BOOK-2010, SecCool software')]\n solObjs += [SecCoolIceData(sFile='IceNA' ,sFolder='xMass',name='IceNA',desc='Ice slurry with NaCl' ,ref='Danish Technological Institute, SecCool software')]\n #solObjs = [Freezium()]\n #solObjs[0].density.DEBUG = True\n #solObjs[0].specific_heat.DEBUG = True\n #solObjs[0].conductivity.DEBUG = True\n #solObjs[0].viscosity.DEBUG = True\n #solObjs[0].T_freeze.DEBUG = True\n #writer.fitSecCoolList(solObjs)\n solObjs = [ThermogenVP1869()]#,Therminol72()]\n solObjs[0].viscosity.DEBUG=True\n #solObjs[0].saturation_pressure.DEBUG=True\n #\n ##from CPIncomp.ExampleObjects import SecCoolExample\n ##solObjs = [SecCoolExample()]\n #writer.fitFluidList(solObjs)\n writer.fitSecCoolList(solObjs)\n writer.writeFluidList(solObjs)\n writer.writeReportList(solObjs)\n sys.exit(0)\n \n # treat the examples first\n fluidObjs = getExampleNames(obj=True)\n examplesToFit = [\"ExamplePure\",\"ExampleSolution\",\"ExampleDigital\",\"ExampleDigitalPure\"]\n \n print(\"\\nProcessing example fluids\")\n for obj in fluidObjs:\n if obj.name in examplesToFit:\n if runFitting: writer.fitAll(obj)\n else: writer.fromJSON(obj)\n doneObjs += fluidObjs[:]\n if runFitting: writer.writeFluidList(doneObjs)\n if runReports: writer.writeReportList(doneObjs, pdfFile=\"all_examples.pdf\")\n \n # If the examples did not cause any errors, \n # we can proceed to the real data.\n doneObjs = []\n \n print(\"\\nProcessing fluids with given coefficients\")\n fluidObjs = getCoefficientFluids()\n doneObjs += fluidObjs[:]\n\n print(\"\\nProcessing digital fluids\")\n fluidObjs = getDigitalFluids()\n if runFitting: writer.fitFluidList(fluidObjs)\n else: writer.readFluidList(fluidObjs)\n doneObjs += fluidObjs[:]\n \n print(\"\\nProcessing Melinder fluids\")\n fluidObjs = getMelinderFluids()\n doneObjs += fluidObjs[:]\n \n print(\"\\nProcessing pure fluids\")\n fluidObjs = getPureFluids()\n if runFitting: writer.fitFluidList(fluidObjs)\n else: writer.readFluidList(fluidObjs)\n doneObjs += fluidObjs[:]\n\n print(\"\\nProcessing SecCool fluids\")\n fluidObjs = getSecCoolFluids()\n if runFitting: writer.fitSecCoolList(fluidObjs)\n else: writer.readFluidList(fluidObjs)\n doneObjs += fluidObjs[:]\n \n print(\"\\nAll {0} fluids processed, all coefficients should be set.\".format(len(doneObjs)))\n print(\"Checking the list of fluid objects.\")\n #doneObjs += getCoefficientObjects()[:]\n doneObjs = sorted(doneObjs, key=lambda x: x.name)\n \n purefluids = []\n solMass = []\n solMole = []\n solVolu = []\n errors = []\n for i in range(len(doneObjs)-1):\n if doneObjs[i].name==doneObjs[i+1].name:\n print(\"Conflict between {0} and {1}, aborting\".format(doneObjs[i],doneObjs[i+1]))\n raise ValueError(\"Two elements have the same name, that does not work: {0}\".format(doneObjs[i].name))\n else:\n if doneObjs[i].xid==SolutionData.ifrac_mass:\n solMass += [doneObjs[i]]\n elif doneObjs[i].xid==SolutionData.ifrac_mole:\n solMole += [doneObjs[i]]\n elif doneObjs[i].xid==SolutionData.ifrac_volume:\n solVolu += [doneObjs[i]]\n elif doneObjs[i].xid==SolutionData.ifrac_pure:\n purefluids += [doneObjs[i]]\n else: \n errors += [doneObjs[i]]\n solutions = solMass\n solutions += solMole\n solutions += solVolu\n \n if runFitting: print(\"All checks passed, going to write parameters to disk.\")\n if runFitting: writer.writeFluidList(doneObjs)\n \n if runReports: \n print(\"Creating the fitting reports for the different groups.\")\n #writer.writeReportList(doneObjs)\n #doneObjs.sort(key=lambda x: (x.xid ,x.name))\n if len(purefluids)>0 and runReports:\n print(\"Processing {0:2d} pure fluids - \".format(len(purefluids)), end=\"\")\n writer.writeReportList(purefluids, pdfFile=\"all_pure.pdf\")\n if len(solutions)>0 and runReports:\n print(\"Processing {0:2d} solutions - \".format(len(solutions)), end=\"\")\n writer.writeReportList(solutions, pdfFile=\"all_solutions.pdf\") \n if len(errors)>0 and runReports:\n print(\"Processing {0:2d} faulty fluids - \".format(len(errors)), end=\"\")\n writer.writeReportList(errors, pdfFile=\"all_errors.pdf\")\n \n if runSummary:\n writer.makeSolutionPlots(solObjs=doneObjs, pdfObj=None)\n\n print(\"All done, bye\")\n sys.exit(0)\n\n ","sub_path":"dev/incompressible_liquids/all_incompressibles.py","file_name":"all_incompressibles.py","file_ext":"py","file_size_in_byte":5559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"11998243","text":"import pandas as pd\nimport numpy as np\n\npd.set_option(\"display.max_rows\", 10)\npd.set_option(\"display.max_columns\", 101)\n\ndf = pd.read_csv(\"Titanic.csv\")\n\n# see columns\ndf.columns\n\n# drop columns we won't use\ndf = df.drop(['PassengerId', 'Name', 'Ticket'], axis=1)\n\ndf.columns\n\n# recompute HasCabin\ndf.loc[df.Cabin.isnull()]\ndf['HasCabin'] = np.nan\ndf.loc[df.Cabin.notnull(), 'HasCabin'] = 1\ndf.loc[df.Cabin.isnull(), 'HasCabin'] = 0\ndf.HasCabin.value_counts()\ndf = df.drop(['Cabin'], axis=1)\ndf\n\n# add dummy variables - change categorial vars into text\nembarked = pd.get_dummies(df.Embarked, prefix='Embarked_')\nembarked\n \nsex = pd.get_dummies(df.Sex, prefix='Sex_')\nsex\n\n\ndf = df.join(embarked)\ndf = df.join(sex)\ndf\n\nvars_to_drop = ['Sex','Embarked']\ndf = df.drop(vars_to_drop, axis=1)\n\n\n# keep only complete cases\ndf = df.dropna(axis=0)\ndf\n\ndf.to_csv(\"Titanic_Clean.csv\", index=False)\n","sub_path":"data_science/titanic/clean_and_explore.py","file_name":"clean_and_explore.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"272995243","text":"from django.core.management.base import BaseCommand\nfrom firecares.firestation.models import FireDepartment\n\n\nclass Command(BaseCommand):\n \"\"\"\n This command is used to export data that department heat maps visualize.\n \"\"\"\n\n help = 'Creates a sql file to export building fires from.'\n\n def handle(self, *args, **options):\n vals = FireDepartment.objects.filter(fdid__isnull=False, state__isnull=False).exclude(fdid__exact='')\n\n sql = \"\"\"\n \\COPY (select alarm, a.inc_type, alarms,ff_death, oth_death, ST_X(geom) as x, st_y(geom) as y from buildingfires a left join incidentaddress b using (state, inc_date, exp_no, fdid, inc_no) where state='{state}' and fdid='{fdid}') to PROGRAM 'aws s3 cp - s3://firecares-pipeline/heatmaps/{id}-building-fires.csv --acl=\\\"public-read\\\"' DELIMITER ',' CSV HEADER;\n \"\"\"\n\n for fd in vals:\n self.stdout.write(sql.format(fdid=fd.fdid, state=fd.state, id=fd.id) + '\\n')","sub_path":"firecares/firestation/management/commands/export-building-fires.py","file_name":"export-building-fires.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"156103911","text":"#!/usr/bin/env python\n# (C) 2017 OpenEye Scientific Software Inc. All rights reserved.\n#\n# TERMS FOR USE OF SAMPLE CODE The software below (\"Sample Code\") is\n# provided to current licensees or subscribers of OpenEye products or\n# SaaS offerings (each a \"Customer\").\n# Customer is hereby permitted to use, copy, and modify the Sample Code,\n# subject to these terms. OpenEye claims no rights to Customer's\n# modifications. Modification of Sample Code is at Customer's sole and\n# exclusive risk. Sample Code may require Customer to have a then\n# current license or subscription to the applicable OpenEye offering.\n# THE SAMPLE CODE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT\n# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall OpenEye be\n# liable for any damages or liability in connection with the Sample Code\n# or its use.\n\nfrom openeye import oechem\nfrom openeye import oedepict\n\n###############################################################\n# USED TO GENERATE CODE SNIPPETS FOR THE OEDEPICT DOCUMENTATION\n###############################################################\n\n\ndef WriteTable(tableoptions, basefilename):\n\n image = oedepict.OEImage(300, 200)\n table = oedepict.OEImageTable(image, tableoptions)\n\n for idx, cell in enumerate(table.GetHeaderCells()):\n table.DrawText(cell, \"(header %d)\" % (idx + 1))\n\n for idx, cell in enumerate(table.GetStubColumnCells()):\n table.DrawText(cell, \"(stub %d)\" % (idx + 1))\n\n onlybody = True\n for row in range(1, table.NumRows(onlybody) + 1):\n for col in range(1, table.NumColumns(onlybody) + 1):\n cell = table.GetBodyCell(row, col)\n table.DrawText(cell, \"(body %d, %d)\" % (row, col))\n\n oedepict.OEDrawBorder(image, oedepict.OELightGreyPen)\n oedepict.OEWriteImage(basefilename + \".png\", image)\n oedepict.OEWriteImage(basefilename + \".pdf\", image)\n\n\n# @ \ntableopts = oedepict.OEImageTableOptions(4, 4, oedepict.OEImageTableStyle_MediumBlue)\n# @ \nWriteTable(tableopts, \"OEImageTableOptions_Default\")\n\n# @ \ntableopts = oedepict.OEImageTableOptions(4, 4, oedepict.OEImageTableStyle_MediumBlue)\ntableopts.SetColumnWidths([20, 10, 20, 10])\n# @ \nWriteTable(tableopts, \"OEImageTableOptions_SetColumnWidths\")\n\n# @ \ntableopts = oedepict.OEImageTableOptions(4, 4, oedepict.OEImageTableStyle_MediumBlue)\ntableopts.SetRowHeights([10, 20, 30, 40])\n# @ \nWriteTable(tableopts, \"OEImageTableOptions_SetRowHeights\")\n\n# @ \ntableopts = oedepict.OEImageTableOptions(4, 4, oedepict.OEImageTableStyle_MediumBlue)\ntableopts.SetBaseFontSize(6)\n# @ \nWriteTable(tableopts, \"OEImageTableOptions_SetBaseFontSize\")\n\n# @ \ntableopts = oedepict.OEImageTableOptions(4, 4, oedepict.OEImageTableStyle_MediumBlue)\npen = oedepict.OEPen(oechem.OEBlack, oechem.OEDarkBlue, oedepict.OEFill_Off, 2.0)\ntableopts.SetCellBorderPen(pen)\n# @ \nWriteTable(tableopts, \"OEImageTableOptions_SetCellBorderPen\")\n\n# @ \ntableopts = oedepict.OEImageTableOptions(4, 4, oedepict.OEImageTableStyle_MediumBlue)\nevenrow = True\ntableopts.SetCellColor(oechem.OELightGrey, not evenrow)\n# @ \nWriteTable(tableopts, \"OEImageTableOptions_SetCellColor\")\n\n# @ \ntableopts = oedepict.OEImageTableOptions(4, 4, oedepict.OEImageTableStyle_MediumBlue)\nfont = oedepict.OEFont(oedepict.OEFontFamily_Default,\n oedepict.OEFontStyle_Italic | oedepict.OEFontStyle_Bold,\n 8, oedepict.OEAlignment_Left, oechem.OEDarkRed)\ntableopts.SetCellFont(font)\n# @ \nWriteTable(tableopts, \"OEImageTableOptions_SetCellFont\")\n\n# @ \ntableopts = oedepict.OEImageTableOptions(4, 4, oedepict.OEImageTableStyle_MediumBlue)\ntableopts.SetHeader(False)\n# @ \nWriteTable(tableopts, \"OEImageTableOptions_SetHeader\")\n\n# @ \ntableopts = oedepict.OEImageTableOptions(4, 4, oedepict.OEImageTableStyle_MediumBlue)\ntableopts.SetHeaderColor(oechem.OELightGrey)\n# @ \nWriteTable(tableopts, \"OEImageTableOptions_SetHeaderColor\")\n\n# @ \ntableopts = oedepict.OEImageTableOptions(4, 4, oedepict.OEImageTableStyle_MediumBlue)\nfont = oedepict.OEFont(oedepict.OEFontFamily_Default, oedepict.OEFontStyle_Default, 12,\n oedepict.OEAlignment_Right, oechem.OEPinkTint)\ntableopts.SetHeaderFont(font)\n# @ \nWriteTable(tableopts, \"OEImageTableOptions_SetHeaderFont\")\n\n# @ \ntableopts = oedepict.OEImageTableOptions(4, 4, oedepict.OEImageTableStyle_MediumBlue)\ntableopts.SetMargin(oedepict.OEMargin_Left, 10.0)\ntableopts.SetMargin(oedepict.OEMargin_Right, 10.0)\n# @ \nWriteTable(tableopts, \"OEImageTableOptions_SetMargin\")\n\n# @ \ntableopts = oedepict.OEImageTableOptions(4, 4, oedepict.OEImageTableStyle_MediumBlue)\ntableopts.SetMargins(10.0)\n# @ \nWriteTable(tableopts, \"OEImageTableOptions_SetMargins\")\n\n# @ \ntableopts = oedepict.OEImageTableOptions(4, 4, oedepict.OEImageTableStyle_MediumBlue)\ntableopts.SetStubColumn(True)\n# @ >\nWriteTable(tableopts, \"OEImageTableOptions_SetStubColumn\")\n\n# @ \ntableopts = oedepict.OEImageTableOptions(4, 4, oedepict.OEImageTableStyle_MediumBlue)\ntableopts.SetStubColumn(True)\ntableopts.SetStubColumnColor(oechem.OELightGrey)\n# @ \nWriteTable(tableopts, \"OEImageTableOptions_SetStubColumnColor\")\n\n# @ \ntableopts = oedepict.OEImageTableOptions(4, 4, oedepict.OEImageTableStyle_MediumBlue)\ntableopts.SetStubColumn(True)\nfont = oedepict.OEFont(oedepict.OEFontFamily_Default, oedepict.OEFontStyle_Default, 12,\n oedepict.OEAlignment_Right, oechem.OEPinkTint)\ntableopts.SetStubColumnFont(font)\n# @ \nWriteTable(tableopts, \"OEImageTableOptions_SetStubColumnFont\")\n","sub_path":"venv/Lib/site-packages/openeye/docexamples/depict/OEImageTableOpts_SetProps.py","file_name":"OEImageTableOpts_SetProps.py","file_ext":"py","file_size_in_byte":6899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"389425640","text":"#!/usr/bin/env python3\n############## ROS Import ###############\nimport rospy\nimport std_msgs\nfrom sensor_msgs.msg import Image\n\nimport numpy as np\nimport random\nimport time\nimport itertools\nimport os\nimport cv2\nfrom cv_bridge import CvBridge, CvBridgeError\n\n#import jetson.inference\n#import jetson.utils\n\n#net = jetson.inference.detectNet(\"ssd-mobilenet-v2\")\n\n\nimport tensorflow as tf\n\npath_raw_video = '/home/kimbring2/Desktop/raw_video.avi'\npath_styled_video = '/home/kimbring2/Desktop/styled_video.avi'\nfps = 5\nsize = (512,512)\n\nraw_video_out = cv2.VideoWriter(path_raw_video, cv2.VideoWriter_fourcc(*'DIVX'), fps, (1280,720))\nstyled_video_out = cv2.VideoWriter(path_styled_video, cv2.VideoWriter_fourcc(*'DIVX'), fps, (128,128))\n\nimported_rl = tf.saved_model.load(\"/home/kimbring2/Desktop/rl_model\")\nimported_style = tf.saved_model.load(\"/home/kimbring2/Desktop/style_model\")\n#imported_cyclegan = tf.saved_model.load(\"/home/kimbring2/Desktop/cyclegan_model\")\n\nf_rl = imported_rl.signatures[\"serving_default\"]\nf_style = imported_style.signatures[\"serving_default\"]\n#f_cyclegan = imported_cyclegan.signatures[\"serving_default\"]\n\nrl_test_input = np.zeros([1,128,128,5])\nstyle_test_input = np.zeros([1,256,256,3])\n#cyclegan_test_input = np.zeros([1,256,256,3])\n\nrl_test_tensor = tf.convert_to_tensor(rl_test_input, dtype=tf.float32)\nstyle_test_tensor = tf.convert_to_tensor(style_test_input, dtype=tf.float32)\n#cyclegan_test_tensor = tf.convert_to_tensor(cyclegan_test_input, dtype=tf.float32)\n\nprint(f_rl(rl_test_tensor)['dueling_model'].numpy()[0])\ntime.sleep(2)\nprint(f_style(style_test_tensor)['output_1'].numpy()[0])\n#print(f_cyclegan(cyclegan_test_tensor)['output_1'].numpy()[0])\n\nbridge = CvBridge()\n\ncamera_frame = np.zeros([128,128,3])\ndef image_callback(msg):\n global camera_frame\n \n #print(\"image_callback\")\n cv_image = bridge.imgmsg_to_cv2(msg, \"passthrough\")\n #raw_video_out.write(cv_image)\n \n cv_image_shape = cv_image.shape\n #print(\"cv_image.shape: \" + str(cv_image.shape))\n width = cv_image_shape[1]\n height = cv_image_shape[0]\n \n cv_image = cv2.resize(cv_image, (256, 256), interpolation=cv2.INTER_AREA)\n cv_image = cv2.normalize(cv_image, None, 0, 1, cv2.NORM_MINMAX, cv2.CV_32F)\n #cv_image = cv2.cvtColor(cv_image, cv2.COLOR_RGB2RGBA).astype(np.float32)\n \n resized = np.array([cv_image])\n input_tensor = tf.convert_to_tensor(resized, dtype=tf.float32)\n output = f_style(input_tensor)['output_1'].numpy()[0]\n \n #camera_frame = cv2.resize(cv_image, (128, 128), interpolation=cv2.INTER_AREA)\n camera_frame = cv2.resize(output, (128, 128), interpolation=cv2.INTER_AREA)\n #print(\"camera_frame.shape: \" + str(camera_frame.shape))\n #print(\"\")\n #styled_video_out.write(np.uint8(camera_frame))\n #print(\"cv_image.shape: \" + str(cv_image.shape))\n #print(\"type(cv_image): \" + str(type(cv_image)))\n \n #cuda_image = jetson.utils.cudaFromNumpy(cv_image)\n #array = jetson.utils.cudaToNumpy(cuda_image, 720, 1280, 3)\n #jetson.utils.saveImageRGBA(\"cuda-from-numpy.jpg\", cuda_image, 720, 1280)\n #print(\"cv_image.shape: \" + str(cv_image.shape))\n #detections = net.Detect(cuda_image, width, height, \"box,labels,conf\")\n\n # print the detections\n #print(\"detected {:d} objects in image\".format(len(detections)))\n\n #for detection in detections:\n # print(detection)\n \n #cv2.imwrite(\"camera_frame.jpg\", camera_frame)\n #jetson.utils.saveImageRGBA(\"detected_image.jpg\", cv_image, width, height)\n\n\nlidar_value = 0\ndef lidar_callback(msg):\n global lidar_value\n \n lidar_value = msg.data\n #print(\"lidar: \" + str(msg))\n\n \ninfrared_value = 'False'\ndef infrared_callback(msg):\n global infrared_value\n \n infrared_value = msg.data\n #print(\"infrared: \" + str(msg))\n \n \n############## ROS Part ###############\nrospy.init_node('deepsoccer')\nwheel1 = rospy.Publisher('/deepsoccer_motors/cmd_str_wheel1', std_msgs.msg.String, queue_size=1)\nwheel2 = rospy.Publisher('/deepsoccer_motors/cmd_str_wheel2', std_msgs.msg.String, queue_size=1)\nwheel3 = rospy.Publisher('/deepsoccer_motors/cmd_str_wheel3', std_msgs.msg.String, queue_size=1)\nwheel4 = rospy.Publisher('/deepsoccer_motors/cmd_str_wheel4', std_msgs.msg.String, queue_size=1)\nsolenoid = rospy.Publisher('/deepsoccer_solenoid/cmd_str', std_msgs.msg.String, queue_size=5)\nroller = rospy.Publisher('/deepsoccer_roller/cmd_str', std_msgs.msg.String, queue_size=5)\nrospy.Subscriber(\"/deepsoccer_camera/raw\", Image, image_callback)\nrospy.Subscriber(\"/deepsoccer_lidar\", std_msgs.msg.String, lidar_callback)\nrospy.Subscriber(\"/deepsoccer_infrared\", std_msgs.msg.String, infrared_callback)\n \nrate = rospy.Rate(5000)\n\nstop_action = [0, 0, 0, 0, 'stop', 'none']\nforward_action = [50, 1074, 1074, 50, 'in', 'none']\nleft_action = [1074, 1074, 1074, 1074, 'in', 'none']\nright_action = [50, 50, 50, 50, 'in', 'out']\nbacward_action = [1074, 50, 50, 1074, 'in', 'none']\nhold_action = [0, 0, 0, 0, 'in', 'none']\nkick_action = [0, 0, 0, 0, 'stop', 'out']\nrun_action = [100, 1124, 1124, 100, 'stop', 'out']\nrobot_action_list = [stop_action, forward_action, left_action, right_action, bacward_action, hold_action, kick_action, run_action]\n\n\n############## ROS + Deep Learning Part ###############\nwhile not rospy.is_shutdown():\n #print(\"start\")\n \n action_index = 0\n #print(\"camera_frame.shape: \" + str(camera_frame.shape))\n #print(\"lidar_value: \" + str(lidar_value))\n lidar_ = int(lidar_value) / 1200\n print(\"lidar_: \" + str(lidar_))\n \n #print(\"infrared_value: \" + str(infrared_value))\n #print(\"type(infrared_value): \" + str(type(infrared_value)))\n infrared_ = int(infrared_value == 'True')\n print(\"infrared_: \" + str(infrared_))\n #print(\"action: \" + str(action))\n #print(\"\")\n \n frame_state_channel = camera_frame\n lidar_state_channel = (np.ones(shape=(128,128,1), dtype=np.float32)) * lidar_\n infrared_state_channel = (np.ones(shape=(128,128,1), dtype=np.float32)) * infrared_ / 2.0\n state_channel1 = np.concatenate((frame_state_channel, lidar_state_channel), axis=2)\n state_channel2 = np.concatenate((state_channel1, infrared_state_channel), axis=2)\n state_channel2 = np.array([state_channel2])\n #print(\"state_channel2.shape: \" + str(state_channel2.shape))\n \n state_channel_tensor = tf.convert_to_tensor(state_channel2, dtype=tf.float32)\n predict_value = f_rl(state_channel_tensor)['dueling_model'].numpy()[0]\n #print(\"predict_value: \" + str(predict_value))\n action_index = np.argmax(predict_value, axis=0)\n #action_index = 0\n print(\"action_index: \" + str(action_index))\n action = robot_action_list[action_index]\n \n wheel1_action = action[0]\n wheel2_action = action[1]\n wheel3_action = action[2]\n wheel4_action = action[3]\n roller_action = action[4]\n solenoid_action = action[5]\n \n wheel1.publish(str(wheel1_action))\n wheel2.publish(str(wheel2_action))\n wheel3.publish(str(wheel3_action))\n wheel4.publish(str(wheel4_action))\n roller.publish(roller_action)\n solenoid.publish(solenoid_action)\n \n #time.sleep(0.1)\n \nrate.sleep()","sub_path":"deepsoccer_jetson/scripts/deepsoccer_main.py","file_name":"deepsoccer_main.py","file_ext":"py","file_size_in_byte":7134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"109649500","text":"from elasticsearch_dsl.response import Hit\n\n\nclass DocumentsBy:\n @staticmethod\n def map_hit_with_score(hit: Hit) -> dict:\n document = hit.__dict__['_d_']\n document[\"id\"] = hit.meta.id\n document[\"score\"] = hit.meta.score\n return document\n\n @staticmethod\n def group_queries_by_operator(queries: list) -> dict:\n operators = [\"must\", \"must_not\", \"should\"]\n grouped_queries = {}\n for operator in operators:\n grouped_queries[operator] = []\n\n for query_operator, query in queries:\n for operator in operators:\n if operator == query_operator:\n grouped_queries[operator].append(query)\n continue\n\n return grouped_queries\n\n def corpus_text_document_indices(self, corpus_id: str) -> str:\n \"\"\"\n Get corpus indices wildcard for the corpus id and all languages.\n \"\"\"\n corpus = self.multi_corpus.corpus_from_id(corpus_id)\n return corpus.dd.get_indices(docTypes=[])\n\n def target_text_document_indices(self, grouped_targets: dict) -> list:\n return [self.corpus_text_document_indices(corpus_id) for corpus_id in grouped_targets.keys()]\n\n","sub_path":"jassrealtime/search/multicorpus/DocumentsBy.py","file_name":"DocumentsBy.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"375493150","text":"from flask import Blueprint, jsonify\nfrom flask_ssa.extensions import login_manager\nfrom flask_ssa.manage_users.models import User, users_schema, user_schema\nfrom flask_login import current_user\nimport base64\n\napi = Blueprint('api', __name__, url_prefix='/api')\n\n\n@api.route('/listusers', methods=[\"POST\"])\ndef listusers():\n if current_user.is_authenticated:\n userlist = User.query.all()\n results = users_schema.dumps(userlist)\n return jsonify(results)\n else:\n return auth_error()\n\n\n@api.route('/getuser/', methods=[\"POST\"])\ndef getuser(username):\n if current_user.is_authenticated:\n thisuser = User.query.filter_by(username=username).first()\n results = user_schema.dumps(thisuser)\n return jsonify(results)\n else:\n return auth_error()\n\n\n@api.errorhandler(401)\ndef auth_error(error=None):\n message = {\n 'status': 401,\n 'message': 'Authentication error',\n }\n resp = jsonify(message)\n resp.status_code = 401\n\n return resp\n\n\n@login_manager.request_loader\ndef load_user_from_request(request):\n\n # first, try to login using the api_key url arg\n api_key = request.args.get('api_key')\n if api_key:\n user = User.query.filter_by(api_key=api_key).first()\n if user:\n return user\n\n # next, try to login using Basic Auth\n api_key = request.headers.get('Authorization')\n if api_key:\n api_key = api_key.replace('Basic ', '', 1)\n try:\n api_key = base64.b64decode(api_key)\n api_key = api_key.decode().split(\":\")[-1]\n except TypeError:\n pass\n user = User.query.filter_by(api_key=api_key).first()\n if user:\n return user\n\n # finally, return None if both methods did not login the user\n return None\n","sub_path":"flask_ssa/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"106618220","text":"import requests\nimport urllib\nimport json\nimport time\nimport datetime\nimport pandas as pd\nimport config_Hubspot as hsc\nimport config_Exasol as ec\nimport exasol as e\nimport sys\nimport multiprocessing as mp\n\n# reload(sys);\n# sys.setdefaultencoding(\"utf8\")\n\nsystem_cores = mp.cpu_count()\n\napikey = hsc.apikey\n\nexaconnect = e.connect(\n dsn=ec.dsn,\n DRIVER=ec.DRIVER,\n EXAHOST=ec.EXAHOST,\n EXAUID=ec.EXAUID,\n EXAPWD=ec.EXAPWD,\n autocommit=True\n )\n\nexasol_lookup_db = 'CU_ONLINE_MARKETING_STG.HUBSPOT_CONTACTS'\nexasol_import_db = 'CU_ONLINE_MARKETING_STG.HUBSPOT_CONTACTS_INFO'\nexasol_import_db_2 = 'CU_ONLINE_MARKETING_STG.HUBSPOT_CONTACTS_ACADEMIC_PROGRAMS'\n\ndef cast_unix_to_datetime(dataframe, field):\n dataframe[field] = pd.to_datetime(dataframe[field], unit='ms').dt.date\n\ndef get_hubspot_data(passed_url):\n get_active_url = requests.get(passed_url)\n json_details = json.loads(get_active_url.text)\n return json_details\n\ndef getValue(myObject, path):\n returnValue = myObject\n for key in path:\n if(returnValue):\n if(type(returnValue) is dict and key in returnValue.keys() and returnValue[key]):\n returnValue = returnValue[key]\n elif(type(returnValue) is list and key <= len(returnValue)):\n returnValue = returnValue[key]\n elif(type(returnValue) is bool and key <= len(returnValue)):\n returnValue = returnValue[key]\n else:\n returnValue = \"\"\n break\n return returnValue\n\ndef converttime(epoch_date):\n if epoch_date == \"\":\n return_date = epoch_date\n else:\n return_date = time.strftime(\"%Y-%m-%d\", time.localtime(abs(float(epoch_date)/1000)))\n return return_date\n\ndef hubspot_get_contact_info(contact_id):\n print(contact_id)\n url = 'https://api.hubapi.com/contacts/v1/contact/vid/'+ str(contact_id) + '/profile?hapikey=' + apikey\n print(url)\n # json_data_detail = get_hubspot_data(url)\n # hs_df = pd.DataFrame({\n # \"vid\": getValue(json_data_detail, ['vid']),\n # \"birthdate\": converttime(getValue(json_data_detail, [\"properties\", \"birthdate\", \"value\"])),\n # \"created_date\": converttime(getValue(json_data_detail, [\"properties\", \"createdate\", \"value\"])),\n # \"lifecyclestage\": getValue(json_data_detail, [\"properties\", \"lifecyclestage\", \"versions\", 0, \"value\"]),\n # \"lifecyclestage_date\": converttime(getValue(json_data_detail, [\"properties\", \"lifecyclestage\", \"versions\", 0, \"timestamp\"])),\n # \"first_referrer\": getValue(json_data_detail, [\"properties\", \"hs_analytics_first_referrer\", \"versions\", 0, \"value\"]),\n # \"first_referrer_date\": converttime(getValue(json_data_detail, [\"properties\", \"hs_analytics_first_referrer\", \"versions\", 0, \"timestamp\"])),\n # \"conversion_name\": getValue(json_data_detail, [\"properties\", \"recent_conversion_event_name\", \"versions\", 0, \"value\"]),\n # \"conversion_date\": getValue(json_data_detail, [\"properties\", \"recent_conversion_event_name\", \"versions\", 0, \"timestamp\"]),\n # \"num_page_views\": getValue(json_data_detail, [\"properties\", \"hs_analytics_num_page_views\", \"value\"]),\n # \"city\": getValue(json_data_detail, [\"properties\", \"city\", \"value\"]),\n # \"state\": getValue(json_data_detail, [\"properties\", \"state\", \"value\"]),\n # \"zip\": getValue(json_data_detail, [\"properties\", \"zip\", \"value\"]),\n # \"sales_email_last_opened\": converttime(getValue(json_data_detail, [\"properties\", \"hs_sales_email_last_opened\", \"value\"])),\n # \"hubspot_score\": getValue(json_data_detail, [\"properties\", \"hubspotscore\", \"value\"]),\n # \"first_name\": getValue(json_data_detail, [\"properties\", \"firstname\", \"value\"]),\n # \"last_name\": getValue(json_data_detail, [\"properties\", \"lastname\", \"value\"]),\n # \"twitter\": getValue(json_data_detail, [\"properties\", \"twitterhandle\", \"value\"]),\n # \"linkedin\": getValue(json_data_detail, [\"properties\", \"linkedinconnections\", \"value\"]),\n # \"linkedinbio\": getValue(json_data_detail, [\"properties\", \"linkedinbio\", \"value\"]),\n # \"phone\": getValue(json_data_detail, [\"properties\", \"phone\", \"value\"]),\n # \"specializations\": getValue(json_data_detail, [\"properties\", \"specializations\", \"value\"]),\n # \"email\": getValue(json_data_detail, [\"properties\", \"email\", \"value\"]),\n # \"cu_email\": getValue(json_data_detail, [\"properties\", \"cu_email_address\", \"value\"]),\n # \"lead_status\": getValue(json_data_detail, [\"properties\", \"hs_lead_status\", \"value\"]),\n # \"emails_since_last_engagement\": getValue(json_data_detail, [\"properties\", \"hs_emails_sends_since_last_engagement\", \"value\"]),\n # \"residency\": getValue(json_data_detail, [\"properties\", \"residency\", \"value\"]),\n # \"cu_admit\": getValue(json_data_detail, [\"properties\", \"cu_admit\", \"value\"]),\n # \"closeddate\": converttime(getValue(json_data_detail, [\"properties\", \"closeddate\", \"value\"])),\n # \"lastmodifieddate\": converttime(getValue(json_data_detail, [\"properties\", \"lastmodifieddate\", \"value\"])),\n # \"kloutscore\": getValue(json_data_detail, [\"properties\", \"kloutscoregeneral\", \"value\"]),\n # \"academic_program\": getValue(json_data_detail, [\"properties\", \"academic_program\", \"value\"]),\n # \"import_date\": datetime.date.today()\n # }, index=[0])\n #\n # hs_df_ordered = hs_df[[\n # \"vid\",\n # \"first_name\",\n # \"last_name\",\n # # \"birthdate\",\n # \"created_date\",\n # \"lifecyclestage\",\n # \"lifecyclestage_date\",\n # # \"first_referrer\",\n # # \"first_referrer_date\",\n # \"conversion_name\",\n # \"conversion_date\",\n # \"num_page_views\",\n # \"city\",\n # \"state\",\n # \"zip\",\n # # \"sales_email_last_opened\",\n # \"hubspot_score\",\n # \"twitter\",\n # \"linkedin\",\n # \"linkedinbio\",\n # \"phone\",\n # \"specializations\",\n # \"email\",\n # \"cu_email\",\n # \"lead_status\",\n # \"emails_since_last_engagement\",\n # \"residency\",\n # \"cu_admit\",\n # \"closeddate\",\n # \"lastmodifieddate\",\n # \"kloutscore\",\n # \"import_date\"\n # ]]\n # # print(hs_df)\n # # print('')\n # print(hs_df_ordered)\n\ndef pool_handler(function, values, core_cnt):\n p = mp.Pool(core_cnt)\n p.map(function, values)\n\nif __name__ == '__main__':\n\n # exaconnect.execute('truncate table ' + exasol_import_db)\n # exaconnect.execute('truncate table ' + exasol_import_db_2)\n #\n # hubspot_ids = exaconnect.readData(\"select vid from \" + exasol_lookup_db)\n # print(hubspot_ids)\n\n ids = [\n '21611',\n '424259',\n '57544306',\n '5509356',\n '7725206',\n '11328106',\n '12057256',\n '13168756',\n '15211606',\n '15422556',\n '17085806',\n '18370306',\n '19459906',\n '19621906',\n '20360656'\n ]\n\n pool_handler(hubspot_get_contact_info, ids, system_cores)\n\n # test vids -'37079638' has multiple academic programs --60931956 no academic programs -- 31988356, 37079606 - MSIS\n\n # for id in ids:\n # hubspot_get_contact_info(id)\n\n # print(vid)\n # # try:\n # # exaconnect.writePandas(hs_df_ordered, exasol_import_db)\n # # except:\n # # pass\n # #\n # # print('')\n # #\n # # majors = getValue(json_data_detail, [\"properties\", \"academic_program\", \"value\"]).split(';')\n # # try:\n # # for major in majors:\n # # table = zip([major], hs_df['vid'])\n # # hs_academic_program_df = pd.DataFrame({\"vid\": table[0][0],\n # # \"academic_program\": table[0][1]}, index=[0])\n # # print(hs_academic_program_df)\n # #\n # # exaconnect.writePandas(hs_academic_program_df, exasol_import_db_2)\n # # except:\n # # pass\n","sub_path":"HubSpot_Contacts_InfoByContact_Multiprocessing.py","file_name":"HubSpot_Contacts_InfoByContact_Multiprocessing.py","file_ext":"py","file_size_in_byte":8165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"650874174","text":"# -*-coding=utf-8-*-\n\n# @Time : 2020/4/2 9:19\n# @File : qt5_demo.py\nimport threading\nimport time\nimport area\nimport sys\nfrom PyQt5 import QtWidgets,QtCore\nfrom PyQt5.QtWidgets import (QWidget, QPushButton,QHBoxLayout, QVBoxLayout, QApplication,QFrame,QSplitter,QTextEdit)\n\n\ndef case1():\n app = QtWidgets.QApplication(sys.argv)\n widget=QtWidgets.QWidget()\n widget.resize(400,400)\n widget.setWindowTitle('First Demo')\n widget.show()\n sys.exit(app.exec_()) # 必须有这一行\n\ndef case2():\n import sys\n from PyQt5.QtWidgets import QWidget, QLabel, QApplication\n\n class Example(QWidget):\n\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n lbl1 = QLabel('Zetcode', self)\n lbl1.move(15, 10)\n\n lbl2 = QLabel('tutorials', self)\n lbl2.move(35, 40)\n\n lbl3 = QLabel('for programmers', self)\n lbl3.move(55, 70)\n\n self.setGeometry(300, 300, 250, 150)\n self.setWindowTitle('Absolute')\n self.show()\n\n app =QApplication(sys.argv)\n exe =Example()\n sys.exit(app.exec_())\n\ndef case3():\n class Example(QWidget):\n\n def __init__(self):\n super().__init__()\n\n self.initUI()\n\n def initUI(self):\n okButton = QPushButton(\"OK\")\n cancelButton = QPushButton(\"Cancel\")\n\n hbox = QHBoxLayout()\n hbox.addStretch(1)\n hbox.addWidget(okButton)\n hbox.addWidget(cancelButton)\n\n vbox = QVBoxLayout()\n vbox.addStretch(1)\n vbox.addLayout(hbox)\n\n self.setLayout(vbox)\n\n self.setGeometry(300, 300, 300, 150)\n self.setWindowTitle('Buttons')\n self.show()\n\n app = QApplication(sys.argv)\n exe =Example()\n sys.exit(app.exec())\n\ndef case4():\n class Windform(QWidget):\n def __init__(self, parent=None):\n super(Windform, self).__init__(parent)\n\n hlayout = QHBoxLayout()\n hlayout.addWidget(QPushButton(str(1)))\n hlayout.addWidget(QPushButton(str(2)))\n hlayout.addWidget(QPushButton(str(3)))\n hlayout.addWidget(QPushButton(str(4)))\n hlayout.addWidget(QPushButton(str(5)))\n # 设置控件的间距\n hlayout.setSpacing(0)\n self.setLayout(hlayout)\n\n app = QApplication(sys.argv)\n exe = Windform()\n exe.show()\n sys.exit(app.exec_())\n\ndef case5():\n class Windform(QWidget):\n def __init__(self, parent=None):\n super(Windform, self).__init__(parent)\n\n self.setWindowTitle(\"水平布局管理\")\n self.resize(800, 200)\n\n hlayout = QHBoxLayout()\n # 按钮水平居左,垂直居上\n hlayout.addWidget(QPushButton(str(1)), 0, Qt.AlignLeft | Qt.AlignTop)\n hlayout.addWidget(QPushButton(str(2)), 0, Qt.AlignLeft | Qt.AlignTop)\n hlayout.addWidget(QPushButton(str(3)), 5)\n # 水平居左,垂直居下\n hlayout.addWidget(QPushButton(str(4)), 0, Qt.AlignLeft | Qt.AlignBottom)\n hlayout.addWidget(QPushButton(str(5)), 0, Qt.AlignLeft | Qt.AlignBottom)\n self.setLayout(hlayout)\n\n\n app = QApplication(sys.argv)\n exe = Windform()\n exe.show()\n sys.exit(app.exec_())\n\n\n\ndef case5():\n from PyQt5.QtWidgets import QApplication, QMainWindow\n from PyQt5.uic import loadUi\n\n class MainWindow(QMainWindow):\n def __init__(self, parent=None):\n super(MainWindow, self).__init__(parent)\n loadUi('qt_windows.ui', self)\n self.setFixedSize(self.sizeHint())\n\n app = QApplication(sys.argv)\n w = MainWindow()\n w.show()\n sys.exit(app.exec())\n\nfrom PyQt5 import QtGui\ndef case6():\n class Widget(QWidget):\n def __init__(self):\n super(Widget, self).__init__()\n self.resize(600, 400)\n\n layout = QtGui.QVBoxLayout(self)\n self.table = QtGui.QTableWidget(20, 10)\n self.vBar = self.table.verticalScrollBar()\n self._vBar_lastVal = self.vBar.value()\n\n layout.addWidget(self.table)\n\n self.vBar.valueChanged.connect(self.scrollbarChanged)\n\n def scrollbarChanged(self, val):\n bar = self.vBar\n minVal, maxVal = bar.minimum(), bar.maximum()\n avg = (minVal + maxVal) / 2\n rowCount = self.table.rowCount()\n\n # scrolling down\n if val > self._vBar_lastVal and val >= avg:\n self.table.insertRow(rowCount)\n\n # scrolling up\n elif val < self._vBar_lastVal:\n lastRow = rowCount - 1\n empty = True\n for col in range(self.table.columnCount()):\n item = self.table.item(lastRow, col)\n if item and item.text():\n empty = False\n break\n if empty:\n self.table.removeRow(lastRow)\n\n self._vBar_lastVal = val\n\n\n\ndef case8():\n import sys, os\n from PyQt5.QtWidgets import QApplication, QHBoxLayout, QVBoxLayout, QWidget, QPushButton\n from PyQt5.QtGui import QIcon\n\n # path = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))\n\n class MyWindow(QWidget):\n\n def __init__(self):\n super(MyWindow, self).__init__()\n self.initUI()\n\n def initUI(self):\n self.setGeometry(300, 300, 500, 400)\n # self.setWindowIcon(QIcon(r'%s/4.图标素材/chuan.ico' % path))\n self.setWindowTitle('盒布局示例')\n\n okbutton = QPushButton('确认') # 设置“确认”按钮\n cancelbutton = QPushButton('取消') # 设置“取消”按钮\n\n okbutton2 = QPushButton('确认') # 设置“确认”按钮\n cancelbutton2 = QPushButton('取消') # 设置“取消”按钮\n\n\n label1 = QtWidgets.QLabel('导入')\n label2 = QtWidgets.QLabel('正常')\n label3 = QtWidgets.QLabel('异常')\n\n vbox = QVBoxLayout() # 布局实例化对象\n # hbox.addStretch(1) # 设置分配比例\n vbox.addWidget(okbutton) # 添加“确认”按钮到窗体\n vbox.addWidget(cancelbutton)\n # vbox.addWidget(result_label)\n splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)\n\n vbox2 = QVBoxLayout() # 布局实例化对象\n # hbox2.addStretch(1) # 设置分配比例\n # vbox2.addWidget(okbutton2) # 添加“确认”按钮到窗体\n # vbox2.addWidget(cancelbutton2)\n vbox2.addWidget(label1)\n vbox2.addWidget(label2)\n vbox2.addWidget(label3)\n\n hbox = QHBoxLayout()\n # vbox.addStretch(1)\n hbox.addLayout(vbox)\n hbox.addLayout(vbox2)\n\n self.setLayout(hbox) # 设置窗体布局\n\n\n app = QApplication(sys.argv)\n win = MyWindow()\n win.show()\n sys.exit(app.exec_())\n\ndef case9():\n class SplitterExample(QWidget):\n def __init__(self):\n super(SplitterExample, self).__init__()\n self.initUI()\n\n def initUI(self):\n # 设置全局布局为水平布局,设置标题与初始大小窗口\n hbox = QHBoxLayout()\n self.setWindowTitle(\"QSplitter例子\")\n self.setGeometry(400, 400, 400, 400)\n\n # 实例化QFrame控件\n topLeft = QFrame()\n topLeft.setFrameShape(QFrame.StyledPanel)\n\n bottom = QFrame()\n bottom.setFrameShape(QFrame.StyledPanel)\n\n # 实例化QSplitter控件并设置初始为水平方向布局\n splitter1 = QSplitter(QtCore.Qt.Horizontal)\n textedit = QTextEdit()\n\n # 向Splitter内添加控件。并设置游戏的初始大小\n splitter1.addWidget(topLeft)\n splitter1.addWidget(textedit)\n splitter1.setSizes([100, 200])\n\n # 实例化Splitter管理器,添加控件到其中,设置垂直方向\n splitter2 = QSplitter(QtCore.Qt.Vertical)\n splitter2.addWidget(splitter1)\n splitter2.addWidget(bottom)\n\n label1 = QtWidgets.QLabel('导入')\n label2 = QtWidgets.QLabel('正常')\n label3 = QtWidgets.QLabel('异常')\n\n # 设置窗体全局布局以及子布局的添加\n hbox.addWidget(splitter2)\n self.setLayout(hbox)\n\n app = QApplication(sys.argv)\n win = SplitterExample()\n win.show()\n sys.exit(app.exec_())\n\ndef case10():\n from PyQt5.QtWidgets import QMainWindow, QApplication\n from PyQt5.QtCore import pyqtSlot\n class Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(684, 259)\n self.centralWidget = QtWidgets.QWidget(MainWindow)\n self.centralWidget.setObjectName(\"centralWidget\")\n self.pushButton = QtWidgets.QPushButton(self.centralWidget)\n self.pushButton.setGeometry(QtCore.QRect(160, 190, 93, 28))\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton_2 = QtWidgets.QPushButton(self.centralWidget)\n self.pushButton_2.setGeometry(QtCore.QRect(390, 190, 93, 28))\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.lineEdit = QtWidgets.QLineEdit(self.centralWidget)\n self.lineEdit.setGeometry(QtCore.QRect(160, 30, 361, 21))\n self.lineEdit.setObjectName(\"lineEdit\")\n self.lineEdit_2 = QtWidgets.QLineEdit(self.centralWidget)\n self.lineEdit_2.setGeometry(QtCore.QRect(160, 70, 361, 21))\n self.lineEdit_2.setObjectName(\"lineEdit_2\")\n self.label = QtWidgets.QLabel(self.centralWidget)\n self.label.setGeometry(QtCore.QRect(20, 40, 72, 15))\n self.label.setObjectName(\"label\")\n self.label_2 = QtWidgets.QLabel(self.centralWidget)\n self.label_2.setGeometry(QtCore.QRect(20, 70, 72, 15))\n self.label_2.setObjectName(\"label_2\")\n self.comboBox = QtWidgets.QComboBox(self.centralWidget)\n self.comboBox.setGeometry(QtCore.QRect(180, 130, 87, 22))\n self.comboBox.setObjectName(\"comboBox\")\n self.comboBox_2 = QtWidgets.QComboBox(self.centralWidget)\n self.comboBox_2.setGeometry(QtCore.QRect(380, 130, 87, 22))\n self.comboBox_2.setObjectName(\"comboBox_2\")\n self.label_3 = QtWidgets.QLabel(self.centralWidget)\n self.label_3.setGeometry(QtCore.QRect(190, 110, 72, 15))\n self.label_3.setObjectName(\"label_3\")\n self.label_4 = QtWidgets.QLabel(self.centralWidget)\n self.label_4.setGeometry(QtCore.QRect(390, 110, 72, 15))\n self.label_4.setObjectName(\"label_4\")\n MainWindow.setCentralWidget(self.centralWidget)\n\n self.retranslateUi(MainWindow)\n self.pushButton_2.clicked.connect(MainWindow.close)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n self.pushButton.setText(_translate(\"MainWindow\", \"开始\"))\n self.pushButton_2.setText(_translate(\"MainWindow\", \"退出\"))\n self.label.setText(_translate(\"MainWindow\", \"显示省份\"))\n self.label_2.setText(_translate(\"MainWindow\", \"显示城市\"))\n self.label_3.setText(_translate(\"MainWindow\", \"选择省份\"))\n self.label_4.setText(_translate(\"MainWindow\", \"选择城市\"))\n\n class MainWindow(QMainWindow, Ui_MainWindow):\n \"\"\"\n Class documentation goes here.\n \"\"\"\n\n def __init__(self, parent=None):\n \"\"\"\n Constructor\n\n @param parent reference to the parent widget\n @type QWidget\n \"\"\"\n super(MainWindow, self).__init__(parent)\n self.setupUi(self)\n # 初始化省\n self.comboBox.clear() # 清空items\n self.comboBox.addItem('请选择')\n for k, v in area.dictProvince.items():\n self.comboBox.addItem(v, k) # 键、值反转\n\n @pyqtSlot(int)\n # 取市的键值\n def on_comboBox_activated(self, index):\n key = self.comboBox.itemData(index)\n print(key)\n self.comboBox_2.clear() # 清空items\n if key:\n self.comboBox_2.addItem('请选择')\n # 初始化市\n for k, v in area.dictCity[key].items():\n self.comboBox_2.addItem(v, k) # 键、值反转\n\n @pyqtSlot()\n def on_pushButton_clicked(self):\n # 获取当前选项框索引\n province_index = self.comboBox.currentIndex()\n city_index = self.comboBox_2.currentIndex()\n # 取当前省市县名称\n province_name = self.comboBox.itemText(province_index)\n city_name = self.comboBox_2.itemText(city_index)\n print(province_name, city_name)\n self.lineEdit.setText(province_name) # 显示省份\n self.lineEdit_2.setText(city_name) # 显示城市\n\n # app = QtWidgets.QApplication(sys.argv)\n # MainWindow = QtWidgets.QMainWindow()\n # ui = Ui_MainWindow()\n # ui.setupUi(MainWindow)\n # MainWindow.show()\n # sys.exit(app.exec_())\n\n app = QApplication(sys.argv)\n ui = MainWindow()\n ui.show()\n sys.exit(app.exec_())\n\ndef case11():\n import sys\n from PyQt5.QtWidgets import (QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem, QAbstractItemView,\n QComboBox, QPushButton)\n\n class Table(QWidget):\n\n def __init__(self):\n super(Table,self).__init__()\n\n self.initUI()\n\n def initUI(self):\n self.setWindowTitle(\"QTableWidget 例子\")\n self.resize(430, 300)\n conLayout = QVBoxLayout()\n self.tableWidget = QTableWidget(self)\n # self.tableWidget.setRowCount(10)\n self.tableWidget.setColumnCount(3)\n conLayout.addWidget(self.tableWidget)\n\n self.tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '体重(kg)'])\n button = QPushButton('Run')\n button.clicked.connect(self.start_to_add)\n conLayout.addWidget(button)\n self.setLayout(conLayout)\n # self.add_comBox()\n\n # 多线程\n def start_to_add(self):\n self.task = threading.Thread(target=self.add_comBox(), args=())\n self.stop_task = False\n self.task.start()\n\n def add_comBox(self):\n # self.tableWidget.setRowCount(10)\n\n for i in range(10):\n # time.sleep(0.5)\n self.tableWidget.insertRow(i)\n newItem = QTableWidgetItem(\"张三\")\n self.tableWidget.setItem(i, 0, newItem)\n\n comBox = QComboBox()\n comBox.addItem(\"男\")\n comBox.addItem(\"女\")\n comBox.setStyleSheet(\"QComboBox{margin:3px};\")\n self.tableWidget.setCellWidget(i, 1, comBox)\n\n searchBtn = QPushButton(\"修改\")\n searchBtn.setDown(True)\n searchBtn.setStyleSheet(\"QPushButton{margin:3px};\")\n self.tableWidget.setCellWidget(i, 2, searchBtn)\n\n\n app = QApplication(sys.argv)\n ui = Table()\n ui.show()\n sys.exit(app.exec_())\n\nif __name__=='__main__':\n # case1()\n # case2()\n # case3()\n # case4()\n # case5()\n # case5()\n # case8()\n # case9()\n # case10()\n case11()\n","sub_path":"qt_demo/qt5_demo.py","file_name":"qt5_demo.py","file_ext":"py","file_size_in_byte":15939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"630213495","text":"# -*- coding: utf-8; -*-\n\n\"\"\"\nBecause only mitmproxy/mitmdump calls our script, not the other way around,\nwe can imitate mitmproxy's calls and collect the results.\n\"\"\"\n\nimport io\nimport os\nimport tempfile\n\nimport pytest\n\nimport mitmproxy_httpolice\n\n\nclass Bin(object):\n\n pass\n\n\nclass FakeMitmdump(object):\n\n # pylint: disable=attribute-defined-outside-init\n\n def __init__(self):\n self.opts = []\n\n def start(self):\n self.context = Bin()\n fd, self.report_path = tempfile.mkstemp()\n os.close(fd)\n argv = [''] + self.opts + [self.report_path]\n mitmproxy_httpolice.start(self.context, argv)\n\n def flow(self,\n req_scheme, req_method, req_path, req_http_version,\n req_fields, req_content,\n resp_http_version, resp_status_code, resp_reason,\n resp_fields, resp_content):\n flow = Bin()\n flow.request = Bin()\n flow.request.scheme = req_scheme\n flow.request.method = req_method\n flow.request.path = req_path\n flow.request.http_version = req_http_version\n flow.request.headers = Bin()\n flow.request.headers.fields = req_fields\n flow.request.content = req_content\n flow.response = Bin()\n flow.response.http_version = resp_http_version\n flow.response.status_code = resp_status_code\n flow.response.reason = resp_reason\n flow.response.headers = Bin()\n flow.response.headers.fields = resp_fields\n flow.response.content = resp_content\n mitmproxy_httpolice.response(self.context, flow)\n\n def done(self):\n mitmproxy_httpolice.done(self.context)\n with io.open(self.report_path, 'rb') as f:\n self.report = f.read()\n\n def __enter__(self):\n self.start()\n return self\n\n def __exit__(self, exc_type, _exc_value, _traceback):\n if exc_type is None:\n self.done()\n if os.path.exists(self.report_path):\n os.unlink(self.report_path)\n\n\n@pytest.fixture\ndef fake_mitmdump(request): # pylint: disable=unused-argument\n return FakeMitmdump()\n\n\ndef test_simple(fake_mitmdump): # pylint: disable=redefined-outer-name\n with fake_mitmdump:\n fake_mitmdump.flow(\n 'http',\n 'GET', '/', 'HTTP/1.1',\n [\n ('host', 'example.com'),\n ('User-Agent', 'demo'),\n ],\n b'',\n 'HTTP/1.1', 200, 'OK',\n [\n ('Content-Type', 'text/plain'),\n ('Content-Length', '14'),\n ('Date', 'Tue, 03 May 2016 14:13:34 GMT'),\n ],\n b'Hello world!\\r\\n'\n )\n assert fake_mitmdump.report == b''\n\n\ndef test_complex(fake_mitmdump): # pylint: disable=redefined-outer-name\n with fake_mitmdump:\n fake_mitmdump.flow(\n 'http',\n 'POST', '/foo-bar?baz=qux', 'HTTP/1.1',\n [\n ('host', 'example.com'),\n ('User-Agent', 'demo'),\n ('Transfer-Encoding', 'chunked'),\n ('content-length', '14'),\n ('content-type', 'application/json'),\n ],\n b'{foo: \"bar\"}',\n 'HTTP/1.1', 201, u'Très bien'.encode('iso-8859-1'),\n [\n ('Content-Type', 'text/plain'),\n ('Content-Length', '14'),\n ('Date', 'Tue, 03 May 2016 14:13:34 GMT'),\n ],\n b'Hello world!\\r\\n'\n )\n\n fake_mitmdump.flow(\n 'http',\n 'GET', '/', 'HTTP/1.1',\n [\n ('host', 'example.com'),\n ('User-Agent', 'demo'),\n ('If-None-Match', '\"quux\"'),\n ],\n b'',\n 'HTTP/1.1', 304, 'Not Modified',\n [\n ('Content-Type', 'text/plain'),\n ('Date', 'Tue, 03 May 2016 14:13:34 GMT'),\n ('content-length', '0'),\n ],\n b''\n )\n\n assert fake_mitmdump.report == (\n b'------------ request 1 : POST /foo-bar?baz=qux\\n'\n b'E 1038 Bad JSON body\\n' +\n u'------------ response 1 : 201 Très bien\\n'.encode('utf-8') +\n b'C 1073 Possibly missing Location header\\n'\n b'------------ request 2 : GET /\\n'\n b'------------ response 2 : 304 Not Modified\\n'\n b'C 1127 Content-Type in a 304 response\\n'\n )\n\n\ndef test_http2(fake_mitmdump): # pylint: disable=redefined-outer-name\n with fake_mitmdump:\n fake_mitmdump.flow(\n 'https',\n 'GET', '/index.html', 'HTTP/2.0',\n [\n (':method', 'GET'),\n (':scheme', 'https'),\n (':authority', 'example.com'),\n (':path', '/index.html'),\n ('user-agent', 'demo'),\n ('if-match', 'quux'),\n ],\n b'',\n 'HTTP/2.0', 404, None,\n [\n (':status', '404'),\n ('content-type', 'text/plain'),\n ('content-length', '14'),\n ('date', 'Tue, 03 May 2016 14:13:34 GMT'),\n ('connection', 'close'),\n ],\n b'Hello world!\\r\\n'\n )\n assert fake_mitmdump.report == (\n b'------------ request 1 : GET https://example.com/index.html\\n'\n b'E 1000 Malformed if-match header\\n'\n b'------------ response 1 : 404 Not Found\\n'\n b'E 1244 connection header in an HTTP/2 message\\n'\n )\n\n\ndef test_html(fake_mitmdump): # pylint: disable=redefined-outer-name\n fake_mitmdump.opts = ['-o', 'html']\n with fake_mitmdump:\n fake_mitmdump.flow(\n 'http',\n 'GET', '/', 'HTTP/1.1',\n [\n ('host', 'example.com'),\n ('User-Agent', 'demo'),\n ],\n b'',\n 'HTTP/1.1', 200, 'OK',\n [\n ('Content-Type', 'text/plain'),\n ('Content-Length', '14'),\n ('Date', 'Tue, 03 May 2016 14:13:34 GMT'),\n ],\n b'Hello world!\\r\\n'\n )\n assert b'

HTTPolice report

' in fake_mitmdump.report\n\n\ndef test_silence(fake_mitmdump): # pylint: disable=redefined-outer-name\n fake_mitmdump.opts = ['-s', '1087', '-s', '1194']\n with fake_mitmdump:\n fake_mitmdump.flow(\n 'http',\n 'GET', '/', 'HTTP/1.1',\n [\n ('host', 'example.com'),\n ('User-Agent', 'demo'),\n ],\n b'',\n 'HTTP/1.1', 401, 'Unauthorized',\n [\n ('Content-Type', 'text/plain'),\n ('Content-Length', '0'),\n ],\n b''\n )\n assert fake_mitmdump.report == (\n b'------------ request 1 : GET /\\n'\n b'------------ response 1 : 401 Unauthorized\\n'\n b'C 1110 401 response with no Date header\\n'\n )\n","sub_path":"test_fake_mitmdump.py","file_name":"test_fake_mitmdump.py","file_ext":"py","file_size_in_byte":6960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"511883347","text":"import cv2\nfrom binary_cls_3 import test\nfrom PIL import Image\n\n#이미지 resize()\ndef resize(img,cnt1,cnt2,cnt3,cnt4):\n\n dst = img.copy()\n dst = img[cnt4:cnt2,cnt3:cnt1]\n return dst\n\n#값 측정\ndef calculate(img):\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img = Image.fromarray(img)\n\n result = test(img)\n return result\n\ndef main():\n img = cv2.imread('./hani.jpg')\n\n # cv2.waitKey()\n# img = cv2.rectangle(img, (150, 100), (400, 250), (0, 255, 0), 3)\n\n cnt1 = 200 ;cnt3=0;cnt2=200;cnt4=0\n count = 1\n while True:\n img = cv2.imread('./hani.jpg')\n\n print(cnt2, \" : \", cnt4)\n\n img = cv2.rectangle(img, (cnt1, cnt2), (cnt3, cnt4), (0, 255, 0), 3)\n height = img.shape[0]\n width = img.shape[1]\n resize_img = resize(img,cnt1,cnt2,cnt3,cnt4)\n\n print(height,width)\n #cv2.imshow(\"dfasd\",resize_img)\n #cv2.waitKey(0)\n result = calculate(resize_img)\n\n if(result >0.3):\n cv2.imshow(\"df\",resize_img)\n cv2.waitKey(0)\n\n cv2.imshow('loop',img)\n k = cv2.waitKey(1)\n if k == 27: # wait for ESC key to exit\n cv2.destroyAllWindows()\n break\n\n cnt3 +=10;cnt1+=10\n\n if(cnt1== 780 and cnt3 == 680 and cnt2 ==600 and cnt4==500):\n cnt1 = 200; cnt3 = 0; cnt2 = 200; cnt4 = 0\n if(cnt1 == 780 and cnt3 == 580):\n cnt1 = 200;cnt3 = 0;cnt2 += 200*count;cnt4 += 200*count\n count+=1\n\nif __name__ == \"__main__\":\n main()","sub_path":"7월 12일 얼굴인식(사각형 포착)/capture_hani.py","file_name":"capture_hani.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"189210923","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nimport os,sys,json\nimport datetime,time\nfrom module.Constant import default_value,default_keys\nclass LoadConfHandler:\n def __init__(self,default_conf_file):\n self.default_conf_file = default_conf_file\n\n def _parseConf(self,conf_file):\n content = self._loadConfFile(conf_file)\n conf = {}\n for key in default_keys:\n conf[key] = content.get(key) if content.get(key,None) is not None and str(content.get(key)).strip() != '' else default_value[key]\n return conf\n\n def _loadConfFile(self,config):\n f = open(config,'r')\n try:\n content = json.load(f)\n except:\n content = {}\n return content\n\n def loadConf(self,conf_file = None):\n if conf_file:\n return self._loadConfFile(conf_file)\n else:\n return self._parseConf(self.default_conf_file)\n","sub_path":"utils_updates/etl_worker2/utils/LoadConfHandler.py","file_name":"LoadConfHandler.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"238332006","text":"from random import seed\nfrom random import randrange\nfrom csv import reader\nfrom math import sqrt\nimport numpy as np\nfrom numpy.random import randn\nimport matplotlib.pyplot as plt\nfrom pandas import date_range,Series,DataFrame,read_csv, qcut\nsavepred=list()\n\ndef load_csv(filename):\n\tdataset = list()\n\twith open(filename, 'r') as f:\n\t\tcsv_reader = reader(f)\n\t\tfor row in csv_reader:\n\t\t\tif not row:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tdataset.append(row)\n\treturn dataset\n\ndef str_column_to_float(dataset,column):\n\tfor row in dataset:\n\t\trow[column] = float(row[column].strip())\n\ndef dataset_minmax(dataset):\n\tminmax = list()\n\tfor i in range(len(dataset[0])):\n\t\tcol_values = [row[i] for row in dataset]\n\t\tvalue_min = min(col_values)\n\t\tvalue_max = max(col_values)\n\t\tminmax.append([value_min, value_max])\n\treturn minmax\n\ndef normalize_dataset(dataset, minmax):\n\tfor row in dataset:\n\t\tfor i in range(len(row)):\n\t\t\trow[i] = (row[i] - minmax[i][0])/(minmax[i][1] - minmax[i][0])\n\ndef cross_validation_split(dataset, n_folds):\n\tdataset_split = list()\n\tdataset_copy = list(dataset)\n\tfold_size = int(len(dataset) / n_folds)\n\tfor i in range(n_folds):\n\t\tfold = list()\n\t\twhile len(fold) < fold_size:\n\t\t\tindex = randrange(len(dataset_copy))\n\t\t\tfold.append(dataset_copy.pop(index))\n\t\tdataset_split.append(fold)\n\treturn dataset_split\n\n\ndef rmse_metric(actual, predicted):\n\tsum_error = 0.0\n\tfor i in range(len(actual)):\n\t\terror = actual[i] - predicted[i]\n\t\tsq_error = error**2\n\t\tsum_error += sq_error\n\tmean_error = sum_error/float(len(actual))\n\treturn (sqrt(mean_error))\n\ndef evaluate_algorithm(dataset, algorithm, n_folds, *args):\n\t#plt.plot(algorithm, 'ro')\n\t#plt.show()\n\tfolds = cross_validation_split(dataset, n_folds)\n\tscores = list()\n\tfor fold in folds:\n\t\ttrain_set = list(folds)\n\t\ttrain_set.remove(fold)\n\t\ttrain_set = sum(train_set, [])\n\t\ttest_set = list()\n\t\tfor row in fold:\n\t\t\trow_copy = list(row)\n\t\t\ttest_set.append(row_copy)\n\t\t\trow_copy[-1] = None\n\t\tpredicted = algorithm(train_set, test_set, *args)\n\t\tactual = [row[-1] for row in fold]\n\t\trmse = rmse_metric(actual, predicted)\n\t\tscores.append(rmse)\n\tplt.plot(actual, 'k', color='blue', label='Actual data')\n\tplt.plot(predicted, 'k--', label='Predicted data')\n\treturn scores\n\ndef predict(row, coefficients):\n\tyhat = coefficients[0]\n\tfor i in range(len(row)-1):\n\t\tyhat += row[i]*coefficients[i+1]\n\treturn yhat\n\ndef coefficients_sgd(train, l_rate, n_epoch):\n\tcoef = [0.0 for i in range(len(train[0]))]\n\tfor epoch in range(n_epoch):\n\t\tfor row in train:\n\t\t\ty = predict(row, coef)\n\t\t\terror = y - row[-1]\n\t\t\tcoef[0] = coef[0] - l_rate*error\n\t\t\tfor i in range(len(coef)-1):\n\t\t\t\tcoef[i+1] = coef[i+1] - l_rate*error*row[i]\n\t#plt.plot(coef)\n\treturn coef\n\ndef multivariate_linear_regression(train, test, l_rate, n_epoch):\n\tpredictions = list()\n\tcoef = coefficients_sgd(train, l_rate, n_epoch)\n\t#plt.plot(coef)\n\tfor row in test:\n\t\tyhat = predict(row, coef)\n\t\tpredictions.append(yhat)\n\t#print('predictions: %s' % predictions)\n\t#plt.plot(predictions,'o')\n\t#plt.show()\n\tsavepred=predictions\n\treturn(predictions)\n\n\nseed(1)\nfilename = 'brcancer2.csv'\ndataset = load_csv(filename)\n# df=read_csv(filename, header = None, names = ['x','y'])\n#\n# x = np.array(df.x)\n# y = np.array(df.y)\n#\n# theta = np.zeros((2,1))\n# #scatterplot of data with option to save figure.\n# def scatterPlot(x,y,yp=None,savePng=False):\n# \tplt.xlabel('Clump Thickness')\n# \tplt.ylabel('Marginal Adhension')\n# \tplt.scatter(x, y, marker='x')\n# \t#if yp is not None:\n# \t\t#plt.plot(x,yp)\n# \t#if savePng==False:\n# \t\t#plt.show()\n# \t#else:\n# \t\t#name = raw_input('Name Figure File: ')\n# \t\t#plt.savefig(name+'.png')\n#\n#\n# #scatterPlot(x,y)\n#\n# #linear regression implementation using libraries\n# (m,b) = np.polyfit(x,y,1)\n# print 'Slope is ' + str(m)\n# print 'Y intercept is ' + str(b)\n# yp = np.polyval([m,b],x)\n# scatterPlot(x,y,yp)\n#\n\n\n#plt.plot(dataset, 'ro')\n#plt.show()\n\nfor i in range(len(dataset[0])):\n\tstr_column_to_float(dataset, i)\nminmax = dataset_minmax(dataset)\nnormalize_dataset(dataset, minmax)\n\n\n\n#plt.plot(dataset, 'ro')\n#plt.show()\n\nn_folds = 5\nl_rate = 0.01\nn_epoch = 50\n#\n#\n#\nscores = evaluate_algorithm(dataset, multivariate_linear_regression, n_folds, l_rate, n_epoch)\nprint('Scores: %s' % scores)\nprint('Mean RMSE: %.3f' % (sum(scores)/float(len(scores))))\n#\n# # names=['id','ClumpThickness','UniformityofCellSize','UniformityofCellShape',\t'MarginalAdhesion',\t'SingleEpithelialCellSize',\t'BareNuclei',\t'BlandChromatin',\t'NormalNucleoli',\t'Mitoses',\t'Class']\n# # data=read_csv(filename, delimiter='\\t',names=names).dropna()\n# # plt.scatter(data.Mitoses, data.Class)\n# # plt.xlabel(\"Number of Votes\")\n# # plt.ylabel(\"IMDB Rating\")\n# # plt.xscale('log')\n#\n# #plt.plot(dataset,'o')\n# #plt.plot(predictions,'o')\n# #plt.show()\n# #plt.plot(minmax)\n# #plt.plot(dataset,'ro',alpha=.2)\nplt.show()\n#\n# n_folds = 7\n# l_rate = 0.01\n# n_epoch = 50\n# scores = evaluate_algorithm(dataset, multivariate_linear_regression, n_folds, l_rate, n_epoch)\n# print('Scores: %s' % scores)\n# print('Mean RMSE: %.3f' % (sum(scores)/float(len(scores))))\n# # plt.plot(scores)\n# # plt.show()\n# n_folds = 10\n# l_rate = 0.01\n# n_epoch = 50\n# scores = evaluate_algorithm(dataset, multivariate_linear_regression, n_folds, l_rate, n_epoch)\n# #plt.plot(scores)\n# plt.legend();\n# #plt.show()\n#\n# print('Scores: %s' % scores)\n# print('Mean RMSE: %.3f' % (sum(scores)/float(len(scores))))\n# n_folds = 4\n# l_rate = 0.01\n# n_epoch = 50\n# scores = evaluate_algorithm(dataset, multivariate_linear_regression, n_folds, l_rate, n_epoch)\n# #plt.plot(scores)\n# plt.legend();\n# #plt.show()\n#\n# print('Scores: %s' % scores)\n# print('Mean RMSE: %.3f' % (sum(scores)/float(len(scores))))\n# n_folds = 6\n# l_rate = 0.01\n# n_epoch = 50\n# scores = evaluate_algorithm(dataset, multivariate_linear_regression, n_folds, l_rate, n_epoch)\n# #plt.plot(scores)\n# plt.legend();\n# #plt.show()\n#\n# print('Scores: %s' % scores)\n# print('Mean RMSE: %.3f' % (sum(scores)/float(len(scores))))\n# n_folds = 8\n# l_rate = 0.01\n# n_epoch = 50\n# scores = evaluate_algorithm(dataset, multivariate_linear_regression, n_folds, l_rate, n_epoch)\n# #plt.plot(scores)\n# plt.legend();\n# #plt.show()\n#\n# print('Scores: %s' % scores)\n# print('Mean RMSE: %.3f' % (sum(scores)/float(len(scores))))\n# n_folds = 9\n# l_rate = 0.01\n# n_epoch = 50\n# scores = evaluate_algorithm(dataset, multivariate_linear_regression, n_folds, l_rate, n_epoch)\n# #plt.plot(scores)\n# plt.legend();\n# #plt.show()\n#\n# print('Scores: %s' % scores)\n# print('Mean RMSE: %.3f' % (sum(scores)/float(len(scores))))\n#\n","sub_path":"NEWregression.py","file_name":"NEWregression.py","file_ext":"py","file_size_in_byte":6497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"471814731","text":"import argparse\n\n# run this command python3 assignment_6.py --firstValue 10 --secondValue 20\n\n\nparser = argparse.ArgumentParser(description='add arguments for commandline!')\nparser.add_argument(\"--firstValue\")\nparser.add_argument(\"--secondValue\")\n\nargs = parser.parse_args()\nfirstValue = args.firstValue\nsecondValue = args.secondValue\n\nadditionOfValue = int(firstValue) + int(secondValue)\n\nprint(additionOfValue)\n","sub_path":"assignment1/assignment_6.py","file_name":"assignment_6.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"25139175","text":"def tree_intersection(bt1, bt2):\n common_values = []\n\n def _traverse(node1, node2):\n if node1 is None or node2 is None:\n return\n\n if node1.value == node2.value:\n common_values.append(node1.value)\n\n _traverse(node1.left, node2.left)\n _traverse(node1.right, node2.right)\n \n _traverse(bt1.root, bt2.root)\n return common_values\n\n\"\"\"\nref (https://repl.it/@MohammedGhafri/tree-intersection)\n\n 2 4\n 6 -1 6 9\n 8 5 1 5 8\n \n[6, 8]\n\nRecursion Visualization:\n[]\n1. _travese(node(2), node(4))\n\n 2. _travese(node(6), node(6)). => [6]\n\n 3. _travese(None, node(5)) ...X\n 4. _travese(None, node(1)) ...X\n\n 5. _travese(node(-1), node(9)) => [6]\n\n 6. _travese(None, node(5)) ...X\n 7. _travese(node(8), node(8)) =>[6,8]\n\n 8. _travese(None, None) ...X\n 9. _travese(None, None) ...X\n\"\"\"\n\n\n","sub_path":"data_structures_and_algorithms/challenges/insertion_sort/another_sol.py","file_name":"another_sol.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"190302896","text":"from xpresso.ai.core.data.xdm.unstructured_dataset import UnstructuredDataset\nfrom xpresso.ai.core.data.exploration.dataset_explorer import Explorer\ndataset_text=UnstructuredDataset()\n\nuser_config3 = {\n \"type\": \"FS\",\n \"path\": \"/test_connector/small_size_data/city.txt\"\n}\n\n\ndataset_text.import_dataset(user_config3)\n\nexplorer3=Explorer(dataset_text)\n\nexplorer3.understand(verbose=True)\n# explorer3.explore_unstructured()","sub_path":"Xpresso/qa_unstruct.py","file_name":"qa_unstruct.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"448306976","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport vgg\n\n# Thủ tục này giúp hiển thị ảnh\ndef imshow(img):\n img = img / 2 + 0.5 # Ánh xạ giá trị lại khoảng [0, 1].\n npimg = img.numpy()\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n plt.show()\n\n\ntransform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\ntrainset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=4,\n shuffle=True, num_workers=2)\n\ntestset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=4,\n shuffle=False, num_workers=2)\n\nclasses = ('Máy Bay', 'Ôtô', 'Chim', 'Mèo',\n 'Hươu', 'Chó', 'Ếch', 'Ngựa', 'Thuyền', 'Xe Tải')\n\n# Lấy vài tấm ảnh huấn luyện ngẫu nhiên\n# dataiter = iter(trainloader)\n# images, labels = dataiter.next()\n#\n# # Hiển thị ảnh\n# imshow(torchvision.utils.make_grid(images))\n# # In nhãn\n# print(' / '.join('%5s' % classes[labels[j]] for j in range(4)))\n\n\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 16 * 5 * 5)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\ndevice = torch.device(\"cuda:0\")\n# net = vgg.vgg13(pretrained=True)\nprint('aaa')\n# net.load_state_dict(torch.load('modelvgg'))\nnet = Net()\n# print(net)\n# params = list(net.parameters())\n# print(params[0])\n\nnet.to(device)\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\n\nfor epoch in range(1): # Lặp qua bộ dữ liệu huấn luyện nhiều lần\n running_loss = 0.0\n for i, data in enumerate(trainloader, 0):\n # Lấy dữ liệu\n inputs, labels = data\n # print(inputs.shape)\n inputs, labels = inputs.to(device), labels.to(device)\n\n # Xoá giá trị đạo hàm\n optimizer.zero_grad()\n\n # Tính giá trị tiên đoán, đạo hàm, và dùng bộ tối ưu hoá để cập nhật trọng số.\n outputs = net(inputs)\n print(outputs)\n print(labels)\n loss = criterion(outputs, labels)\n print(loss)\n input('no do')\n loss.backward()\n optimizer.step()\n\n # In ra số liệu trong quá trình huấn luyện\n running_loss += loss.item()\n if i % 2000 == 1999: # In mỗi 2000 mini-batches.\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, running_loss / 2000))\n running_loss = 0.0\n# torch.save(net.state_dict(), 'modelvgg')\nprint('Huấn luyện xong')\n\n# correct = 0\n# total = 0\n# with torch.no_grad():\n# for data in testloader:\n# images, labels = data\n# # inputs, labels = inputs.to(device), labels.to(device)\n# outputs = net(images)\n# # print(outputs)\n# # input()\n# # outputs.to(device)\n# _, predicted = torch.max(outputs, 1)\n# total += labels.size(0)\n# correct += (predicted == labels).sum().item()\n#\n# print('Độ chính xác của mạng trên 10000 ảnh trong tập kiểm tra: %d %%' % (\n# 100 * correct / total))\n\n# class_correct = list(0. for i in range(10))\n# class_total = list(0. for i in range(10))\n# with torch.no_grad():\n# for data in testloader:\n# images, labels = data\n# inputs, labels = inputs.to(device), labels.to(device)\n# outputs = net(images)\n# outputs.to(device)\n# _, predicted = torch.max(outputs, 1)\n# c = (predicted == labels).squeeze()\n# for i in range(4):\n# label = labels[i]\n# class_correct[label] += c[i].item()\n# class_total[label] += 1\n\n\n# for i in range(10):\n# print('Độ chính xác của loại %5s : %2d %%' % (\n# classes[i], 100 * class_correct[i] / class_total[i]))\n# dataiter = iter(testloader)\n# images, labels = dataiter.next()\n#\n# _, predicted = torch.max(outputs, 1)\n","sub_path":"neural.py","file_name":"neural.py","file_ext":"py","file_size_in_byte":4839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"327939755","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 2 15:02:44 2018\n\nTrain WGAN\n\n@author: vayer\n\"\"\"\n#%%\nimport os,sys\n#path='/home/vayer/wgw/gwtest-master/code_deep_ecn'\n#path='/Users/vayer/Documents/cours/deep_ecn_2018/code_deep_ecn/lib'\npath='./code_deep_ecn/lib'\nmodule_path = os.path.abspath(os.path.join(path))\nsys.path.append(module_path)\nfrom dcgan import DCGAN\nfrom utils import make_keras_picklable,ElapsedTimer,sample_images\nimport numpy as np\n\n#%%\nmnist_dcgan = DCGAN()\n\n#%%\ntimer = ElapsedTimer()\nmnist_dcgan.train(epochs=10000, batch_size=256, save_interval=500)\ntimer.elapsed_time()\nmnist_dcgan.save_models(path)\n#%%\n\nsample_images(generator=mnist_dcgan.generator,noise= np.random.normal(0, 1, (5 * 5, 100)))\n\n\n\n#%%\nmnist_dcgan.save_models(path)","sub_path":"courses/deep_ecn_2018/code_deep_ecn/lib/train_dcgan.py","file_name":"train_dcgan.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"580541263","text":"# Copyright (c) Sebastian Scholz\n# See LICENSE for details.\nimport json\nimport logging\n\ntry:\n from urllib import urlencode\nexcept ImportError:\n # noinspection PyUnresolvedReferences\n from urllib.parse import urlencode\n\nfrom twisted.web.server import NOT_DONE_YET\n\nfrom txoauth2.util import addToUrl\n\nOK = 200\nBAD_REQUEST = 400\nUNAUTHORIZED = 401\nFORBIDDEN = 403\nINTERNAL_SERVER_ERROR = 500\nSERVICE_UNAVAILABLE = 503\n\n\nclass OAuth2Error(object):\n \"\"\"\n Represents an OAuth2 error. This is not a Python exception and cannot be raised.\n It is intended to return a json description of the error and setting the response\n code of the request via the generate method, to comply with the OAuth2 specification.\n \"\"\"\n message = None\n detail = None\n errorUri = None\n code = BAD_REQUEST\n _logger = logging.getLogger('txOauth2')\n\n def __init__(self, code, message, detail, errorUri=None):\n self.code = code\n self.message = message\n self.detail = detail\n self.errorUri = errorUri\n\n def _generateErrorBody(self):\n error = {'error': self.message}\n if self.detail is not None:\n error['error_description'] = self.detail\n if self.errorUri is not None:\n error['error_uri'] = self.errorUri\n return error\n\n def generate(self, request):\n \"\"\"\n Set the response code of the request and return a string representing\n the error, which can be written to the request.\n :param request: The request.\n :return: A string representing the error.\n \"\"\"\n request.setResponseCode(self.code)\n request.setHeader('Content-Type', 'application/json;charset=UTF-8')\n request.setHeader('Cache-Control', 'no-store')\n request.setHeader('Pragma', 'no-cache')\n result = json.dumps(self._generateErrorBody()).encode('utf-8')\n self._logger.debug('OAuth2 error: {msg}'.format(msg=result))\n return result\n\n\nclass AuthorizationError(OAuth2Error):\n \"\"\"\n Represents an error can occur during authorization. The OAuth2 specification says\n that these errors should be send to the redirection url with the error details\n encoded into the url parameters of the redirect.\n \"\"\"\n state = None\n\n def __init__(self, code, message, detail, errorUri=None, state=None):\n super(AuthorizationError, self).__init__(code, message, detail, errorUri)\n self.state = state\n\n def _generateErrorBody(self):\n error = super(AuthorizationError, self)._generateErrorBody()\n if self.state is not None:\n error['state'] = self.state\n return error\n\n def generate(self, request, redirectUri=None, errorInFragment=False):\n \"\"\"\n If a redirectUri is given, the request is redirected to the url with the error details\n encoded into the url parameter. Otherwise it behaves like generate in OAuth2Error.\n :param request: The request.\n :param redirectUri: An optional redirect uri.\n :param errorInFragment: Whether or not the error shout be send in the query or fragment.\n :return: NOT_DONE_YET or a string representing the error.\n \"\"\"\n if redirectUri is None:\n return super(AuthorizationError, self).generate(request)\n else:\n request.setResponseCode(self.code)\n errorParameter = self._generateErrorBody()\n self._logger.debug('OAuth2 error: {msg}'.format(msg=errorParameter))\n for key, value in errorParameter.items():\n if not (isinstance(value, str) or isinstance(value, bytes)):\n errorParameter[key] = value.encode('utf-8') # For Python 2 unicode strings\n destination = 'fragment' if errorInFragment else 'query'\n request.redirect(addToUrl(redirectUri, **{destination: errorParameter}))\n request.finish()\n return NOT_DONE_YET\n\n\nclass OAuth2RequestError(OAuth2Error):\n \"\"\" An error that happens during a request to a protected resource. \"\"\"\n _wwwAuthenticateContent = ''\n scope = []\n\n def __init__(self, code, message, detail, scope, errorUri=None, addDetailsToHeader=True):\n super(OAuth2RequestError, self).__init__(code, message, detail, errorUri)\n self.scope = scope\n if addDetailsToHeader:\n self._wwwAuthenticateContent += ',scope=\"' + ' '.join(scope) + '\"'\n self._wwwAuthenticateContent += ',error=\"' + message + '\"'\n self._wwwAuthenticateContent += ',error_description=\"' + detail + '\"'\n if errorUri is not None:\n self._wwwAuthenticateContent += ',error_uri=\"' + errorUri + '\"'\n\n def _generateErrorBody(self):\n body = super(OAuth2RequestError, self)._generateErrorBody()\n body['scope'] = self.scope[0] if len(self.scope) == 1 else self.scope\n return body\n\n def generate(self, request):\n content = 'Bearer realm=\"{realm}\"'.format(realm=request.prePathURL())\\\n + self._wwwAuthenticateContent\n request.setHeader('WWW-Authenticate', content)\n return super(OAuth2RequestError, self).generate(request)\n\n\nclass UnauthorizedOAuth2Error(OAuth2Error):\n \"\"\" Error during a request to the token resource without valid client credentials. \"\"\"\n\n def __init__(self, code, message, detail, errorUri=None):\n super(UnauthorizedOAuth2Error, self).__init__(code, message, detail, errorUri)\n\n def generate(self, request):\n authorizationHeader = request.getHeader(b'Authorization')\n if authorizationHeader is not None:\n authType = authorizationHeader.strip().split(b' ', 1)[0]\n request.setHeader(b'WWW-Authenticate',\n authType + b' realm=\"' + request.prePathURL() + b'\"')\n return super(UnauthorizedOAuth2Error, self).generate(request)\n\n\nclass MissingParameterError(AuthorizationError):\n def __init__(self, name=None, state=None):\n if name is None:\n message = 'A required parameter was missing from the request'\n else:\n message = 'Request was missing the \\'{name}\\' parameter'.format(name=name)\n super(MissingParameterError, self).__init__(BAD_REQUEST, 'invalid_request',\n message, state=state)\n\n\nclass InvalidParameterError(AuthorizationError):\n def __init__(self, name=None, state=None):\n if name is None:\n message = 'A required parameter was invalid'\n else:\n message = 'The parameter \\'{name}\\' is invalid'.format(name=name)\n super(InvalidParameterError, self).__init__(BAD_REQUEST, 'invalid_request',\n message, state=state)\n\n\nclass InsecureConnectionError(AuthorizationError):\n def __init__(self, state=None):\n message = 'OAuth 2.0 requires requests over HTTPS'\n super(InsecureConnectionError, self).__init__(BAD_REQUEST, 'invalid_request',\n message, state=state)\n\n\nclass UnsupportedResponseTypeError(AuthorizationError):\n def __init__(self, responseType, state=None):\n message = 'Obtaining an authorization code using this method ' \\\n 'is not supported: ' + responseType\n super(UnsupportedResponseTypeError, self).__init__(\n BAD_REQUEST, 'unsupported_response_type', message, state=state)\n\n\nclass ServerError(AuthorizationError):\n def __init__(self, state=None):\n message = 'An unexpected condition was encountered and the request could not get fulfilled.'\n super(ServerError, self).__init__(\n SERVICE_UNAVAILABLE, 'server_error', message, state=state)\n\n\nclass TemporarilyUnavailableError(AuthorizationError):\n def __init__(self, state=None):\n message = 'The request could not be handled due to a temporary overloading or maintenance.'\n super(TemporarilyUnavailableError, self).__init__(\n BAD_REQUEST, 'temporarily_unavailable', message, state=state)\n\n\nclass MultipleParameterError(AuthorizationError):\n def __init__(self, parameter=None, state=None):\n message = 'The request contained a duplicate parameter'\n if parameter is not None:\n message += ': ' + parameter\n super(MultipleParameterError, self).__init__(\n BAD_REQUEST, 'invalid_request', message, state=state)\n\n\nclass MalformedParameterError(AuthorizationError):\n def __init__(self, name, state=None):\n message = 'The parameter \\'{name}\\' was malformed'.format(name=name)\n super(MalformedParameterError, self).__init__(\n BAD_REQUEST, 'invalid_request', message, state=state)\n\n\nclass UnauthorizedClientError(AuthorizationError):\n def __init__(self, grantType=None, state=None):\n message = 'The authenticated client is not authorized to use this authorization grant type'\n if grantType is not None:\n message += ': ' + grantType\n super(UnauthorizedClientError, self).__init__(\n BAD_REQUEST, 'unauthorized_client', message, state=state)\n\n\nclass InvalidRedirectUriError(OAuth2Error):\n def __init__(self):\n message = 'Invalid redirection URI'\n super(InvalidRedirectUriError, self).__init__(BAD_REQUEST, 'invalid_request', message)\n\n\nclass InvalidClientIdError(UnauthorizedOAuth2Error):\n def __init__(self):\n message = 'Invalid client_id'\n super(InvalidClientIdError, self).__init__(UNAUTHORIZED, 'invalid_client', message)\n\n\nclass NoClientAuthenticationError(UnauthorizedOAuth2Error):\n def __init__(self):\n message = 'The request was missing client authentication'\n super(NoClientAuthenticationError, self).__init__(UNAUTHORIZED, 'invalid_client', message)\n\n\nclass InvalidClientAuthenticationError(UnauthorizedOAuth2Error):\n def __init__(self):\n super(InvalidClientAuthenticationError, self).__init__(\n UNAUTHORIZED, 'invalid_client', 'The client could not get authenticated.')\n\n\nclass InvalidTokenError(OAuth2Error):\n def __init__(self, tokenType):\n message = 'The provided {type} is invalid'.format(type=tokenType)\n super(InvalidTokenError, self).__init__(BAD_REQUEST, 'invalid_grant', message)\n\n\nclass DifferentRedirectUriError(OAuth2Error):\n def __init__(self):\n message = 'The redirect_uri does not match the ' \\\n 'redirection URI used in the authorization request'\n super(DifferentRedirectUriError, self).__init__(BAD_REQUEST, 'invalid_grant', message)\n\n\nclass InvalidScopeError(AuthorizationError):\n def __init__(self, scope, state=None):\n if isinstance(scope, list):\n scope = ' '.join(scope)\n if isinstance(scope, bytes):\n scope = scope.decode('utf-8', errors='replace')\n message = 'The provided scope is invalid: ' + scope\n super(InvalidScopeError, self).__init__(BAD_REQUEST, 'invalid_scope', message, state=state)\n\n\nclass UnsupportedGrantTypeError(OAuth2Error):\n def __init__(self, grantType=None):\n message = 'The authorization grant type is not supported'\n if grantType is not None:\n message += ': ' + grantType\n super(UnsupportedGrantTypeError, self).__init__(\n BAD_REQUEST, 'unsupported_grant_type', message)\n\n\nclass MultipleClientCredentialsError(OAuth2Error):\n def __init__(self):\n super(MultipleClientCredentialsError, self).__init__(\n BAD_REQUEST, 'invalid_request', 'The request contained multiple client credentials')\n\n\nclass MultipleClientAuthenticationError(OAuth2Error):\n def __init__(self):\n message = 'The request utilized more than one mechanism for authenticating the client'\n super(MultipleClientAuthenticationError, self).__init__(\n BAD_REQUEST, 'invalid_request', message)\n\n\nclass MalformedRequestError(OAuth2Error):\n def __init__(self, msg=None):\n message = 'The request was malformed'\n if msg is not None:\n message += ': ' + msg\n super(MalformedRequestError, self).__init__(BAD_REQUEST, 'invalid_request', message)\n\n\nclass UserDeniesAuthorization(AuthorizationError):\n def __init__(self, state=None):\n message = 'The resource owner denied the request'\n super(UserDeniesAuthorization, self).__init__(OK, 'access_denied', message, state=state)\n\n\nclass MissingTokenError(OAuth2RequestError):\n def __init__(self, scope):\n message = 'No access token provided'\n super(MissingTokenError, self).__init__(\n UNAUTHORIZED, 'invalid_request', message, scope, addDetailsToHeader=False)\n\n\nclass InvalidTokenRequestError(OAuth2RequestError):\n def __init__(self, scope):\n message = 'The access token is invalid'\n super(InvalidTokenRequestError, self).__init__(\n UNAUTHORIZED, 'invalid_token', message, scope)\n\n\nclass InsufficientScopeRequestError(OAuth2RequestError):\n def __init__(self, scope):\n message = 'The request requires higher privileges than provided by the access token'\n super(InsufficientScopeRequestError, self).__init__(\n FORBIDDEN, 'insufficient_scope', message, scope)\n\n\nclass MultipleTokensError(OAuth2RequestError):\n def __init__(self, scope):\n message = 'The request contained multiple access tokens'\n super(MultipleTokensError, self).__init__(BAD_REQUEST, 'invalid_request', message, scope)\n","sub_path":"txoauth2/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":13423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"135137738","text":"\"\"\"\nTest two tone evoked potentials for JR\n\"\"\"\nimport numpy as np\nimport os.path as op\nimport matplotlib.pyplot as plt\nfrom mne import find_events, Epochs\nfrom mne.io import read_raw_kit\nfrom mne.decoding import GeneralizationAcrossTime\nfrom jr.gat import scorer_auc\nfrom jr.meg import least_square_reference\nfrom jr.utils import OnlineReport\nfrom data.R1022_160204 import meg_files, session\n\nreport = OnlineReport()\n\n# Paths\n# data_path = '/media/DATA/Pro/Projects/NewYork/audio_wm/data/'\ndata_path = op.join('/media/jrking/harddrive/Audio_sequence/data/', session)\nrun = meg_files.query('typ == \"two_tones\"')\nmeg = op.join(data_path, run.fname.get_values()[0])\nmrk = op.join(data_path, run.marker.get_values()[0])\nhsp = op.join(data_path, run.hsp.get_values()[0])\nelp = op.join(data_path, run.elp.get_values()[0])\nbad_channels = run.bad_channels.get_values()[0]\n\n# Read data\nraw = read_raw_kit(meg, preload=True, mrk=mrk, elp=elp, hsp=hsp)\nfor bad in bad_channels:\n raw.info['bads'] += [bad]\n\n# Get events\nevents = find_events(raw)\nevent_id = dict(low=np.min(events[:, 2]), high=np.max(events[:, 2]))\n\n# Apply Least Square projection from ref channels\nraw = least_square_reference(raw)\n\n# Interpolate bad channels\nraw.interpolate_bads()\n\n# Filter\nraw.filter(.51, h_freq=30.0)\n\n# Epoch\nepochs = Epochs(raw, events, tmin=-.200, tmax=.700, baseline=None,\n preload=True, verbose=False, event_id=event_id)\n\n# Plot evoked potentials\nevoked = epochs.average()\nevoked.plot_joint(times=[0., .100, .300, .500], ts_args=dict(gfp=True),\n topomap_args=dict(sensors=False), show=False)\nreport.add_figs_to_section(plt.gcf(), 'all', 'ERF')\n\nevoked = epochs['high'].average() - epochs['low'].average()\nevoked.plot_joint(times=[0., .100, .300, .500], ts_args=dict(gfp=True),\n topomap_args=dict(sensors=False), show=False)\nreport.add_figs_to_section(plt.gcf(), 'high - low', 'ERF')\n\n# Decoding\nepochs.crop(0, .700)\nepochs.decimate(10)\ngat = GeneralizationAcrossTime(predict_method='predict_proba',\n scorer=scorer_auc, n_jobs=-1)\ngat.fit(epochs)\nscores = gat.score(epochs)\ngat.plot_diagonal(show=False)\nreport.add_figs_to_section(plt.gcf(), 'Decoding pitch', 'decoding')\ngat.plot(show=False)\nreport.add_figs_to_section(plt.gcf(), 'GAT pitch', 'decoding')\n\nreport.save()\n","sub_path":"scripts/analysis/pilots/R1022_2.4.16/two_tones.py","file_name":"two_tones.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"498795588","text":"__author__ = '未昔'\n__date__ = '2018/11/27 10:35'\n\nfrom flask import render_template,g\nimport datetime\n\n\n\ndef ops_render( context = {}):\n return render_template( **context )\n\n\n\ndef getCurrentData( format = \"%Y-%m-%d %H:%M:%S\"):\n return datetime.datetime.now().strftime( format )\n\n\n'''\n根据某个字段获取一个dic出来\n'''\ndef getDictFilterField( db_model,select_filed,key_field,id_list ): # 数据表。希望查询的字段。希望作为字典里面key的字段。希望的字段值\n ret = {}\n query = db_model.query\n if id_list and len( id_list ) > 0:\n query = query.filter( select_filed.in_( id_list ) )\n\n list = query.all()\n if not list:\n return ret\n for item in list:\n if not hasattr( item,key_field ):\n break\n\n ret[ getattr( item,key_field ) ] = item\n return ret\n\n\"\"\"\n 从一个对象里面取出结果\n\"\"\"\ndef selectFilterObj( obj,field ):\n ret = []\n for item in obj:\n if not hasattr(item, field ):\n break\n if getattr( item,field ) in ret:\n continue\n ret.append( getattr( item,field ) ) # 添加结果,统一返回\n return ret\n\n","sub_path":"python/新肺炎-v4.0/common/libs/Helper.py","file_name":"Helper.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"28431013","text":"import numpy as np\n\nimport plotly.graph_objs as go\nfrom plotly.offline import iplot\n\nfrom palantiri.BasePlotHandlers import PlotHandler\n\n\nclass RegressionPlotHandler(PlotHandler):\n \"\"\" Handles all the plots related of the chosen regressor. \"\"\"\n\n def __init__(self, dataset, trained_regressor, **params):\n \"\"\"\n Initialization function\n :param dataset: the dataset in a dict format with the following keys:\n 'data' - numpy array with all the data points.\n 'target' - the label of the corresponding data point.\n 'target_names' - the target name.\n\n :param trained_regressor: sklearn regressor(trained / fitted)..\n :param params: other params\n \"\"\"\n\n self._dataset = dataset\n self._trained_regressor = trained_regressor\n\n self.prediction_figure = None\n\n self.target_name = 'Target'\n\n super(RegressionPlotHandler, self).__init__(**params)\n\n @classmethod\n def from_pandas_dataframe(cls, dataframe, trained_regressor, **params):\n \"\"\"\n Constructing the handler from a pandas dataframe.\n :param dataframe: the dataframe form which the handler is constructed.\n :param trained_regressor: sklearn regressor (trained / fitted).\n :param params: other params.\n :return: returns the classifier plot handler object.\n \"\"\"\n\n assert 'target' in dataframe.columns.values, 'target values not in dataframe'\n\n dataset = dict()\n dataset['data'] = dataframe.drop('target', axis=1).values\n dataset['target'] = dataframe['target'].values\n dataset['feature_names'] = dataframe.drop('target', axis=1).columns.values\n return cls(dataset, trained_regressor, **params)\n\n @property\n def trained_regressor(self):\n \"\"\"\n The trained regressor.\n :return: The regressor in sklearn format.\n \"\"\"\n return self._trained_regressor\n\n @property\n def dataset(self):\n \"\"\"\n The dataset\n :return: The dataset as a dictionary\n \"\"\"\n return self._dataset\n\n @dataset.setter\n def dataset(self, dataset):\n \"\"\"\n The dataset setter.\n :param dataset: the new dataset\n \"\"\"\n self._dataset = dataset\n\n def build_prediction_figure(self, figure_layout):\n \"\"\"\n Building the regression figure.\n :param figure_layout: figure layout - plot.ly layout object.\n \"\"\"\n\n pass\n\n def plot_prediction(self, figure_layout=None):\n \"\"\"\n Plotting the regression figure with plot.ly's iplot function.\n :param figure_layout: figure layout - plot.ly layout object.\n \"\"\"\n\n if not figure_layout:\n figure_layout = go.Layout(title=dict(text='Regression Plot', x=0.5))\n\n if not self.prediction_figure:\n self.build_prediction_figure(figure_layout)\n else:\n self.prediction_figure['layout'].update(figure_layout)\n\n iplot(self.prediction_figure)\n\n def save_prediction_figure(self, file_name):\n \"\"\"\n Saving the prediction figure as an html file.\n :param file_name: the html file name.\n \"\"\"\n\n self.save_figure(self.prediction_figure, file_name)\n\n\nclass OneDimensionalRegressionPlotHandler(RegressionPlotHandler):\n \"\"\" Handles all the plots related of the chosen 1D regression. \"\"\"\n\n def __init__(self, dataset, trained_regressor, **params):\n \"\"\"\n The initialization function of the 2D classifier plot handler.\n :param dataframe: the dataframe form which the handler is constructed.\n :param trained_regressor: sklearn regressor (trained / fitted).\n :param params: other params.\n \"\"\"\n dataset['data'] = dataset['data'][:, :1]\n\n super(OneDimensionalRegressionPlotHandler, self).__init__(dataset, trained_regressor, **params)\n\n def build_prediction_figure(self, figure_layout, step_size=0.1, x_range=None):\n \"\"\"\n Building the regression figure.\n :param figure_layout: figure layout - plot.ly layout object.\n :param step_size: resolution of the x-axis.\n :param x_range: the range of the prediction (x-axis),\n list of 2 numbers - indicating the start and end of the range\n if none will take the minimum and maximum of the data set.\n \"\"\"\n\n if not x_range:\n x = np.arange(min(self.dataset['data']), max(self.dataset['data']), step_size).reshape(-1, 1)\n else:\n x = np.arange(min(x_range), max(x_range), step_size).reshape(-1, 1)\n\n data = [go.Scatter(x=self.dataset['data'][:, 0],\n y=self.dataset['target'],\n showlegend=False,\n hoverinfo='skip',\n mode='markers',\n marker=dict(\n line=dict(color='black', width=1))),\n go.Scatter(x=x.ravel(),\n y=self.trained_regressor.predict(x).ravel(),\n hoverinfo='y',\n showlegend=False,\n mode='lines')]\n\n if 'feature_names' in self.dataset.keys():\n figure_layout['xaxis'].update({'title': self.dataset['feature_names'][0]})\n figure_layout['yaxis'].update({'title': self.target_name})\n\n self.prediction_figure = go.Figure(data=data, layout=figure_layout)\n\n\nclass TwoDimensionalRegressionPlotHandler(RegressionPlotHandler):\n \"\"\" Handles all the plots related of the chosen regressor on 2D. \"\"\"\n\n def __init__(self, dataset, trained_regressor, **params):\n \"\"\"\n The initialization function of the 3D classifier plot handler.\n :param dataframe: the dataframe form which the handler is constructed.\n :param trained_regressor: sklearn regressor(trained / fitted).\n :param params: other params.\n \"\"\"\n\n dataset['data'] = dataset['data'][:, :2]\n\n super(TwoDimensionalRegressionPlotHandler, self).__init__(dataset, trained_regressor, **params)\n\n def build_prediction_figure(self, figure_layout=go.Layout(), x_range=None, y_range=None, step_size=0.1):\n \"\"\"\n Building the regression figure.\n :param figure_layout: figure layout - plot.ly layout object.\n :param step_size: resolution of the x-axis.\n :param x_range: the range of the prediction (x-axis),\n list of 2 numbers - indicating the start and end of the range\n if none will take the minimum and maximum of the data set.\n :param y_range: similar to x_range for the y-axis.\n \"\"\"\n\n if not x_range:\n x = np.arange(min(self.dataset['data'][:, 0]), max(self.dataset['data'][:, 0]), step_size)\n else:\n x = np.arange(min(x_range), max(x_range), step_size)\n\n if not y_range:\n y = np.arange(min(self.dataset['data'][:, 1]), max(self.dataset['data'][:, 1]), step_size)\n else:\n y = np.arange(min(y_range), max(y_range), step_size)\n\n x_mesh, y_mesh = np.meshgrid(x, y)\n\n z = self.trained_regressor.predict(np.column_stack((x_mesh.ravel(), y_mesh.ravel()))).reshape(x_mesh.shape)\n\n data = [go.Surface(x=x, y=y, z=z,\n showscale=False,\n colorscale='Viridis',\n hoverinfo='z'),\n go.Scatter3d(x=self.dataset['data'][:, 0],\n y=self.dataset['data'][:, 1],\n z=self.dataset['target'],\n hoverinfo='skip',\n mode='markers',\n marker=dict(showscale=False,\n colorscale='Reds',\n line=dict(color='black', width=0.3)))]\n\n if 'feature_names' in self.dataset.keys():\n figure_layout['scene'].update(\n dict(xaxis={'title': self.dataset['feature_names'][0]},\n yaxis={'title': self.dataset['feature_names'][1]},\n zaxis={'title': self.target_name}))\n\n self.prediction_figure = go.Figure(data=data, layout=figure_layout)\n","sub_path":"palantiri/RegressionPlotHandlers.py","file_name":"RegressionPlotHandlers.py","file_ext":"py","file_size_in_byte":8285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"164708700","text":"import re\n\n\ndef fun(s):\n regex = r'[\\w-]+@[A-Za-z0-9]*\\..{1,3}'\n\n if re.fullmatch(regex, s):\n return s\n\n\ndef filter_mail(emails):\n return list(filter(fun, emails))\n\n\nif __name__ == '__main__':\n n = int(input())\n emails = []\n for _ in range(n):\n emails.append(input())\n\nfiltered_emails = filter_mail(emails)\nfiltered_emails.sort()\nprint(filtered_emails)\n","sub_path":"hackerrank/others/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"323907101","text":"# Dependencyhandler function START \ndef dependencyhandler(depend):\n result=0\n depin=input(\"Module missing ! named \"+str(depend)+\" !\\nIf you want,I can install it by myself automatically.\\nTo do so make sure you have a working internet connection because I will Need it to install Module.\\n Y for yes and N for no?\")\n if(depin==\"y\" or depin==\"Y\"):\n from pip._internal import main\n leftdep=[]\n for go in depend:\n package=str(go)\n x=main(['install', package,'--user'])\n if not x:\n print(\"Successfuly installed Module \"+package+\" !\")\n else:\n leftdep.append(go)\n print(\"Sorry I was unable to install that module \"+package+\"! Please try running 'pip install \"+package+\"' in your command line(terminal or cmd)\") \n if len(leftdep)==0:\n print(\"############################################\\n\\n\\nAll given Modules Installed!\")\n result=1\n elif len(leftdep)0):\n x=input(\"Enter module to be fixed:\")\n depend.append(x)\n we=input(\"Want to add more module ? Y for yes and N for no. : \")\n if we!=\"Y\" and we!=\"y\":xx=-1\n print(\"Modules to be instlled : \"+str(depend))\n q=input(\"Fix ? Y for yes N for no. : \")\n if q==\"y\" or q==\"Y\":dependencyhandler(depend)","sub_path":"dependencyhandler.py","file_name":"dependencyhandler.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"103249491","text":"#!/usr/bin/env python\n\"\"\"\nExtract the data out of .mat files and save as .wav files.\n\"\"\"\n\nimport sys\nimport os\nimport glob\nimport numpy as np\nfrom scipy import io\nfrom scikits import audiolab\n\n\ndef extract(path):\n print('Extracting data into %s...' % path)\n filelist = glob.glob(os.path.join(path, '*.mat'))\n for srcfile in filelist:\n wavwrite(srcfile)\n\n\ndef wavwrite(srcfile):\n try:\n mat = io.loadmat(srcfile)\n except ValueError:\n print('Could not load %s' % srcfile)\n return\n\n dat = mat['dataStruct'][0, 0][0]\n mn = dat.min()\n mx = dat.max()\n mx = float(max(abs(mx), abs(mn)))\n if mx != 0:\n dat *= 0x7FFF / mx\n dat = np.int16(dat)\n\n for elec in range(16):\n dstfile = srcfile.replace('mat', str(elec) + '.wav')\n aud = dat[:, elec]\n audiolab.wavwrite(aud, dstfile, fs=400, enc='pcm16')\n\n\nif len(sys.argv) < 2:\n print('Usage %s /path/to/data' % sys.argv[0])\n sys.exit(0)\n\nfor subj_id in range(1, 4):\n path = os.path.join(sys.argv[1], 'train_' + str(subj_id))\n extract(path)\n","sub_path":"prep.py","file_name":"prep.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"153725913","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 6 12:52:04 2021\n\n@author: danie\n\"\"\"\n\nimport numpy as np\n#np.random.seed(0)\nimport itertools\nimport re\n\ndef dist(X,x,y,linkage_method='single'):\n D = []\n if type(x)==int:\n x = [x]\n if type(y)==int:\n y = [y]\n for i in itertools.product(x,y):\n D.append(sum((X[i[0]]-X[i[1]])**2)**.5)\n if linkage_method=='single':\n return(min(D))\n if linkage_method=='complete':\n #print(x,y,D,max(D))\n #print(D,max(D))\n return(max(D))\n if linkage_method=='average':\n #print(x,y,D,np.mean(D))\n #print(D,np.mean(D))\n return(np.mean(D))\n #m = lambda x1,x2 :.5*np.array(x1)+ .5*np.array(x2)\n\ndef flatten(TheList):\n a = str(TheList)\n b,crap = re.subn(r'[\\[,\\]]', ' ', a)\n c = b.split()\n d = [int(x) for x in c]\n return list(d)\n\nclass HClustering:\n \"\"\"\n # ######################################################################################\n #\n # Class for building Hierarchical Clustering Model\n #\n # hyperparameters : \n # - linkage_method, string (number of cluster ) ,\n # - ...,\n # - ...\n # \n # ######################################################################################\n \"\"\" \n def __init__(self):\n self.unused = []\n self.next_process = []\n self.clusters = [[],[]]\n\n\n \n def fit(self,X,linkage_method='single'):\n \"\"\"\n # $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n #\t\t\tFunction for training : finds the optimal centroids\n # $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n \"\"\"\n self.unused = [i for i in range(X.shape[0])]\n self.next_process = [i for i in range(X.shape[0])]\n \n #while len(self.unused)!=0: \n while len(set(flatten(self.clusters[-2:])))!=X.shape[0]:\n #print(' - unused',self.unused)\n count = 0\n dist_list =[]\n \n # ###### ------------- Distance Matrix calculation -----------------\n while count != (len(self.next_process)*(len(self.next_process)-1)/2):\n for c in self.next_process[count+1:]:\n dist_list.append((dist(X,self.next_process[count],c,linkage_method=linkage_method),[self.next_process[count],c]))\n count+=1\n dist_list.sort(reverse=False)\n \n # ######------------ Minimum Distance pair (can be 2 clusters) ------------------\n cl = dist_list[0][1]\n \n # --------- Loop trough the elements of the minimum distance pair ------------\n for i in list(set(flatten(cl))): \n # ###### try to remove element of min distance pair from the unused points list\n try:\n self.unused.remove(i)\n # ###### if the element is a previous cluster, the element\n # ###### is not in the unused list, so nothing happen\n except :\n pass\n \n try:\n # ###### try to remove the elements of min distance pair from the next_process points list...\n for i in cl:\n try:\n self.next_process.remove(i) \n except :\n pass\n except :\n # ###### ...in cas of failure, that mean that the element is a cluster\n # ###### that need to be flatened before processed\n for i in list(set(flatten(cl))):\n try:\n self.next_process.remove(i) \n except :\n pass\n \n # ###### add minimum distance pair to the next process list\n self.next_process.append(flatten(cl))\n #print(\"-------- Next Process --------\\n\\t\"+str(next_process))\n \n # ###### add minimum distance pair to the cluster list\n self.clusters.append(cl)\n #print(self.clusters)\n #self.unused.extend(flatten(cl))\n #self.next_process.extend(flatten(cl))\n self.clusters=self.clusters[2:]","sub_path":"Hierarchical_Clustering_From_Scratch/mypackage/mypackage/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":4494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"414283321","text":"from torch.utils import data\nimport os\n\n# 读取图片名,标签 并 拼接成完成图片路径\ndef get_image(txt_path, file_path):\n imgs = []\n label = []\n with open(txt_path, 'r') as lines:\n for line in lines:\n # line ../data/\n # emotion/2smile/4353smile.jpg 2\n img_path = os.path.join(file_path, line[:-3])\n imgs.append(img_path)\n label.append(line[-1])\n return imgs, label\n\nif __name__ == '__main__':\n images, label = get_image('../data/all_shuffle_train.txt', '../data/train')\n print(len(label))\n print(images[:2])","sub_path":"datasets/Expression.py","file_name":"Expression.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"46761961","text":"import random\r\nimport os\r\nimport sys\r\nimport time\r\n\r\nsuits = ['♠','♣','♦','♥']\r\nranks = ['two','three','four','five','six','seven','eight','nine','ten','jack','queen','king','ace']\r\nvalues = {'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,'ten':10,'jack':10,'queen':10,'king':10,'ace':11}\r\n\r\ndeck=[]\r\nfor suit in suits:\r\n for rank in ranks:\r\n deck.append(suit+\"-\"+rank)\r\n\r\ndef shuffle():\r\n random.shuffle(deck) \r\n\r\ndef print_card(card):\r\n card_list = card.split('-')\r\n symbol = card_list[0]\r\n if card_list[1] in ['jack','queen','king','ace']:\r\n \tvalue = card_list[1]\r\n else:\r\n \tvalue = values[card_list[1]]\r\n print(\"---------------\")\r\n print(f\"|{symbol}{value} |\\n\\n\")\r\n \r\n print(f\"| {symbol}{value} |\\n\\n\")\r\n \r\n print(f\"| {symbol}{value}|\")\r\n print(\"---------------\") \r\n\r\ndef draw_card():\r\n ind = random.randint(0,len(deck))\r\n card=deck[ind]\r\n deck.pop(ind)\r\n return card\r\n\r\ndef plsum():\r\n\tplayersum=0\r\n\tfor c in playercards:\r\n\t\tst=c.split('-')\r\n\t\tplayersum+=values[st[1]]\r\n\treturn playersum\r\n\r\n\r\ndef end():\r\n\tsys.exit(0)\r\nos.system('cls')\r\nplayersum = 0 \r\nhousesum = 0\r\ngame = 'on'\r\nplayercards=[]\r\nhousecards=[]\r\nshuffle()\r\nbet=0\r\nchips=100\r\nplayercards.append(draw_card())\r\nplayercards.append(draw_card())\r\nhousecards.append(draw_card())\r\nhousecards.append(draw_card())\r\nprint(\"House cards:\")\r\nprint(f\"***Card 1 is enclosed***{housecards[0]}\")\r\ntime.sleep(1)\r\nprint_card(housecards[1])\r\nfor c in housecards:\r\n\tst=c.split('-')\r\n\thousesum+=values[st[1]]\r\nprint(\"Players cards:\")\r\nfor c in playercards:\r\n\ttime.sleep(1)\t\r\n\tprint_card(c)\r\n\r\nprint(f\"The sum of ur cards is {plsum()}\")\r\nwhile game == 'on':\r\n\tprint(f\"No of chips available with player is: {chips}\")\r\n\twhile (bet<=0 or bet>100):\r\n\t\tbet=int(input(\"Enter the bet amount\\n\"))\r\n\tturn = \"p\"\r\n\twhile turn == 'p':\r\n\t\tplayerchoice=int(input(\"Enter 1 to hit\\nEnter 2 to stand\\n\"))\r\n\t\tif playerchoice==1:\r\n\t\t\ttime.sleep(1)\r\n\t\t\tdc = draw_card()\r\n\t\t\tprint_card(dc)\r\n\t\t\tplayercards.append(dc)\r\n\t\t\tpsum=plsum()\r\n\t\t\tprint(f\"The sum of ur cards is {psum}\")\r\n\t\t\tif psum>21:\r\n\t\t\t\tprint(\"Player lost!!\")\r\n\t\t\t\tchips-=bet\r\n\t\t\t\tprint(f\"The player chips are {chips}\")\r\n\t\t\t\tend()\r\n\t\telse:\r\n\t\t\tturn = 'h'\r\n\r\n\twhile turn=='h':\r\n\t\tprint(\"House turn!!\")\r\n\t\ttime.sleep(5)\r\n\t\thousechoice=1\r\n\t\tif housesum>17:\r\n\t\t\thousechoice = random.randint(1,2)\r\n\t\tif housechoice == 1:\r\n\t\t\tprint(\"House wants to HIT\")\r\n\t\t\ttime.sleep(1)\r\n\t\t\tdc = draw_card()\r\n\t\t\tprint_card(dc)\r\n\t\t\thousecards.append(dc)\r\n\t\t\tdc=c.split('-')\r\n\t\t\thousesum+=values[dc[1]]\r\n\t\t\tif housesum>21:\r\n\t\t\t\tprint(f\"House sum = {housesum}\\nHouse lost!!\")\r\n\t\t\t\tchips+=(bet*2)\r\n\t\t\t\tprint(f\"The player chips are {chips}\")\r\n\t\t\t\tend()\r\n\t\telse:\r\n\t\t\tprint(\"The house wants to stand\\n\\n\")\r\n\t\t\tprint(f\"The sum of house cards is {housesum}\")\r\n\t\t\tif housesum factor or change < 1.0 / factor:\n table.append(\n (change, before[name], after[name], name, benchmark))\n if change > factor:\n slowed_down = True\n\n print(\"\")\n\n if not len(table):\n color_print(\"BENCHMARKS NOT SIGNIFICANTLY CHANGED.\\n\", 'green')\n return 0\n\n table.sort(reverse=True)\n\n color_print(\n \"{0:40s} {1:>8} {2:>8} {3:>8}\\n\".format(\"BENCHMARK\", \"BEFORE\", \"AFTER\", \"FACTOR\"),\n 'blue')\n for change, before, after, name, benchmark in table:\n before_display = util.human_value(before, benchmark['unit'])\n after_display = util.human_value(after, benchmark['unit'])\n\n print(\"{0:40s} {1:>8} {2:>8} {3:.8f}x\".format(\n truncate_left(name, 40),\n before_display, after_display, change))\n\n print(\"\")\n color_print(\n \"SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY.\\n\", 'red')\n\n return slowed_down\n","sub_path":"asv/commands/continuous.py","file_name":"continuous.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"187016187","text":"fib_dict = {1:1, 2:1}\n\ndef fib_memo(n):\n if n in fib_dict:\n return fib_dict[n]\n else:\n fib_dict[n] = fib_memo(n-1) + fib_memo(n-2)\n return fib_dict[n]\n\ndef find_1000_digit_fib_num():\n count = 3\n while True:\n if len(str(fib_memo(count))) >= 1000:\n return count\n count += 1\n\nprint(find_1000_digit_fib_num())\n","sub_path":"Prob25.py","file_name":"Prob25.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"108408900","text":"import turtle\nimport math\n\ndef drawTri(tur, len):\n if len>20:\n tri(tur,0.5*len)\n else:\n tur.down()\n tur.fd(0.25*len)\n tur.left(120)\n tur.fd(0.5*len)\n tur.left(120)\n tur.fd(0.5*len)\n tur.left(120)\n tur.fd(0.25*len)\n\ndef tri(tur, len):\n \"\"\"\n #draw triangles with turtle\n :param len: the len of the square\n :param tur:\n :return:\n \"\"\"\n\n #right\n tur.up()\n tur.fd(0.25*len)\n tur.down()\n drawTri(tur,len)\n\n #left\n tur.up()\n tur.backward(0.5*len)\n tur.down()\n drawTri(tur,len)\n\n #top\n tur.up()\n tur.fd(0.25*len)\n tur.left(90)\n tur.fd(math.sqrt(3)*0.25*len)\n tur.down()\n tur.right(90)\n drawTri(tur,len)\n\n tur.up()\n tur.right(90)\n tur.fd(math.sqrt(3)*0.25*len)\n tur.left(90)\n tur.down()\n\n#creates window\nmyWin = turtle.Screen()\n#creates turtle\nrp = turtle.Turtle()\n#draw square\nrp.up()\nrp.right(90)\nrp.fd(200)\nrp.left(90)\ntri(rp, 500)\n#close the window with a click\nmyWin.exitonclick()\n","sub_path":"Q1-3/Turtle/triangle.py","file_name":"triangle.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"207755187","text":"import scipy as sp\r\nimport scipy.signal as sg\r\nimport numpy as np\r\nimport pylab as pyl\r\nimport scipy.misc as msc\r\nimport scipy.ndimage as ndimage\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef createGaussianFilter( sigma=1.0, sigmax=None, sigmay=None, size=None ):\r\n\r\n sigmax = sigmax or sigma\r\n sigmay = sigmay or sigma\r\n\r\n size = size or (int( np.ceil( sigmax * 2.575 ) * 2 + 1 ), int( np.ceil( sigmay * 2.575 ) * 2 + 1 ))\r\n \r\n msize = size[0]\r\n x = np.arange( msize )\r\n gx = np.exp( -0.5 * ( ( x-msize/2) / sigmax ) ** 2 )\r\n gx /= gx.sum()\r\n\r\n nsize = size[1]\r\n y = np.arange( nsize )\r\n gy = np.exp( -0.5 * ( ( y-nsize / 2 ) / sigmay ) ** 2 )\r\n gy /= gy.sum()\r\n\r\n G = np.outer( gx, gy )\r\n G /= G.sum()\r\n return G, gx, gy\r\n\r\n\r\n\r\ndef createGaussianFilterBySize( size=(3,3) ):\r\n sigmas = [((s-1)/2)/2.575 for s in size]\r\n return createGaussianFilter(sigmax = sigmas[0], sigmay=sigmas[1], size=size)\r\n\r\ndef polartocartesian(rho, phi):\r\n x = rho * np.cos(phi)\r\n y = rho * np.sin(phi)\r\n return(x, y)\r\n\r\ndef cartesiantopolar(x, y):\r\n rho = np.sqrt(x**2 + y**2)\r\n phi = np.arctan2(y, x)\r\n return(rho, phi)\r\n\r\n\r\ndef transform_xy(Im):\r\n (sy,sx) = Im.shape\r\n mu = [sy/2,sx/2]\r\n #mu = [180,180]\r\n Final = np.zeros((sy,sx))\r\n thr = 2*np.pi\r\n r_i = np.linspace(0,np.sqrt(mu[1]**2 + mu[0]**2), sy)\r\n theta_i = np.linspace(0, thr, sy)\r\n r_grid, theta_grid = np.meshgrid(r_i, theta_i)\r\n _, gy, gx = createGaussianFilterBySize(size=(21,21))\r\n xo, yo = polartocartesian(r_grid,theta_grid)\r\n xo = xo + mu[1]\r\n yo = yo + mu[0]\r\n C = np.vstack((yo.flatten(),xo.flatten()))\r\n\r\n transformed = ndimage.interpolation.map_coordinates(Im,C).reshape(sy,sx)\r\n transformed_blur = ndimage.convolve1d(transformed,gx,axis=0).T[::-1,:]\r\n\r\n mul_fac = sx/np.sqrt(mu[1]**2 + mu[0]**2)\r\n ys = mu[0] - pyl.arange(sy)\r\n xs = mu[1] - pyl.arange(sx)\r\n xq, yq = np.meshgrid(xs,ys)\r\n r,t = cartesiantopolar(yq,xq)\r\n inx = abs(sx - t * (sx/thr))%(sx-1)\r\n iny = abs(sy - r*mul_fac)\r\n X = np.vstack((iny.flatten(),inx.flatten()))\r\n final = ndimage.interpolation.map_coordinates(transformed_blur,X).reshape(sy,sx).T[:,::-1]\r\n\r\n return transformed, transformed_blur, final\r\n\r\nface = msc.imread(\"bauckhage.jpg\", flatten=True).astype('float')\r\nclock = msc.imread(\"clock.jpg\", flatten=True).astype('float')\r\nflag = msc.imread(\"flag.png\", flatten=True).astype('float')\r\n\r\nresult = transform_xy(flag)\r\nplt.figure()\r\nplt.imshow(result[0], cmap=\"Greys_r\")\r\nmsc.imsave(\"resulting_images/one_.png\", result[0])\r\nplt.show()\r\n\r\nplt.imshow(result[1], cmap=\"Greys_r\")\r\nmsc.imsave(\"resulting_images/two_.png\", result[1])\r\nplt.show()\r\n\r\nplt.imshow(result[2], cmap=\"Greys_r\")\r\nmsc.imsave(\"resulting_images/fin_.png\", result[2])\r\nplt.show()\r\n","sub_path":"Project 3/Project3_Task4.py","file_name":"Project3_Task4.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"452607553","text":"import os\ndef isAdam(n):\n\tcopy1 = n\n\tsquare1 = n ** 2\n\tsum1 = 0\n\twhile (copy1 > 0):\n\t\tremainder1 = copy1 % 10\n\t\tsum1 = (sum1 * 10) + remainder1\n\t\tcopy1 = copy1 // 10\n\tsquare2 = sum1 ** 2\n\tcopy2 = square2\n\tsum2 = 0\n\twhile (copy2 > 0):\n\t\tremainder2 = copy2 % 10\n\t\tsum2 = (sum2 * 10) + remainder2\n\t\tcopy2 = copy2 // 10\n\tif (sum2 == square1):\n\t\tprint(n,\"is Adam.\")\n\telse:\n\t\tprint(n,\"is not Adam.\")\nnumber = int(input(\"Number to check if Adam: \"))\nisAdam(number)\nos.system(\"pause\")","sub_path":"How to Code Together using Python/PYTHON AGAIN/adam.py","file_name":"adam.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"499697377","text":"# coding=utf-8\nfrom __future__ import absolute_import #导入3.x的特征函数\nfrom __future__ import print_function\n\nimport pandas as pd #导入Pandas\nimport numpy as np #导入Numpy\nimport jieba #导入结巴分词\n\nfrom keras.preprocessing import sequence\nfrom keras.optimizers import SGD, RMSprop, Adagrad\nfrom keras.utils import np_utils\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.recurrent import LSTM, GRU\n\n# coding=utf-8\nimport urllib2\nimport json\nfrom elasticsearch import Elasticsearch\nimport re\n\n\nprint('start model...')\n\n\ndef filer_str(temp):\n\tstring = re.sub(\"[\\s+\\.\\!\\/_,$%^*(+\\\"\\']+|[+——!,。?、~@#¥%……&*()]+\".decode(\"utf8\"), \"\".decode(\"utf8\"),temp)\n\tprint(string)\n\treturn string\n\ndef save_raw_data(file,data):\t\n\tfile.write( data.encode('utf8').replace('\\n','').replace('\\'','').replace('\"','').replace(',','') + '\\n')\n\n\ndef fenci(summary):\n\tnlp_features_list = \"\"\n\tnlp_features = pseg.cut(summary)\n\tfor w in nlp_features:\n\t\tif w.flag == 'ns' or w.flag == 'n' or w.flag == 'ng' or w.flag == 'nl' or \"a\" in w.flag or \"v\" in w.flag or w.flag == 't':\n\t\t\t#print w.word + w.flag \n\t\t\tnlp_features_list = nlp_features_list + \" \" + w.word \n\t##jieba.analyse.extract_tags(summary,allowPOS=('ns', 'n','ng','nl','t','v','a'), topK=1000)\n\t#nlp_features_list = ' '.join(nlp_features)\n\treturn nlp_features_list \n\nes = Elasticsearch()\n\n\ntypes = ['剧情','喜剧','动作','爱情', '科幻', '音乐', '纪录片', '悬疑', '情色']\nfolder = ['juqing','xiju']\nfile_root_path = 'raw_data/'\n\nfoler_index=0\njuqing_type_list = []\nxiju_type_list = []\ndongzuo_type_list = []\naiqing_type_list = []\nkehuan_type_list = []\nyinyue_type_list = []\njilu_type_list = []\nxuanyi_type_list = []\nqingse_type_list = []\n\n\nfor type in types:\n\t#file = open(file_root_path + folder[foler_index], 'w')\n\tres = es.search(index=\"douban\", doc_type=type, size=2000, body={\"query\": {\"match_all\": {}}})\n\tprint(\"Got %d Hits:\" % res['hits']['total'])\n\tfor hit in res['hits']['hits']:\n\t\tid = hit[\"_id\"]\n\t\t##print(hit[\"_id\"])\n#\t\tprint(hit[\"_source\"][\"alt_title\"])\n#\t\tprint(hit[\"_source\"][\"summary\"])\n\t\t##feature = fenci(hit[\"_source\"][\"summary\"])\n\t\t#save_raw_data(file , hit[\"_source\"][\"alt_title\"])\n\t\t##save_raw_data(file , hit[\"_source\"][\"summary\"])\n\t\tif type == '剧情':\n\t\t\tjuqing_type_list.append(filer_str(hit[\"_source\"][\"summary\"]))\n\t\tif type == '喜剧':\n\t\t\txiju_type_list.append(filer_str(hit[\"_source\"][\"summary\"]))\n\t\tif type == '动作':\n\t\t\tdongzuo_type_list.append(filer_str(hit[\"_source\"][\"summary\"]))\n\t\tif type == '爱情':\n\t\t\taiqing_type_list.append(filer_str(hit[\"_source\"][\"summary\"]))\n\t\tif type == '科幻':\n\t\t\tkehuan_type_list.append(filer_str(hit[\"_source\"][\"summary\"]))\n\t\tif type == '音乐':\n\t\t\tyinyue_type_list.append(filer_str(hit[\"_source\"][\"summary\"]))\n\t\tif type == '纪录片':\n\t\t\tjilu_type_list.append(filer_str(hit[\"_source\"][\"summary\"]))\n\t\tif type == '悬疑':\n\t\t\txuanyi_type_list.append(filer_str(hit[\"_source\"][\"summary\"]))\n\t\tif type == '情色':\n\t\t\tqingse_type_list.append(filer_str(hit[\"_source\"][\"summary\"]))\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t#print(hit[\"_source\"][\"summary\"])\n\tfoler_index = foler_index+1\t\n\t#print raw_type_list\n#\tprint(\"Got %d Hits:\" % res['hits']['total'])\n\nneg = pd.DataFrame(juqing_type_list) \nprint(neg)\n\npos = pd.DataFrame(xiju_type_list) \nprint(pos)\n\ndongzuo = pd.DataFrame(dongzuo_type_list) \nprint(dongzuo)\n\naiqing = pd.DataFrame(aiqing_type_list) \nprint(aiqing)\n\nkehuan = pd.DataFrame(kehuan_type_list) \nprint(kehuan)\n\nyinyue = pd.DataFrame(yinyue_type_list) \nprint(yinyue)\n\njilu = pd.DataFrame(jilu_type_list) \nprint(jilu)\n\nxuanyi = pd.DataFrame(xuanyi_type_list) \nprint(xuanyi)\n\nqingse = pd.DataFrame(qingse_type_list) \nprint(qingse)\n\n#neg = pd.read_csv('raw_data/juqing', sep=\",\", header = None)\n#print(neg)\n#pos=pd.read_txt('raw_data/xiju',header=None,index=None) #读取训练语料完毕\npos['mark']=1\nneg['mark']=0 #给训练语料贴上标签\ndongzuo['mark']=2\naiqing['mark']=3\nkehuan['mark']=4\nyinyue['mark']=5\njilu['mark']=6\nxuanyi['mark']=7\nqingse['mark']=8\n\n\n\npn=pd.concat([pos,neg, dongzuo, aiqing, kehuan, yinyue, jilu, xuanyi, qingse ],ignore_index=True) #合并语料\nneglen=len(neg)\nposlen=len(pos) #计算语料数目\n\ncw = lambda x: list(jieba.cut(x)) #定义分词函数\npn['words'] = pn[0].apply(cw)\nprint (pn['words'])\n\n#comment = pd.read_excel('sum.xls') #读入评论内容\n#comment = pd.read_csv('a.csv', encoding='utf-8')\n#comment = comment[comment['rateContent'].notnull()] #仅读取非空评论\n#comment['words'] = comment['rateContent'].apply(cw) #评论分词 \n\nd2v_train = pd.concat([pn['words']], ignore_index = True) \n\n\nprint (d2v_train)\n\nw = [] #将所有词语整合在一起\nfor i in d2v_train:\n w.extend(i)\n\ndict = pd.DataFrame(pd.Series(w).value_counts()) #统计词的出现次数\ndel w,d2v_train\ndict['id']=list(range(1,len(dict)+1))\n\nget_sent = lambda x: list(dict['id'][x])\npn['sent'] = pn['words'].apply(get_sent) #速度太慢\n\nmaxlen = 1000\nmax_features = 1000\n\nprint(\"Pad sequences (samples x time)\")\npn['sent'] = list(sequence.pad_sequences(pn['sent'], maxlen=maxlen))\nprint(pn['sent']) \n\nx = np.array(list(pn['sent']))[::2] #训练集\ny = np.array(list(pn['mark']))[::2]\nxt = np.array(list(pn['sent']))[1::2] #测试集\nyt = np.array(list(pn['mark']))[1::2]\nxa = np.array(list(pn['sent'])) \nprint(xa)\nya = np.array(list(pn['mark']))\n\nprint('Build model...')\nmodel = Sequential()\n\nmodel.add(Embedding(input_dim=len(dict)+1, output_dim=256))\nmodel.add(LSTM(256, activation='tanh',inner_activation='hard_sigmoid')) # try using a GRU instead, for fun\nmodel.add(Dropout(0.5))\nmodel.add(Dense(9))\nmodel.add(Activation('softmax'))\nmodel.compile(loss='sparse_categorical_crossentropy', optimizer='adam', class_mode=\"categorical\", metrics=['accuracy'])\n\n#model.add(Dense(512, input_shape=(max_features,), activation='tanh'))\n#model.add(Dropout(0.5))\n#model.add(Dense(9, activation='softmax'))\n#model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', class_mode=\"categorical\", metrics=['accuracy'])\n\nprint('before tain...')\nmodel.fit(xa, ya, batch_size=16, nb_epoch=10) #训练时间为若干个小时\n\n#classes = model.predict_classes(xa)\n#acc = np_utils.accuracy(classes, ya)\n#print('Test accuracy:', acc)\n\n# evaluate the model\n\n# serialize model to JSON\nmodel_json = model.to_json()\nwith open(\"model_test_1000_lstm_50.json\", \"w\") as json_file:\n json_file.write(model_json)\n# serialize weights to HDF5\nmodel.save_weights(\"model_test_1000_lstm_50.h5\")\nprint(\"Saved model to disk\")\n\nscore, acc = model.evaluate(xa, ya, verbose=0)\n#classes = model.predict_classes(xa)\n#acc =np_utils.accuracy(classes, ya)\nprint(acc)\nprint(scores)\n\n \n","sub_path":"lstm_classifier_50000.py","file_name":"lstm_classifier_50000.py","file_ext":"py","file_size_in_byte":6743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"592700748","text":"from rest_framework import viewsets\nfrom rest_framework.filters import SearchFilter\nfrom rest_framework_gis.filters import InBBoxFilter, DistanceToPointFilter\nfrom ..models import ProviderLocation\nfrom ..serializers import ProviderLocationSerializer\n\n\nclass ProviderLocationView(viewsets.ModelViewSet):\n \"\"\"\n CRUD заполнения локации для организации.\n in_bbox - query параметр для фильтрации по координатам\n - пример: `in_bbox=-90,29,-89,35`\n - format: (min Lon, min Lat, max Lon, max Lat)\n search - query параметр для поиска по:\n - названию организации.\n point - формат данных для сохранения/обновления: \"POINT(lon lat)\", например: \"POINT(-123.0208 44.0464)\"\n \"\"\"\n\n queryset = ProviderLocation.objects.all().prefetch_related('provider')\n serializer_class = ProviderLocationSerializer\n\n filter_backends = (\n SearchFilter,\n InBBoxFilter,\n DistanceToPointFilter,\n )\n bbox_filter_field = 'point'\n bbox_filter_include_overlapping = True\n search_fields = (\n 'provider__organization_name',\n )\n","sub_path":"service/views/ProviderLocationView.py","file_name":"ProviderLocationView.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"628507994","text":"import newspaper\nimport datetime\nfrom utils.url_clean import get_domain\n\ndef get_news_info(n, nlp=False):\n \"\"\"\n Receives a piece of news, in a dictionary format.\n The dictionary must contain a url field, which\n will be the link to be scraped by the news scraper.\n\n It returns nothing. Instead it inserts more fields\n to the piece of news dictionary.\n \"\"\"\n url = n['url']\n article = newspaper.Article(url, language='es')\n article.download()\n article.parse()\n # Get info\n # date = f'{article.publish_date.year}-{article.publish_date.day}-{article.publish_date.month}'\n n['summary'] = \"\"\n n['keywords'] = \"\"\n if nlp:\n article.nlp()\n n['summary'] = article.summary\n n['keywords'] = article.keywords\n n['title'] = article.title.replace(\"\\\"\", \"'\")\n n['body'] = article.text.replace(\"\\\"\", \"'\").replace(\"\\n\", \"\")\n n['authors'] = article.authors\n n['publish_date'] = article.publish_date\n n['image'] = article.top_image\n n['url'] = url\n n['additional'] = article.additional_data\n n['sourceURL'] = article.source_url\n n['source'] = get_domain(article.source_url)\n n['publishedAt'], n['time'] = str(n['datetime']).split(' ')\n n['sourceType'] = 'digital'\n \n\nif __name__ == \"__main__\":\n n = {'url': \"https://www.radioagricultura.cl/politica/2019/01/09/presidente-pinera-respalda-al-ministro-chadwick-no-existe-fundamento-alguno-para-una-acusacion-constitucional-contra-el-ministro.html\", 'datetime': '2018-1-9 00:00:00',\n \"news_hash\": \"NTI0Nzg1ODlZMlo3MjQwMjc3NTUyODc0MDIyNzQ1MjI3NjAyNDI0NTI4MjUwMjU3ODUyNjBDNTU1NTU1NTU1Mw==\", \"sourcetype\": \"Televisión\"}\n get_news_info(n)\n print(n)","sub_path":"utils/news_scraper.py","file_name":"news_scraper.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"145931572","text":"\"\"\"\n下記、MITライセンスのコードを再利用しております。\nhttps://github.com/alifelab/alife_book_src\n=>MycroPythonはnumpyが利用できなかったので、書き換えています。\n\"\"\"\n\nimport random\n\nclass GameOfLife:\n def __init__(self, value_range_min=0, value_range_max=1):\n self.HEIGHT=15\n self.WIDTH=15\n\n self.next_state = [[random.randint(-128, 127) for i in range(self.HEIGHT)] for j in range(self.WIDTH)]\n\n # 初期データの設定\n self.state = [[random.randint(0, 1) for i in range(self.HEIGHT)] for j in range(self.WIDTH)]\n self.value_range = (value_range_min, value_range_max)\n\n\n def calc_state(self):\n for i in range(self.HEIGHT):\n for j in range(self.WIDTH):\n # 自分と近傍のセル��状態を取得\n # c: center (自分自身)\n # nw: north west, ne: north east, c: center ...\n nw = self.state[i-1][j-1]\n n = self.state[i-1][j]\n ne = self.state[i-1][(j+1)%self.WIDTH]\n w = self.state[i][j-1]\n c = self.state[i][j]\n e = self.state[i][(j+1)%self.WIDTH]\n sw = self.state[(i+1)%self.HEIGHT][j-1]\n s = self.state[(i+1)%self.HEIGHT][j]\n se = self.state[(i+1)%self.HEIGHT][(j+1)%self.WIDTH]\n neighbor_cell_sum = nw + n + ne + w + e + sw + s + se\n if c == 0 and neighbor_cell_sum == 3:\n self.next_state[i][j] = 1\n elif c == 1 and neighbor_cell_sum in (2,3):\n self.next_state[i][j] = 1\n else:\n self.next_state[i][j] = 0\n \n self.state, self.next_state = self.next_state, self.state\n\n matrix = [[ 1- self.state[i][j] for i in range(self.HEIGHT)] for j in range(self.WIDTH)]\n return matrix\n \n def create_matrix_img(self,matrix):\n img=[[None for i in range(self.HEIGHT)] for j in range(self.WIDTH)]\n\n for i in range(self.HEIGHT):\n for j in range(self.WIDTH):\n\n val=matrix[i][j]\n\n if matrix[i][j]self.value_range[1]:\n val=self.value_range[1]\n \n img[i][j]=abs(int( ((float(val)-self.value_range[0] )/ (self.value_range[1] - self.value_range[0]) * 255)))\n return img\n\n\n def reset(self):\n self.next_state = [[random.randint(-128, 127) for i in range(self.HEIGHT)] for j in range(self.WIDTH)]\n self.state = [[random.randint(0, 1) for i in range(self.HEIGHT)] for j in range(self.WIDTH)]\n\n","sub_path":"src/m5/lifegame/game_of_life.py","file_name":"game_of_life.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"269311280","text":"\nimport torch.nn as nn\n\n__all__ = ['simnet']\n\nclass SimNet(nn.Module):\n\n def __init__(self, num_classes=10):\n super(SimNet, self).__init__()\n self.features = nn.Sequential(\n nn.Conv2d(3, 32, kernel_size=3),\n nn.ReLU(inplace=True),\n nn.Conv2d(32, 32, kernel_size=3),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Dropout(p=0.25),\n nn.Conv2d(32, 64, kernel_size=3),\n nn.ReLU(inplace=True),\n nn.Conv2d(64, 64, kernel_size=3),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Dropout(p=0.25),\n nn.Flatten(),\n nn.Linear(5*5*64, 512),\n nn.ReLU(inplace=True),\n nn.Dropout(p=0.5),\n nn.Linear(512, 256)\n )\n self.fc = nn.Linear(256, num_classes)\n\n def forward(self, x):\n x = self.features(x)\n x = self.fc(x)\n return x\n\n\ndef simnet(**kwargs):\n r\"\"\"AlexNet model architecture from the\n `\"One weird trick...\" `_ paper.\n \"\"\"\n model = SimNet(**kwargs)\n return model","sub_path":"modelzoo/cifar/simnet.py","file_name":"simnet.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"263221300","text":"# -*- coding=utf-8 -*-\n\"\"\"\n-------------------------------\n Project: AI\n File Name: tcp_client.py\n Description: TCP客户端\n Author: Administrator\n Date: 2020/02/24\n Time: 08:23\n-------------------------------\n Modify Activity:\n 2020/02/24\n-------------------------------\n\"\"\"\n__author__ = 'Administrator'\n\nimport socket\nimport pprint\n\ntarget_host = '127.0.0.1' # 目标主机\ntarget_port = 9999 # 目标端口\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP客户端\n\nclient.connect((target_host, target_port)) # 连接目标主机\n# HTTP请求需要一个固定的格式\nclient.send(b'I am tcp')\n\nresponse = client.recv(4096) # 接受响应内容\n\npprint.pprint(response)\n\n","sub_path":"tcp_client.py","file_name":"tcp_client.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"82547012","text":"# https://www.interviewbit.com/problems/add-one-to-number/\n\nclass Solution:\n # @param A : list of integers\n # @return a list of integers\n def plusOne(self, A):\n result = []\n if not A:\n return result\n carry = 1\n index = 0\n while index < len(A) and A[index] == 0:\n index += 1\n for i in reversed(A[index:]):\n n = i + carry\n carry = n / 10\n result.append(n%10)\n if carry != 0:\n result.append(carry)\n return list(reversed(result))\n","sub_path":"interview-bit-add-one-to-number.py","file_name":"interview-bit-add-one-to-number.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"469198617","text":"# O(N) time\n# O(1) space\n#\n# since: a ^ 0 = a \n# a ^ a = 0\n# we get: a ^ b ^ a = (a ^ a) ^ b = 0 ^ b = b\n#\n# 两个字符串,唯一区别是一个比另一个多了一个字母,问多了哪个字母\n# follow up: 数量很大 map reduce( word count?) bottleneck在哪儿,如果只有一个reducer的话那个reducer就是bottleneck\n# follow up: 一样的放在一起, binary search lg(N)\n\ndef single_character(s1, s2):\n ans = 0\n for letter in s1+s2:\n ans ^= ord(letter)\n return chr(ans)\n\n\n################################ follow up ##################################\n# lg(N) time\n# Same character put together, find single character 'aabbcdd'\n#\n# Algo:\n# since same character index begin with (0, 1) so, before single should be (even, odd)\n# index after single character should be (odd, even)\n\ndef single_character(S):\n S = \"##{}##\".format(S)\n lo, hi = 0, len(S)\n while lo < hi:\n mid = (lo + hi) // 2\n if S[mid-1] != S[mid] and S[mid+1] != S[mid]: # single number\n return S[mid]\n if mid > 0 and S[mid-1] == S[mid]: # (mid-1, mid)\n if (mid-1) % 2 == 0:\n lo = mid + 1\n else:\n hi = mid\n elif mid+1 < len(S) and S[mid+1] == S[mid]:\n if mid % 2 == 0:\n lo = mid + 1\n else:\n hi = mid\n else:\n raise Expection('err format')\n return S[lo]\n\nS = '11223'\nassert single_character(S) == '3'\nS = '122'\nassert single_character(S) == '1'\n","sub_path":"Google/single_character.py","file_name":"single_character.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"508813327","text":"import sys\r\nimport os\r\nimport string\r\n\r\n\r\ndef palindrome(s):\r\n # your code goes here\r\n possible = set(string.ascii_lowercase)\r\n s = s.lower()\r\n s = ''.join([char for char in s if char in possible])\r\n return s == s[::-1]\r\n\r\ndef solution(s):\r\n return palindrome(s)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n if len(sys.argv) <= 1:\r\n sys.exit(os.error(\"Argment required\"))\r\n\r\n print(solution(sys.argv[1]))\r\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"42225905","text":"import json\nimport pickle\n\nfrom numpy import mean\n\nfrom agent.dqn_agent_split_action_nets import DQNAgent\nfrom gui.chat_application import ChatApplication\nfrom dialog_config import feasible_agent_actions\nfrom state_tracker import StateTracker\nfrom user.user_real import User\nfrom user.usersim_rulebased import RulebasedUsersim\n\n\nclass Dialogue:\n\n def __init__(self, load_agent_model_from_directory: str = None):\n # Load database of movies (if you get an error unpickling movie_db.pkl then run pickle_converter.py)\n database = pickle.load(open(\"resources/movie_db.pkl\", \"rb\"), encoding=\"latin1\")\n\n # Create state tracker\n self.state_tracker = StateTracker(database)\n\n # Create user simulator with list of user goals\n self.user_simulated = RulebasedUsersim(\n json.load(open(\"resources/movie_user_goals.json\", \"r\", encoding=\"utf-8\")))\n\n # Create GUI for direct text interactions\n self.gui = ChatApplication()\n\n # Create user instance for direct text interactions\n self.user_interactive = User(nlu_path=\"user/regex_nlu.json\", use_voice=False, gui=self.gui)\n\n # Create empty user (will be assigned on runtime)\n self.user = None\n\n # Create agent\n self.agent = DQNAgent(alpha=0.001, gamma=0.9, epsilon=0.5, epsilon_min=0.05,\n n_actions=len(feasible_agent_actions), n_ordinals=3,\n observation_dim=(StateTracker.state_size()),\n batch_size=256, memory_len=80000, prioritized_memory=True,\n replay_iter=16, replace_target_iter=200)\n if load_agent_model_from_directory:\n self.agent.load_agent_model(load_agent_model_from_directory)\n\n def run(self, n_episodes, step_size=100, warm_up=False, interactive=False, learning=True):\n \"\"\"\n Runs the loop that trains the agent.\n\n Trains the agent on the goal-oriented dialog task (except warm_up, which fills memory with rule-based behavior)\n Training of the agent's neural network occurs every episode that step_size is a multiple of.\n Replay memory is flushed every time a best success rate is recorded, starting with success_rate_threshold.\n Terminates when the episode reaches n_episodes.\n\n \"\"\"\n\n if interactive:\n self.user = self.user_interactive\n self.gui.window.update()\n else:\n self.user = self.user_simulated\n\n if not learning:\n self.agent.epsilon = 0.0\n\n batch_episode_rewards = []\n batch_successes = []\n batch_success_best = 0.0\n step_counter = 0\n\n for episode in range(n_episodes):\n\n # print(\"########################\\n------ EPISODE {} ------\\n########################\".format(episode))\n self.episode_reset(interactive)\n done = False\n success = False\n episode_reward = 0\n\n # Initialize episode with first user and agent action\n prev_observation = self.state_tracker.get_state()\n # 1) Agent takes action given state tracker's representation of dialogue (observation)\n prev_agent_action = self.agent.choose_action(prev_observation, warm_up=warm_up)\n while not done:\n step_counter += 1\n # 2) 3) 4) 5) 6a)\n observation, reward, done, success = self.env_step(prev_agent_action, interactive)\n if learning:\n replay = step_counter % self.agent.replay_iter == 0\n # 6b) Add experience\n self.agent.update(prev_observation, prev_agent_action, observation, reward, done,\n warm_up=warm_up, replay=replay)\n # 1) Agent takes action given state tracker's representation of dialogue (observation)\n agent_action = self.agent.choose_action(observation, warm_up=warm_up)\n\n episode_reward += reward\n prev_observation = observation\n prev_agent_action = agent_action\n\n if not warm_up and learning:\n self.agent.end_episode(n_episodes)\n\n # Evaluation\n # print(\"--- Episode: {} SUCCESS: {} REWARD: {} ---\".format(episode, success, episode_reward))\n batch_episode_rewards.append(episode_reward)\n batch_successes.append(success)\n if episode % step_size == 0:\n # Check success rate\n success_rate = mean(batch_successes)\n avg_reward = mean(batch_episode_rewards)\n\n print('Episode: {} SUCCESS RATE: {} Avg Reward: {}'.format(episode, success_rate,\n avg_reward))\n if success_rate > batch_success_best and learning and not warm_up:\n print('Episode: {} NEW BEST SUCCESS RATE: {} Avg Reward: {}'.format(episode, success_rate,\n avg_reward))\n self.agent.save_agent_model()\n batch_success_best = success_rate\n batch_successes = []\n batch_episode_rewards = []\n\n if learning and not warm_up:\n # Save final model\n self.agent.save_agent_model()\n\n def env_step(self, agent_action, interactive=False):\n # 2) Update state tracker with the agent's action\n self.state_tracker.update_state_agent(agent_action)\n if interactive:\n self.gui.insert_message(agent_action.to_utterance(), \"Shop Assistant\")\n # print(agent_action)\n # 3) User takes action given agent action\n user_action, reward, done, success = self.user.get_action(agent_action)\n # print(user_action)\n # 4) Infuse error into user action (currently inactive)\n # 5) Update state tracker with user action\n self.state_tracker.update_state_user(user_action)\n # 6a) Get next state\n observation = self.state_tracker.get_state(done)\n return observation, reward, done, True if success is 1 else False\n\n def episode_reset(self, interactive=False):\n # Reset the state tracker\n self.state_tracker.reset()\n # Reset the user\n self.user.reset()\n # Reset the agent\n self.agent.turn = 0\n # Reset the interactive GUI\n if interactive:\n self.gui.reset_text_widget()\n self.gui.insert_message(\"Guten Tag! Wie kann ich Ihnen heute helfen?\", \"Shop Assistant\")\n # User start action\n user_action, _, _, _ = self.user.get_action(None)\n # print(user_action)\n self.state_tracker.update_state_user(user_action)\n\n\nif __name__ == \"__main__\":\n dialogue = Dialogue()\n print(\"########################\\n--- STARTING WARM UP ---\\n########################\")\n dialogue.run(n_episodes=4000, warm_up=True)\n print(\"########################\\n--- STARTING TRAINING ---\\n#########################\")\n dialogue.run(n_episodes=10000, warm_up=False)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"207571284","text":"\"\"\"\nTests for Lesson 05 Assignment\nMongoDB\n\"\"\"\n\nimport pytest\nimport database as d\n\n# pylint: disable-msg=invalid-name\n# pylint: disable-msg=redefined-outer-name\n# pylint: disable-msg=missing-docstring\n# pylint: disable-msg=protected-access\n\n\n@pytest.fixture(scope=\"function\")\ndef mongo_database():\n \"\"\"\n Creates a MongoDB.\n :return:\n \"\"\"\n mongo = d.MongoDBConnection()\n\n with mongo:\n db = mongo.connection.media\n\n yield db\n\n d.clear_data(db)\n\n\ndef test_import_csv():\n rentals_list = d._import_csv(\"rentals.csv\")\n\n assert {'product_id': 'prd002', 'user_id': 'user008'} in rentals_list\n assert len(rentals_list) == 9\n\n\ndef test_import_data(mongo_database):\n result = d.import_data(mongo_database, \"\", \"products.csv\", \"customers.csv\", \"rentals.csv\")\n\n assert result == ((10, 10, 9), (0, 0, 0))\n\n\ndef test_show_available_products(mongo_database):\n d.import_data(mongo_database, \"\", \"products.csv\", \"customers.csv\", \"rentals.csv\")\n\n result = d.show_available_products(mongo_database)\n\n assert len(result) == 7\n assert \"prd001\" in result\n assert \"prd002\" not in result\n\n\ndef test_show_rentals(mongo_database):\n d.import_data(mongo_database, \"\", \"products.csv\", \"customers.csv\", \"rentals.csv\")\n\n result = d.show_rentals(mongo_database, \"prd005\")\n assert len(result) == 2\n\n assert list(result.keys()) == [\"user001\", \"user003\"]\n\n\ndef test_clear_data(mongo_database):\n d.import_data(mongo_database, \"\", \"products.csv\", \"customers.csv\", \"rentals.csv\")\n\n result = mongo_database.list_collection_names()\n assert result == [\"products\", \"rentals\", \"customers\"]\n\n d.clear_data(mongo_database)\n result2 = mongo_database.list_collection_names()\n assert result2 == []\n","sub_path":"students/DiannaTingg/lessons/lesson05/assignment/test_database.py","file_name":"test_database.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"205635874","text":"import math\nfrom typing import List, Tuple, Union\n\nfrom matplotlib import axes\nimport matplotlib.pyplot as plt\n\nfrom athena import Experiment, Experiments\n\n\ndef plot_experiments(\n experiments: Union[Experiments, List[Experiment]],\n save_path: str = None,\n figsize: Tuple[int, int] = (18, 13),\n):\n \"\"\"\n Plots the metrics of the experiments given. Experiments that have recorded the same metric will have overlapping plots.\n\n Args:\n experiments (Union[Experiments, List[Experiment]]): The list of ``Experiments`` to plot\n save_path (str, optional): The path to save the plot. Defaults to None.\n figsize (Tuple[int, int], optional): The size of the plot. Defaults to (18, 13).\n\n Raises:\n Exception: When there are no metrics to plot.\n \"\"\"\n if isinstance(experiments, Experiments):\n experiments = list(experiments)\n\n # getting the list of metrics to plot\n metric_names = list(\n {\n metric\n for exp in experiments\n for metric in exp.get_solver().get_history().get_metric_names()\n }\n )\n metric_names.sort()\n num_metrics = len(metric_names)\n\n # checking if number of metrics to plot is > 0\n if num_metrics == 0:\n raise Exception(\"No metrics to plot.\")\n\n # calculating the number of rows and column in the plot\n nrows = math.floor(math.sqrt(num_metrics))\n ncols = math.ceil(num_metrics / nrows)\n\n # creating the empty plot\n fig, ax = plt.subplots(nrows, ncols, figsize=figsize)\n\n # if there is only one metric to plot\n if nrows == 1 and ncols == 1:\n _plot_metric(metric_names[0], experiments, ax)\n\n # if there is only one row of metrics to plot\n elif nrows == 1:\n # for every plot,\n for i in range(len(ax)):\n _plot_metric(metric_names[i], experiments, ax[i])\n\n # if there is more than one row of metrics to plot\n else:\n for i in range(nrows):\n metric_idx = 0\n\n for j in range(ncols):\n\n # coverting i and j values into a single value that can be used\n # to index a 1 dimensional array\n metric_idx = i * ncols + j\n\n # if the converted index is greater than the number of metrics to plot,\n # that means there are no more metrics to plot, so break\n if metric_idx >= num_metrics:\n break\n\n # plot the metric for all the experiments\n _plot_metric(metric_names[metric_idx], experiments, ax[i, j])\n\n if metric_idx == num_metrics:\n break\n\n # saving the plot if path is provided\n if save_path is not None:\n fig.savefig(save_path, bbox_inches=\"tight\", pad_inches=0.25)\n\n\ndef _plot_metric(metric: str, experiments: List[Experiment], ax: axes.Axes):\n \"\"\"\n Plots a metric for the given list of experiments.\n\n Args:\n metric (str): The metric to plot.\n experiments (List[Experiment]): The list of experiments whose metrics have to be plotted.\n ax (axes.Axes): The ``~matplotlib.axes.Axes`` to plot on.\n \"\"\"\n\n # setting title of the plot\n ax.set_title(metric)\n\n # for every experiment\n for exp in experiments:\n # plot the metric of the experiment\n _plot_experiment(metric, exp, ax)\n\n # enable legend\n ax.legend()\n\n\ndef _plot_experiment(metric: str, experiment: Experiment, ax: axes.Axes):\n \"\"\"\n Plots a metric of a given experiment.\n\n Args:\n metric (str): The metric to plot.\n experiment (Experiment): The experiment to plot.\n ax (axes.Axes): The ``~matplotlib.axes.Axes`` to plot on.\n \"\"\"\n\n # if the experiment has not recorded that metric\n if not experiment.get_solver().get_history().has_metric(metric):\n return\n\n # plot the metric\n ax.plot(\n experiment.get_solver().get_history().get_metric(metric), label=experiment.name\n )\n","sub_path":"athena/visualizations/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"178382357","text":"class Room: #定义一个房间的类\n def __init__(self,owner,length,width,high):\n self.owner = owner\n self.__length = length #房间的长\n self.__width = width #房间的宽\n self.__high = high #房间的高\n # @property\n def area(self): #求房间的平方的功能\n return self.__length * self.__width #对外提供的接口,隐藏了内部的实现细节\n\nr = Room('刘贺',10,7,8)\nprint(r.area()) \n# print(r.area) # 添加 property装饰器\n","sub_path":"1102_封装.py","file_name":"1102_封装.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"419461928","text":"\"\"\"\n11- Leia uma matriz 3x3 elementos. Calcule a soma dos elementos que\nestão na diagonal secundária.\n\"\"\"\n\nmatriz, soma = [[], [], []], 0\n\nprint('Preencha a matriz')\nfor i in range(3):\n for j in range(3):\n matriz[i].append(int(input(f'M[{i},{j}] = ')))\n\n if i + j == 2:\n soma += matriz[i][j]\n\nfor i in range(3):\n for j in range(3):\n print(matriz[i][j], end=' ')\n print('')\n\nprint(f'Soma dos elementos na diagonal secundária: {soma}')\n","sub_path":"guppe/exercicios_secao_7/pt_2/ex_11.py","file_name":"ex_11.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"613975069","text":"from django.shortcuts import render, redirect\nfrom .models import EduResource\nfrom .forms import EducationForm\n\nfrom django.contrib.auth.decorators import login_required\n\n\n\n@login_required(login_url='/login/')\ndef eduResourceHome(request):\n template = 'eduresources.html'\n\n source = EduResource.objects.all()\n\n form = EducationForm()\n\n context = {'source': source, 'form': form}\n if request.method == 'POST':\n form = EducationForm(request.POST)\n if (form.is_valid()):\n # verify that it doesnt already exist\n data = form.cleaned_data\n exists = False\n for item in source:\n if (str(item.Title).lower() == str(data.get('Title')).lower() and\n str(item.Source_Type).lower() == str(data.get('Source_Type')).lower()):\n exists = True\n if (not exists):\n form.save()\n return redirect('/eduresources/')\n else:\n return redirect('/eduresources/')\n\n return render(request, template, context)\n","sub_path":"biowiki_new/eduresources/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"608308428","text":"from .__init__ import *\n\n\n# =============================================================\n# ActionGoodbye - action responsavel pela despedida do usuário\n# =============================================================\nclass ActionGoodbye(Action):\n def name(self) -> Text:\n return \"action_goodbye\"\n\n def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n log(tracker.latest_message)\n dismiss = choice(['Até logo! 👋', 'Até mais! 👋', 'Até breve! 👋'])\n texto = choice(['Tenha um ótimo dia! 🌞', 'Quando precisar, é só chamar! 😀'])\n dispatcher.utter_message(f'{texto} {dismiss}')\n last_event = tracker.get_last_event_for('user', skip=0)\n last_intent = last_event['parse_data']['intent']['name'] if last_event else None\n if last_intent == 'goodbye_intent':\n user_finish = None\n return [SlotSet('user_alm_qc', user_finish), SlotSet('count_finish', '0')]\n return []\n","sub_path":"actions/action_goodbye.py","file_name":"action_goodbye.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"451154600","text":"# Accpet number from user and check whether number is perfect or not.\r\n#input : 6 , 28\r\n# output : True\r\n#input : 4\r\n#output : False\r\n\r\ndef PerfectNum(no):\r\n iCnt = 1 \r\n iSum = 0\r\n while(iCnt <= no/2):\r\n if((no % iCnt) == 0):\r\n iSum = iSum + iCnt\r\n iCnt = iCnt + 1\r\n if(iSum == no):\r\n return True\r\n else:\r\n return False\r\n \r\n #for i in range(1,int(no/2)+1):\r\n #if no % i == 0 :\r\n #iSum = iSum + i\r\n #if(iSum == no):\r\n #return True\r\n #else:\r\n #return False\r\n \r\ndef main():\r\n print(\"Enter the number\")\r\n value1 = int(input())\r\n print(\"*****************************\") \r\n bret = PerfectNum(value1)\r\n if(bret == True):\r\n print(\"It is perfect number\")\r\n else:\r\n print(\"It is not perfect number\")\r\n print(\"*****************************\") \r\n\r\nif __name__==\"__main__\":\r\n main()","sub_path":"CheckPerfect.py","file_name":"CheckPerfect.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"123487416","text":"import time, os, collections, statistics, logging, numpy\n\nlog = logging.getLogger(__name__)\n\n_summary_types = dict(\n sum=sum,\n mean=statistics.mean,\n min=min,\n max=max,\n median=statistics.median,\n)\n\nclass _TimerGetter:\n def __init__(self, timer, summary):\n self.timer = timer\n self.summary = summary\n\n def __getattr__(self, name):\n if name in ('timer', 'checkpoints'):\n raise AttributeError\n if name in self.timer.checkpoints:\n return self.summary(self.timer.checkpoints[name])\n raise AttributeError(\"Timer has no attribute named: \" + name)\n\nclass Timer:\n def __init__(self, name='Timer', verbose=False):\n self.name = name\n self.verbose = verbose\n self.sum = _TimerGetter(self, numpy.sum)\n self.mean = _TimerGetter(self, numpy.mean)\n self.min = _TimerGetter(self, numpy.min)\n self.max = _TimerGetter(self, numpy.max)\n self.median = _TimerGetter(self, numpy.median)\n\n def start(self):\n return self.__enter__()\n\n def stop(self):\n return self.__exit__()\n\n def __enter__(self):\n if self.verbose: log.debug(f'{self.name} intialized')\n self.start = time.perf_counter()\n self.last = self.start\n self.checkpoints = collections.defaultdict(list)\n return self\n\n def checkpoint(self, name='none', verbose=False):\n t = time.perf_counter()\n self.checkpoints[name].append(t - self.last)\n self.last = t\n if self.verbose or verbose:\n log.debug(f'{self.name} checkpoint {name} iter {len(self.checkpoints[name])}' +\n f'time {self.checkpoints[name][-1]}')\n return self\n\n def __exit__(self, type=None, value=None, traceback=None):\n self.checkpoints['total'].append(time.perf_counter() - self.start)\n if self.verbose: log.debug(f'{self.name} finished')\n if self.verbose: self.report()\n return self\n\n def __getattr__(self, name):\n if name == \"checkpoints\":\n raise AttributeError\n if name in self.checkpoints:\n return self.checkpoints[name]\n raise AttributeError(\"Timer has no attribute named: \" + name)\n\n def alltimes(self, name):\n return self.checkpoints[name]\n\n def report_dict(self, order='longest', summary='sum'):\n if not callable(summary):\n if summary not in _summary_types:\n raise ValueError('unknown summary type: ' + str(summary))\n summary = _summary_types[summary]\n if order == 'longest':\n reordered = sorted(self.checkpoints.items(), key=lambda kv: -summary(kv[1]))\n return {k: summary(v) for k, v in reordered}\n elif order == 'callorder':\n return self.checkpoints\n else:\n raise ValueError('Timer, unknown order: ' + order)\n\n def report(self, order='longest', summary='sum', namelen=None, precision='10.5f',\n printme=True):\n if namelen is None:\n namelen = max(len(n) for n in self.checkpoints)\n lines = [f\"Times(order={order}, summary={summary}):\"]\n times = self.report_dict(order=order, summary=summary)\n for cpoint, t in times.items():\n lines.append(f' {cpoint:>{namelen}} {t:{precision}}')\n r = os.linesep.join(lines)\n if printme: log.info(r)\n return r\n\n @property\n def total(self):\n if 'total' in self.checkpoints:\n return sum(self.checkpoints['total'])\n return time.perf_counter() - self.start\n\n def __str__(self):\n return self.report(printme=False)\n\n def merge(self, others):\n if isinstance(others, Timer): others = [others]\n for other in others:\n for k, v in other.checkpoints.items():\n self.checkpoints[k].extend(v)\n","sub_path":"rpxdock/util/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"210268246","text":"import urllib.request\nimport urllib.parse\nimport os\n\nba_name = input(\"请输入吧名:\")\n\nstart_page = int(input(\"请输入起始页码:\"))\nend_page = int(input(\"请输入要爬取的结束页码:\"))\n\n# 创建文件夹\nif not os.path.exists(ba_name):\n os.mkdir(ba_name)\n\nfor page in range(start_page, end_page + 1):\n \n url = r'http://tieba.baidu.com/f?'\n data = {\n 'kw': ba_name,\n 'ie': 'utf-8',\n 'pn': str((page - 1) * 50)\n }\n\n headers = {\n 'Host': 'tieba.baidu.com',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n 'Connection': 'keep-alive',\n 'Cookie': 'BAIDUID=04AF0E6FCEB74A3E6CA2C32606EF8892:FG=1; BIDUPSID=D8CAC45F89186CC0232016FF853C7430; PSTM=1557136117; BDUSS=RISjJMQkdvREJSdWo0V2VvQlJ6MElVQmNHd3diWDFycE5zdXJ3NmNIT0E3MXhkSVFBQUFBJCQAAAAAAAAAAAEAAAC5XwWb17fRsDE2NTEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIBiNV2AYjVddH; TIEBAUID=5a13ed663e5f49dda2da110c; TIEBA_USERTYPE=7b00a4222b85b84a1b9270d6; bdshare_firstime=1567987337601; Hm_lvt_98b9d8c2fd6608d564bf2ac2ae642948=1567987338; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; STOKEN=aabf886c7b1af17a90a661b3e1c9c1c9497d6894fe159ee122f550637403c471; BDRCVFR[Hp1ap0hMjsC]=mk3SLVN4HKm; delPer=0; PSINO=1; H_PS_PSSID=1426_21082_29567_29221_22159; 2600820665_FRSVideoUploadTip=1',\n 'Upgrade-Insecure-Requests': '1',\n 'Cache-Control': 'max-age=0'\n\n }\n data = urllib.parse.urlencode(data)\n url += data\n request = urllib.request.Request(url=url, headers=headers)\n response = urllib.request.urlopen(request)\n\n \n # 创建文件\n filename = ba_name + \"_\" + str(page) +\".html\"\n filepath = os.path.join(ba_name, filename)\n print(\"第%d页开始下载\" % page)\n with open(filepath, \"wb\") as f:\n f.write(response.read())\n\n\n print(\"第%d页结束下载\" % page)\n","sub_path":"urllib库/3-ajax-teiba.py","file_name":"3-ajax-teiba.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"193276169","text":"import cv2\nimport numpy as np\nimport random\nimport os\nfrom PIL import Image\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport config as cfg\nimport time\n\n'''\n拿到增强所需要的参数\n'''\ndef get_aug_dict():\n '''\n rotation_range=0.2,\n width_shift_range=0.05,\n height_shift_range=0.05,\n shear_range=0.05,\n zoom_range=0.05,\n horizontal_flip=True\n '''\n r_rotation_range = random.random() / 5\n r_width_shift_range = random.random() / 20\n r_height_shift_range = random.random() / 20\n r_shear_range = random.random() / 20\n r_zoom_range = random.random() / 20\n r_horizontal_flip = random.choice([True, False])\n\n data_gen_args = dict(rotation_range=r_rotation_range,\n width_shift_range=r_width_shift_range,\n height_shift_range=r_height_shift_range,\n shear_range=r_shear_range,\n zoom_range=r_zoom_range,\n horizontal_flip=r_horizontal_flip)\n return data_gen_args\n\n'''\n将label【height,weight,3】\n变成【height,weight,2】\n'''\ndef process_label(label_img):\n h,w,channel = label_img.shape\n last_label = np.zeros(shape=[h,w],dtype=np.uint8)\n for i in range(h):\n for j in range(w):\n if max(label_img[i,j,:])>0:\n last_label[i,j]=1\n last_label = np.uint8(last_label)\n last_label = np.reshape(last_label,(h,w,1))\n # 只需要返回一个维度就好\n # last_label_reverse = 1-last_label\n # output = np.concatenate([last_label,last_label_reverse],axis = 2)\n return last_label\n\n'''\n读取原始数据\n将数据分为训练和测试两部分\n'''\ndef devide_all_data():\n all_data = []\n for fi in os.listdir('./my_train_data/'):\n temp_path = './my_train_data/' + fi + '/'\n\n org_img = cv2.imread(temp_path + 'img.png')\n lab_img = cv2.imread(temp_path + 'label.png')\n lab_img = process_label(lab_img)\n\n all_data.append((org_img, lab_img))\n\n valid_choice = random.sample(list(range(95)), 15)\n valid_data = [data for i, data in enumerate(all_data) if i in valid_choice]\n train_data = [data for i, data in enumerate(all_data) if i not in valid_choice]\n\n return train_data, valid_data\n\n\n'''\n读取keras的数据\n'''\ndef devide_all_data2():\n train_img = './ipython_file/train/image/'\n train_lab = './ipython_file/train/label/'\n all_res = []\n for img_path, lab_path in zip(os.listdir(train_img), os.listdir(train_lab)):\n org_img = cv2.imread(train_img + img_path)\n\n org_lab = cv2.imread(train_lab + lab_path)\n org_lab = process_label(org_lab)\n\n all_res.append((org_img, org_lab))\n\n valid_img = './ipython_file/valid/image/'\n valid_lab = './ipython_file/valid/label/'\n all_res_val = []\n for img_path, lab_path in zip(os.listdir(valid_img), os.listdir(valid_lab)):\n org_img = cv2.imread(valid_img + img_path)\n\n org_lab = cv2.imread(valid_lab + lab_path)\n org_lab = process_label(org_lab)\n\n all_res_val.append((org_img, org_lab))\n\n return all_res, all_res_val\n\n'''\n将数据保存成tfrecords的格式。\n'''\ndef to_tfrecords(raw_data, record_name):\n writer = tf.python_io.TFRecordWriter(record_name)\n for temp_org_img, temp_lab_img in raw_data:\n\n temp_org_img = cv2.resize(temp_org_img,(cfg.IMG_SIZE,cfg.IMG_SIZE))\n temp_org_img = Image.fromarray(temp_org_img)\n # temp_org_img = temp_org_img.resize((cfg.IMG_SIZE,cfg.IMG_SIZE))\n temp_org_img_raw = temp_org_img.tobytes()\n\n temp_lab_img = cv2.resize(temp_lab_img,(cfg.IMG_SIZE,cfg.IMG_SIZE))\n temp_lab_img = Image.fromarray(temp_lab_img)\n # temp_lab_img = temp_lab_img.resize((cfg.IMG_SIZE,cfg.IMG_SIZE))\n temp_lab_img_raw = temp_lab_img.tobytes()\n\n feature_dict = {\n 'label': tf.train.Feature(bytes_list=\n tf.train.BytesList(value=[temp_lab_img_raw])),\n 'img_raw': tf.train.Feature(bytes_list=\n tf.train.BytesList(value=[temp_org_img_raw]))\n }\n example = tf.train.Example(features=tf.train.Features(feature=feature_dict))\n\n writer.write(example.SerializeToString())\n\n writer.close()\n\n'''\n直接读取tfrecords文件\n'''\ndef read_and_parse(filename):\n filename_queue = tf.train.string_input_producer([filename])\n\n reader = tf.TFRecordReader()\n _,serialized_example = reader.read(filename_queue)\n\n features_dict = {\n 'label': tf.FixedLenFeature([], tf.string),\n 'img_raw': tf.FixedLenFeature([], tf.string)\n }\n\n features_res = tf.parse_single_example(serialized_example,features=features_dict)\n p_tf_org_img = tf.decode_raw(features_res['img_raw'], tf.uint8)\n p_tf_org_img = tf.reshape(p_tf_org_img, [cfg.IMG_SIZE, cfg.IMG_SIZE, 3])\n\n p_tf_lab_img = tf.decode_raw(features_res['label'], tf.uint8)\n p_tf_lab_img = tf.reshape(p_tf_lab_img, [cfg.IMG_SIZE, cfg.IMG_SIZE, 2])\n\n return p_tf_org_img, p_tf_lab_img\n\n\n'''\n希望通过tf.data的API来读取文件的时候,\n传入参数是record\n'''\ndef parser(record):\n p_feature_dict = {\n 'label': tf.FixedLenFeature([], tf.string),\n 'img_raw': tf.FixedLenFeature([], tf.string)\n }\n p_features_res = tf.parse_single_example(record,\n features=p_feature_dict)\n\n p_tf_org_img = tf.decode_raw(p_features_res['img_raw'], tf.uint8)\n p_tf_org_img = tf.reshape(p_tf_org_img, [cfg.IMG_SIZE, cfg.IMG_SIZE, 3])\n\n p_tf_lab_img = tf.decode_raw(p_features_res['label'], tf.uint8)\n p_tf_lab_img = tf.reshape(p_tf_lab_img, [cfg.IMG_SIZE, cfg.IMG_SIZE, 1])\n\n return p_tf_org_img, p_tf_lab_img\n\n'''\n数据增强综合方法\n'''\ndef img_aug(imgs,labels):\n aug_dict = get_aug_dict()\n # print(aug_dict)\n my_aug = My_Aug(**aug_dict)\n\n aug_imgs = my_aug.process_batch(imgs)\n aug_labs = my_aug.process_batch(labels)\n return aug_imgs,aug_labs\n\n'''\n展示图片\n'''\ndef show_img(img):\n plt.imshow(img)\n plt.show()\n\ndef predict_to_img(img):\n '''\n :param img: 256,256,2 after softmax \n :return: \n '''\n # last_layer = np.zeros(shape=(256,256,1))\n # print(np.sum(np.float32(img>0.5)))\n layer_1 = np.float32(img>0.5)*255\n\n # layer_1 = np.reshape(layer_1,newshape=(256,256,1))\n # layer_2 = np.uint8(img[:,:,1]*255)\n # layer_2 = np.reshape(layer_2,newshape=(256,256,1))\n # print('last_layer:',last_layer.shape)\n # print('layer_1:',layer_1.shape)\n # print('layer_2:',layer_2.shape)\n return layer_1\n\n'''\n数据增强类\n'''\nclass My_Aug():\n def __init__(self,\n rotation_range,\n height_shift_range,\n width_shift_range,\n shear_range,\n zoom_range,\n horizontal_flip):\n self.roration_range = rotation_range\n self.height_shift_range = height_shift_range\n self.width_shift_range = width_shift_range\n self.shear_range = shear_range\n self.zoom_range = zoom_range\n self.horizontal_flip = horizontal_flip\n\n def _roration_img(self, img):\n '''\n 旋转图像\n '''\n # 默认图像是灰度图像\n h, w,channel = img.shape\n M = cv2.getRotationMatrix2D((h / 2, w / 2), self.roration_range, 1)\n img = cv2.warpAffine(img, M, (h, w))\n img = np.reshape(img,(h,w,channel))\n return img\n\n def _shift_img(self, img):\n '''\n 平移变换\n '''\n h, w,channel = img.shape\n M = np.float32([[1, 0, self.width_shift_range], [0, 1, self.height_shift_range]])\n img = cv2.warpAffine(img, M, (h, w))\n img = np.reshape(img,(h,w,channel))\n return img\n\n def _shear_img(self, img):\n '''\n x方向的剪切变换\n '''\n h, w,channel = img.shape\n M = np.float32([[1, np.tan(self.shear_range), 0], [0, 1, 0]])\n img = cv2.warpAffine(img, M, (h, w))\n img = np.reshape(img,(h,w,channel))\n return img\n\n def _zoom_img(self, img):\n '''\n 缩放\n '''\n h, w,channel = img.shape\n zoom_value = 1 + self.zoom_range\n M = np.float32([[zoom_value, 0, 0], [0, zoom_value, 0]])\n img = cv2.warpAffine(img, M, (h, w))\n img = np.reshape(img,(h,w,channel))\n return img\n\n def _flip_img(self, img):\n h,w,channel = img.shape\n img =cv2.flip(img, 1)\n img = np.reshape(img,(h,w,channel))\n return img\n\n def process_img(self, img):\n '''\n 按顺序处理图片:\n 1、旋转\n 2、平移\n 3、剪切\n 4、缩放\n 5、水平翻转\n '''\n img = self._roration_img(img)\n img = self._shift_img(img)\n img = self._shear_img(img)\n img = self._zoom_img(img)\n # if self.horizontal_flip:\n # img = self._flip_img(img)\n return img\n\n def process_batch(self, imgs):\n\n # processed_imgs = np.asarray([self.process_img(img) for img in imgs])\n res=[]\n for img in imgs:\n temp_res = self.process_img(img)\n res.append(temp_res)\n\n processed_imgs = np.asarray(res)\n\n return processed_imgs\n\n def img_show(self, img):\n plt.imshow(img)\n plt.show()\n\n\nif __name__ == '__main__':\n '''\n 调用两个方法,生成对应的tf_records文件\n '''\n train_raw_data, valid_raw_data = devide_all_data()\n to_tfrecords(train_raw_data, 'train_palm.tfrecords')\n to_tfrecords(valid_raw_data, 'valid_palm.tfrecords')\n\n # tf_records文件的placeholder\n file_names = tf.placeholder(dtype=tf.string, shape=[None])\n\n dataset = tf.data.TFRecordDataset(file_names)\n\n # 这里是调用映射函数的地方…但不知道能不能用自己的方法啊…\n # 是不是需要将自己的方法封装成tensorflow的方法?\n dataset = dataset.map(parser)\n dataset = dataset.repeat(cfg.REPEAT_TIME)\n dataset = dataset.batch(20)\n\n # 拿到迭代器\n iterator_init = dataset.make_initializable_iterator()\n # 拿到数据\n images, labels = iterator_init.get_next()\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n\n # 显式初始化\n train_filenames=['./train_palm.tfrecords']\n sess.run(iterator_init.initializer,feed_dict={file_names:train_filenames})\n start_time = time.time()\n for i in range(10):\n train_img,train_label = sess.run([images,labels])\n train_img, train_label = img_aug(train_img, train_label)\n print(train_label.shape)\n break\n\n\n\n end_time = time.time()\n t_i_list = []\n train_img,train_label = img_aug(train_img,train_label)\n end_time1 = time.time()\n print('sess:',end_time-start_time)\n print('aug:',end_time1-end_time)\n\n","sub_path":"Day10_1_My_Unet/data_prepare.py","file_name":"data_prepare.py","file_ext":"py","file_size_in_byte":10972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"371702305","text":"# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\nimport pytest\nfrom pytest import fixture\nimport pkg_resources\nimport os\nimport yaml\n\n\n@fixture\ndef sut():\n from servicecatalog_factory import cli\n return cli\n\n\ndef test_version(sut):\n # setup\n expected_result = pkg_resources.require(\"aws-service-catalog-factory\")[0].version\n\n # execute\n # verify\n assert sut.VERSION == expected_result\n\n\ndef test_bootstrap_stack_name(sut):\n # setup\n expected_result = 'servicecatalog-factory'\n\n # execute\n # verify\n assert sut.BOOTSTRAP_STACK_NAME == expected_result\n\n\ndef test_service_catalog_factory_repo_name(sut):\n # setup\n expected_result = 'ServiceCatalogFactory'\n\n # execute\n # verify\n assert sut.SERVICE_CATALOG_FACTORY_REPO_NAME == expected_result\n\n\ndef test_non_recoverable_states(sut):\n # setup\n expected_result = [\n \"ROLLBACK_COMPLETE\",\n 'CREATE_IN_PROGRESS',\n 'ROLLBACK_IN_PROGRESS',\n 'DELETE_IN_PROGRESS',\n 'UPDATE_IN_PROGRESS',\n 'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS',\n 'UPDATE_ROLLBACK_IN_PROGRESS',\n 'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',\n 'REVIEW_IN_PROGRESS',\n ]\n\n # execute\n # verify\n assert sut.NON_RECOVERABLE_STATES == expected_result\n\n\ndef test_resolve_from_site_packages(mocker, sut):\n # setup\n what = 'asset.py'\n site_path = os.path.sep.join(['some', 'path'])\n abspath = os.path.sep.join([site_path, 'cli.py'])\n expected_result = os.path.sep.join([site_path, what])\n mocker.patch.object(os.path, 'abspath', return_value=abspath)\n\n # execute\n actual_result = sut.resolve_from_site_packages(what)\n\n # verify\n assert expected_result == actual_result\n\n\ndef test_read_from_site_packages(mocker, sut):\n # setup\n what = 'asset.py'\n expected_result = 'foobar'\n mocked_open = mocker.patch('builtins.open')\n mocked_open().read.return_value = expected_result\n mocker.patch.object(sut, 'resolve_from_site_packages', return_value='ignored')\n\n # execute\n actual_result = sut.read_from_site_packages(what)\n\n # verify\n assert expected_result == actual_result\n\n\ndef test_get_regions(mocker, sut):\n # setup\n expected_result = [\n 'us-east-1',\n 'us-east-2',\n ]\n mocked_betterboto_client = mocker.patch.object(sut.betterboto_client, 'ClientContextManager')\n mocked_response = {\n 'Parameter': {\n \"Value\": yaml.safe_dump({'regions': expected_result})\n }\n }\n mocked_betterboto_client().__enter__().get_parameter.return_value = mocked_response\n\n # execute\n actual_result = sut.get_regions()\n\n # verify\n assert actual_result == expected_result\n\n\ndef test_find_portfolio(mocker, sut):\n # setup\n portfolio_searching_for = 'foo'\n\n expected_response = {'DisplayName': portfolio_searching_for}\n mock_service_catalog = mocker.Mock()\n mock_service_catalog.list_portfolios_single_page.return_value = {\n 'PortfolioDetails': [\n {\n 'DisplayName': \"Not{}\".format(portfolio_searching_for)\n },\n expected_response\n ]\n }\n\n # exercise\n actual_response = sut.find_portfolio(mock_service_catalog, portfolio_searching_for)\n\n # verify\n assert expected_response == actual_response\n\n\ndef test_find_portfolio_non_matching(mocker, sut):\n # setup\n portfolio_searching_for = 'foo'\n\n expected_response = {}\n mock_service_catalog = mocker.Mock()\n mock_service_catalog.list_portfolios_single_page.return_value = {\n 'PortfolioDetails': [\n {\n 'DisplayName': \"Not{}\".format(portfolio_searching_for)\n },\n {\n 'DisplayName': \"StillNot{}\".format(portfolio_searching_for)\n },\n ]\n }\n\n # exercise\n actual_response = sut.find_portfolio(mock_service_catalog, portfolio_searching_for)\n\n # verify\n assert expected_response == actual_response\n\n\n@pytest.mark.parametrize(\"portfolio\", [({}), ({\"Description\": 'Niiiice'})])\ndef test_create_portfolio(portfolio, mocker, sut):\n # setup\n portfolio_id = 'foo'\n portfolio_searching_for = 'my-portfolio'\n portfolios_groups_name = 'my-group'\n\n service_catalog = mocker.Mock()\n service_catalog.create_portfolio().get().get.return_value = portfolio_id\n expected_result = portfolio_id\n\n # exercise\n actual_result = sut.create_portfolio(\n service_catalog, portfolio_searching_for, portfolios_groups_name, portfolio\n )\n\n # verify\n assert expected_result == actual_result\n service_catalog.create_portfolio.assert_called_with(\n DisplayName=portfolio_searching_for, ProviderName=portfolios_groups_name, **portfolio\n )\n\n\ndef test_product_exists(mocker, sut):\n # setup\n service_catalog = mocker.Mock()\n product = {\n 'Name': 'foo'\n }\n expected_result = product\n\n service_catalog.search_products_as_admin_single_page.return_value = {\n 'ProductViewDetails': [\n {\n 'ProductViewSummary': {\n 'Name': 'NotFoo'\n }\n },\n {\n 'ProductViewSummary': product\n }\n ]\n }\n\n # exercise\n actual_result = sut.product_exists(service_catalog, product)\n\n # verify\n assert actual_result == expected_result\n\n\ndef test_product_exists_when_it_doesnt(mocker, sut):\n # setup\n service_catalog = mocker.Mock()\n product = {\n 'Name': 'foo'\n }\n expected_result = None\n\n service_catalog.search_products_as_admin_single_page.return_value = {\n 'ProductViewDetails': [\n {\n 'ProductViewSummary': {\n 'Name': 'NotFoo'\n }\n }\n ]\n }\n\n # exercise\n actual_result = sut.product_exists(service_catalog, product)\n\n # verify\n assert actual_result == expected_result\n \n \n@pytest.mark.parametrize(\"input_one, input_two, expected_results\", \n [\n ({ \"hello\": \"world\" }, { \"foo\": \"bar\" }, {\"hello\": \"world\",\"foo\": \"bar\"}),\n ({}, { \"foo\": \"bar\" }, { \"foo\": \"bar\" }),\n ({ \"hello\": \"world\" }, {}, { \"hello\": \"world\" }),\n ({}, {}, {}), \n ]) \ndef test_merge_case(input_one, input_two, expected_results, sut):\n # setup\n # exercise\n actual_results = sut.merge(input_one, input_two)\n\n # verify\n assert expected_results == actual_results\n\n\ndef test_get_bucket_name(mocker, sut):\n # setup\n expected_result = 'test-bucket'\n mocked_betterboto_client = mocker.patch.object(sut.betterboto_client, 'ClientContextManager')\n mocked_response = {\n 'Stacks': [{\n \"Outputs\": [{\"OutputKey\": \"CatalogBucketName\", \"OutputValue\": expected_result}]\n }]\n }\n mocked_betterboto_client().__enter__().describe_stacks.return_value = mocked_response\n\n # execute\n actual_result = sut.get_bucket_name()\n\n # verify\n assert actual_result == expected_result\n mocked_betterboto_client().__enter__().describe_stacks.assert_called_with(StackName=sut.BOOTSTRAP_STACK_NAME)\n \n \ndef test_get_bucket_name_stack_length_more(mocker, sut):\n # setup\n expected_result = 'There should only be one stack with the name'\n mocked_betterboto_client = mocker.patch.object(sut.betterboto_client, 'ClientContextManager')\n mocked_response = {\n 'Stacks': [{\n \"Outputs\": [{\"OutputKey\": \"CatalogBucketName\", \"OutputValue\": expected_result}]\n },\n {\n \"Outputs\": [{\"OutputKey\": \"CatalogBucketName\", \"OutputValue\": 'hello'}]\n }]\n }\n mocked_betterboto_client().__enter__().describe_stacks.return_value = mocked_response\n\n # execute\n with pytest.raises(Exception) as excinfo: \n sut.get_bucket_name()\n\n # verify\n assert str(excinfo.value) == expected_result\n mocked_betterboto_client().__enter__().describe_stacks.assert_called_with(StackName=sut.BOOTSTRAP_STACK_NAME)\n \n\ndef test_get_bucket_name_if_not_exists(mocker, sut):\n # setup\n expected_result = 'Could not find bucket'\n mocked_betterboto_client = mocker.patch.object(sut.betterboto_client, 'ClientContextManager')\n mocked_response = {\n 'Stacks': [{\n \"Outputs\": [{\"OutputKey\": \"BucketName\", \"OutputValue\": expected_result}]\n }]\n }\n mocked_betterboto_client().__enter__().describe_stacks.return_value = mocked_response\n\n # execute\n with pytest.raises(Exception) as excinfo: \n sut.get_bucket_name()\n\n # verify\n assert str(excinfo.value) == expected_result \n mocked_betterboto_client().__enter__().describe_stacks.assert_called_with(StackName=sut.BOOTSTRAP_STACK_NAME)\n \n \ndef test_get_stacks(mocker, sut):\n # setup\n args = {\n \"StackStatusFilter\": [\n 'CREATE_IN_PROGRESS',\n 'CREATE_FAILED',\n 'CREATE_COMPLETE',\n 'ROLLBACK_IN_PROGRESS',\n 'ROLLBACK_FAILED',\n 'ROLLBACK_COMPLETE',\n 'DELETE_IN_PROGRESS',\n 'DELETE_FAILED',\n 'UPDATE_IN_PROGRESS',\n 'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS',\n 'UPDATE_COMPLETE',\n 'UPDATE_ROLLBACK_IN_PROGRESS',\n 'UPDATE_ROLLBACK_FAILED',\n 'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',\n 'UPDATE_ROLLBACK_COMPLETE',\n 'REVIEW_IN_PROGRESS',\n ]\n }\n expected_result = {'foo': 'CREATE_IN_PROGRESS'}\n mocked_betterboto_client = mocker.patch.object(sut.betterboto_client, 'ClientContextManager')\n mocked_betterboto_client().__enter__().list_stacks.return_value = {\n 'StackSummaries': [\n {\n 'StackName': 'foo',\n 'StackStatus': 'CREATE_IN_PROGRESS'\n }\n ]\n }\n\n # execute\n actual_result = sut.get_stacks()\n\n # verify\n assert actual_result == expected_result\n mocked_betterboto_client().__enter__().list_stacks.assert_called_with(**args)\n \n\ndef test_get_stacks_if_empty(mocker, sut):\n # setup\n args = {\n \"StackStatusFilter\": [\n 'CREATE_IN_PROGRESS',\n 'CREATE_FAILED',\n 'CREATE_COMPLETE',\n 'ROLLBACK_IN_PROGRESS',\n 'ROLLBACK_FAILED',\n 'ROLLBACK_COMPLETE',\n 'DELETE_IN_PROGRESS',\n 'DELETE_FAILED',\n 'UPDATE_IN_PROGRESS',\n 'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS',\n 'UPDATE_COMPLETE',\n 'UPDATE_ROLLBACK_IN_PROGRESS',\n 'UPDATE_ROLLBACK_FAILED',\n 'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',\n 'UPDATE_ROLLBACK_COMPLETE',\n 'REVIEW_IN_PROGRESS',\n ]\n }\n expected_result = {}\n mocked_betterboto_client = mocker.patch.object(sut.betterboto_client, 'ClientContextManager')\n mocked_betterboto_client().__enter__().list_stacks.return_value = {\n 'StackSummaries': []\n }\n\n # execute\n actual_result = sut.get_stacks()\n\n # verify\n assert actual_result == expected_result\n mocked_betterboto_client().__enter__().list_stacks.assert_called_with(**args)\n","sub_path":"servicecatalog_factory/cli_test.py","file_name":"cli_test.py","file_ext":"py","file_size_in_byte":11344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"576122993","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAll spiders should yield data shaped according to the Open Civic Data\nspecification (http://docs.opencivicdata.org/en/latest/data/event.html).\n\"\"\"\nfrom datetime import datetime\n\nimport scrapy\nfrom dateutil.parser import parse\n\nfrom city_scrapers.constants import BOARD\nfrom city_scrapers.spider import Spider\n\n\nclass CookElectoralSpider(Spider):\n name = 'cook_electoral'\n agency_name = 'Cook County Electoral Board (Suburban Cook)'\n allowed_domains = ['aba.cookcountyclerk.com']\n start_urls = ['https://aba.cookcountyclerk.com/boardmeetingsearch.aspx']\n download_delay = 1.5\n\n custom_settings = {\n 'COOKIES_ENABLED': True,\n 'USER_AGENT':\n 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1', # noqa\n 'USER_AGENT_CACHE_KEY_LENGTH': '256'\n }\n\n def parse(self, response):\n \"\"\"\n `parse` should always `yield` a dict that follows the Event Schema\n .\n\n Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping\n needs.\n \"\"\"\n for day in response.css('select#ddlMeetingDate > option ::attr(value)').extract():\n yield scrapy.FormRequest(\n url='https://aba.cookcountyclerk.com/boardmeetingsearch.aspx',\n formdata={\n 'ddlMeetingDate': day,\n 'ddlMeetingYear': str(datetime.now().year),\n '__VIEWSTATE': response.css('input#__VIEWSTATE::attr(value)').extract_first(),\n '__VIEWSTATEGENERATOR':\n response.css('input#__VIEWSTATEGENERATOR::attr(value)').extract_first(),\n '__EVENTVALIDATION':\n response.css('input#__EVENTVALIDATION::attr(value)').extract_first(),\n '__EVENTTARGET': '',\n '__EVENTARGUMENT': '',\n '__LASTFOCUS': '',\n '__ASYNCPOST': 'true',\n 'ScriptManager1': 'UpdatePanel1|btnGo',\n 'btnGo.x': '29',\n 'btnGo.y': '9'\n },\n callback=self.parse_results,\n errback=self.request_err\n )\n\n def request_err(self, failure): # If Request throws an error\n self.logger.error(repr(failure))\n\n def parse_results(self, item):\n data = {\n '_type': 'event',\n 'name': 'Electoral Board (Suburban Cook)',\n 'description': self._parse_description(item),\n 'classification': BOARD,\n 'start': self._parse_start(item),\n 'end': self._parse_end(item),\n 'timezone': self._parse_timezone(item),\n 'status': self._parse_status(item),\n 'all_day': self._parse_all_day(item),\n 'location': self._parse_location(item),\n 'documents': self._parse_documents(item),\n 'sources': self._parse_sources(item),\n }\n\n data['id'] = self._generate_id(data)\n\n yield data\n\n # self._parse_next(response) yields more responses to parse if necessary.\n # uncomment to find a \"next\" url\n # yield self._parse_next(response)\n\n def _parse_next(self, response):\n \"\"\"\n Get next page. You must add logic to `next_url` and\n return a scrapy request.\n \"\"\"\n next_url = None # What is next URL?\n return scrapy.Request(next_url, callback=self.parse)\n\n def _parse_id(self, item):\n \"\"\"\n Calulate ID. ID must be unique and in the following format:\n ///\n\n Example:\n chi_buildings/201710161230/2176/daley_plaza_italian_exhibit\n \"\"\"\n return ''\n\n def _parse_description(self, item):\n \"\"\"\n Parse or generate event description.\n \"\"\"\n return ''\n\n def _parse_start(self, item):\n \"\"\"\n Parse start date and time.\n \"\"\"\n\n datetime = parse(\n item.css('span#lblMeetingTime ::text').extract_first() +\n item.css('span#lblDuration ::text').extract_first()\n )\n\n return {'date': datetime.date(), 'time': datetime.time()}\n\n def _parse_end(self, item):\n \"\"\"\n Parse end date and time.\n \"\"\"\n return {}\n\n def _parse_timezone(self, item):\n \"\"\"\n Parse or generate timzone in tzinfo format.\n \"\"\"\n return 'America/Chicago'\n\n def _parse_all_day(self, item):\n \"\"\"\n Parse or generate all-day status. Defaults to False.\n \"\"\"\n return False\n\n def _parse_location(self, item):\n \"\"\"\n Parse or generate location. Latitude and longitude can be\n left blank and will be geocoded later.\n \"\"\"\n return {\n 'url': '',\n 'name': item.css('span#lblLocation ::text').extract_first(),\n 'address':\n item.css('span#lblAddress ::text').extract_first() + ', ' +\n item.css('span#lblCity ::text').extract_first()\n }\n\n def _parse_status(self, item):\n \"\"\"\n Parse or generate status of meeting. Can be one of:\n * cancelled\n * tentative\n * confirmed\n * passed\n By default, return \"tentative\"\n \"\"\"\n return 'tentative'\n\n def _parse_documents(self, item):\n\n documents = []\n\n for link in item.css('#currentDocDisplay li a'):\n documents.append({\n 'url': link.css('::attr(href)').extract_first(),\n 'note': link.css('::text').extract_first()\n })\n\n return documents\n\n def _parse_sources(self, item):\n \"\"\"\n Parse or generate sources.\n \"\"\"\n return [{\n 'url': 'https://www.cookcountyclerk.com/service/board-meetings',\n 'note': 'Must submit form to see any dates',\n }]\n","sub_path":"city_scrapers/spiders/cook_electoral.py","file_name":"cook_electoral.py","file_ext":"py","file_size_in_byte":6031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"606858001","text":"\n\nfrom xai.brain.wordbase.nouns._thrust import _THRUST\n\n#calss header\nclass _THRUSTS(_THRUST, ):\n\tdef __init__(self,): \n\t\t_THRUST.__init__(self)\n\t\tself.name = \"THRUSTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"thrust\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_thrusts.py","file_name":"_thrusts.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"289705477","text":"#!/usr/bin/env python \r\n\"\"\"Epics Scaler\"\"\"\r\nimport epics\r\n\r\nclass Scaler(epics.Device):\r\n \"\"\" \r\n Simple implementation of SynApps Scaler Record. \r\n \"\"\"\r\n attrs = ('CNT', 'CONT', 'TP', 'T', 'VAL')\r\n attr_kws = {'calc_enable': '%s_calcEnable.VAL'}\r\n chan_attrs = ('NM%i', 'S%i')\r\n calc_attrs = {'calc%i': '%s_calc%i.VAL', 'expr%i': '%s_calc%i.CALC'}\r\n _nonpvs = ('_prefix', '_pvs', '_delim', '_nchan', '_chans')\r\n \r\n def __init__(self, prefix, nchan=8):\r\n self._nchan = nchan\r\n self._chans = range(1, nchan+1)\r\n \r\n attrs = list(self.attrs)\r\n for i in self._chans:\r\n for att in self.chan_attrs:\r\n attrs.append(att % i)\r\n \r\n epics.Device.__init__(self, prefix, delim='.', attrs=attrs)\r\n\r\n for key, val in self.attr_kws.items():\r\n self.add_pv(val % prefix, attr= key)\r\n \r\n for i in self._chans:\r\n for key, val in self.calc_attrs.items():\r\n self.add_pv(val % (prefix, i), attr = key % i)\r\n self._mutable = False\r\n \r\n def AutoCountMode(self):\r\n \"set to autocount mode\"\r\n self.put('CONT', 1)\r\n\r\n def OneShotMode(self):\r\n \"set to one shot mode\" \r\n self.put('CONT', 0)\r\n\r\n def CountTime(self, ctime):\r\n \"set count time\"\r\n self.put('TP', ctime)\r\n \r\n def Count(self, ctime=None, wait=False):\r\n \"set count, with optional counttime\"\r\n if ctime is not None:\r\n self.CountTime(ctime)\r\n self.put('CNT', 1, wait=wait)\r\n epics.ca.poll()\r\n\r\n def EnableCalcs(self):\r\n \" enable calculations\"\r\n self.put('calc_enable', 1)\r\n\r\n def setCalc(self, i, calc):\r\n \"set the calculation for scaler i\"\r\n attr = 'expr%i' % i\r\n self.put(attr, calc)\r\n\r\n def getNames(self):\r\n \"get all names\"\r\n return [self.get('NM%i' % i) for i in self._chans]\r\n\r\n def Read(self, use_calc=False):\r\n \"read all values\"\r\n attr = 'S%i'\r\n if use_calc:\r\n attr = 'calc%i'\r\n return [self.get(attr % i) for i in self._chans]\r\n","sub_path":"Python/epics/devices/scaler.py","file_name":"scaler.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"203020602","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division, print_function, absolute_import\n\nfrom timeit import time\nimport warnings\nimport cv2\nimport numpy as np\nfrom PIL import Image\nfrom Nyolo import YOLO\n#from yolo import YOLO\n\nfrom deep_sort import preprocessing\nfrom deep_sort import nn_matching\nfrom deep_sort.detection import Detection\nfrom deep_sort.detection_yolo import Detection_YOLO\nfrom deep_sort.tracker import Tracker\nfrom tools import generate_detections as gdet\nimport imutils.video\n\nimport json\nimport glob\nimport os\n\nwarnings.filterwarnings('ignore')\n\n@classmethod\ndef getValue(cls, key, items):\n values = [x['Value'] for x in items if 'Key' in x and 'Value' in x and x['Key'] == key]\n return values[0] if values else None\n\ndef main(yolo, input):\n\n #拡張子ありのファイル名\n basename = os.path.basename(input)\n print(\" START YOLOv4 + DeepSort input file is \", basename)\n\n # Definition of the parameters\n max_cosine_distance = 0.3\n nn_budget = None\n nms_max_overlap = 1.0\n\n # Deep SORT\n model_filename = '../model/mars-small128.pb'\n cencoder = gdet.create_box_encoder(model_filename, batch_size=1)\n pencoder = gdet.create_box_encoder(model_filename, batch_size=1)\n\n cmetric = nn_matching.NearestNeighborDistanceMetric(\"cosine\", max_cosine_distance, nn_budget)\n pmetric = nn_matching.NearestNeighborDistanceMetric(\"cosine\", max_cosine_distance, nn_budget)\n ctracker = Tracker(cmetric)\n ptracker = Tracker(pmetric)\n\n tracking = True\n writeVideo_flag = True\n\n #推論したいカテゴリを設定\n cl_list = ['Pedestrian', 'Car']\n\n video_capture = cv2.VideoCapture(input)\n\n fps = 0.0\n fps_imutils = imutils.video.FPS().start()\n if writeVideo_flag:\n basename_without_ext = os.path.splitext(os.path.basename(input))[0]\n fname = basename_without_ext +'output_yolov4.mp4'\n output_path = '../output/'+ fname\n video_FourCC = int(video_capture.get(cv2.CAP_PROP_FOURCC))\n video_fps = video_capture.get(cv2.CAP_PROP_FPS)\n video_size = (int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n\n out = cv2.VideoWriter(output_path, video_FourCC, video_fps, video_size)\n frame_index = -1\n\n Nm_fr = 0\n all_result = []\n\n while True:\n\n Car_result_ALL = []\n Pedestrian_result_ALL = []\n\n Nm_fr = Nm_fr + 1\n\n ret, frame = video_capture.read() # frame shape 1920*1216*3\n\n if ret != True:\n break\n\n print(\"Frame no. = \", Nm_fr)\n t1 = time.time()\n image = Image.fromarray(frame[...,::-1])\n\n cboxes, cconfidence, cclasses = yolo.detect_image(image, cl_list[1])\n pboxes, pconfidence, pclasses = yolo.detect_image(image, cl_list[0])\n\n if tracking:\n cfeatures = cencoder(frame, cboxes)\n pfeatures = pencoder(frame, pboxes)\n\n cdetections = [Detection(cbbox, cconfidence, ceach_class, cfeature) for cbbox, cconfidence, ceach_class, cfeature in \\\n zip(cboxes, cconfidence, cclasses, cfeatures)]\n pdetections = [Detection(pbbox, pconfidence, peach_class, pfeature) for pbbox, pconfidence, peach_class, pfeature in \\\n zip(pboxes, pconfidence, pclasses, pfeatures)]\n #else:\n # detections = [Detection_YOLO(bbox, confidence, each_class) for bbox, confidence, each_class in \\\n # zip(boxes, confidence, classes)]\n\n # Run non-maxima suppression.\n cboxes = np.array([d.tlwh for d in cdetections])\n cscores = np.array([d.confidence for d in cdetections])\n cindices = preprocessing.non_max_suppression(cboxes, nms_max_overlap, cscores)\n cdetections = [cdetections[i] for i in cindices]\n\n pboxes = np.array([d.tlwh for d in pdetections])\n pscores = np.array([d.confidence for d in pdetections])\n pindices = preprocessing.non_max_suppression(pboxes, nms_max_overlap, pscores)\n pdetections = [pdetections[i] for i in pindices]\n\n if tracking:\n # Call the tracker\n ctracker.predict()\n ctracker.update(cdetections)\n\n ptracker.predict()\n ptracker.update(pdetections)\n\n for ctrack in ctracker.tracks:\n if not ctrack.is_confirmed() or ctrack.time_since_update > 1:\n continue\n cbbox = ctrack.to_tlbr()\n cv2.rectangle(frame, (int(cbbox[0]), int(cbbox[1])), (int(cbbox[2]), int(cbbox[3])), (0, 0, 255), 3)\n cv2.putText(frame, \"ID: \" + str(ctrack.track_id), (int(cbbox[0]), int(cbbox[1])), 0, \\\n 1.5e-3 * frame.shape[0], (0, 0, 255), 3)\n\n #OUTPUT TRACKING\n ID = int(ctrack.track_id)\n left = int(cbbox[0])\n top = int(cbbox[1])\n right = int(cbbox[2])\n bottom = int(cbbox[3])\n\n Car_result = {'id': ID, 'box2d': [left,top,right,bottom]}#予測結果\n print(\"Car_result = \", Car_result)\n Car_result_ALL.append(Car_result)\n\n for ptrack in ptracker.tracks:\n if not ptrack.is_confirmed() or ptrack.time_since_update > 1:\n continue\n pbbox = ptrack.to_tlbr()\n cv2.rectangle(frame, (int(pbbox[0]), int(pbbox[1])), (int(pbbox[2]), int(pbbox[3])), (255, 0, 0), 3)\n cv2.putText(frame, \"ID: \" + str(ptrack.track_id), (int(pbbox[0]), int(pbbox[1])), 0, \\\n 1.5e-3 * frame.shape[0], (255, 0, 0), 3)\n\n #OUTPUT TRACKING\n ID = int(ptrack.track_id)\n left = int(pbbox[0])\n top = int(pbbox[1])\n right = int(pbbox[2])\n bottom = int(pbbox[3])\n\n Pedestrian_result = {'id': ID, 'box2d': [left,top,right,bottom]}#予測結果\n print(\"Pedestrian_result = \", Pedestrian_result)\n Pedestrian_result_ALL.append(Pedestrian_result)\n\n #YOLOv4 output to frame for Car\n for cdet in cdetections:\n cbbox = cdet.to_tlbr()\n cscore = \"%.2f\" % round(cdet.confidence * 100, 2) + \"%\"\n cv2.rectangle(frame, (int(cbbox[0]), int(cbbox[1])), (int(cbbox[2]), int(cbbox[3])), (255, 255, 255), 2)\n if len(cclasses) > 0:\n ceach_class = cdet.cls\n cv2.putText(frame, str(ceach_class) + \" \" + cscore, (int(cbbox[0]), int(cbbox[3])), 0, \\\n 1.5e-3 * frame.shape[0], (255, 255, 255), 2)\n\n #YOLOv4 output to frame for Pedestrian\n for pdet in pdetections:\n pbbox = pdet.to_tlbr()\n pscore = \"%.2f\" % round(pdet.confidence * 100, 2) + \"%\"\n cv2.rectangle(frame, (int(pbbox[0]), int(pbbox[1])), (int(pbbox[2]), int(pbbox[3])), (127, 127, 127), 2)\n if len(pclasses) > 0:\n peach_class = pdet.cls\n cv2.putText(frame, str(peach_class) + \" \" + pscore, (int(pbbox[0]), int(pbbox[3])), 0, \\\n 1.5e-3 * frame.shape[0], (127, 127, 127), 2)\n\n # Each frame result\n all_result.append({'Car': Car_result_ALL, 'Pedestrian': Pedestrian_result_ALL})\n\n if writeVideo_flag:\n # save a frame\n out.write(frame)\n frame_index = frame_index + 1\n\n fps_imutils.update()\n\n fps = (fps + (1./(time.time()-t1))) / 2\n print(\" FPS = %f\"%(fps))\n\n if writeVideo_flag:\n out.release()\n\n video_capture.release()\n\n fps_imutils.stop()\n print('imutils FPS: {}'.format(fps_imutils.fps()))\n\n return {basename: all_result}\n\nif __name__ == '__main__':\n\n #出力結果\n Output_list = ''\n\n #読みこむデータのパスを記載\n data_path = '../data'\n\n #複数のファイルに対応済み\n videos = sorted(glob.glob(data_path+'/*.mp4'))\n\n for i in range(len(videos)):\n video_path = videos[i]\n\n Output = main(YOLO(), video_path)\n print(\"Output = \", Output)\n\n if i == 0:#最初はキーを指定して辞書作成\n Output_list = Output\n else:#2個目以降はキーを指定して辞書追加\n Output_list.update(Output)\n\n print(\"**************************\")\n with open('../output/prediction.json', 'w') as f:\n json.dump(Output_list, f)\n","sub_path":"YOLOv4_DeepSort_submit_608/src/sample_togakyo.py","file_name":"sample_togakyo.py","file_ext":"py","file_size_in_byte":8870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"344350211","text":"import discord\nfrom discord.ext import commands\n\nfrom chickensmoothie import _get_web_data\n\n\nclass Oekaki:\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n @commands.guild_only()\n async def oekaki(self, ctx, link: str = ''):\n data = await _get_web_data(link) # Get Oekaki data\n if data[0]: # If data is valid\n base_link = 'http://www.chickensmoothie.com/Forum/'\n\n oekaki_title = data[1].xpath('//h3[@class=\"first\"]/a/text()')[0] # Title of drawing\n image = 'https://www.chickensmoothie.com' + data[1].xpath('//li[@class=\"ok-topic-head-image large\"]/img/@src')[0] # Image of drawing\n user_icon = base_link[:-1] + data[1].xpath('//dl[@class=\"postprofile\"]')[0].xpath('dt/a/img/@src')[0][1:] # The profile picture of the artist\n warning_text = 'Reminder!! Copying another person\\'s art without permission to reproduce their work is a form of art-theft!' # General warning text regarding Oekaki art\n\n if data[1].xpath('//table[@class=\"ok-drawing-info\"]/tr')[0].xpath('td')[1].xpath('a/text()')[0] == 'Click to view': # If drawing is based off another drawing\n artist_links = data[1].xpath('//table[@class=\"ok-drawing-info\"]/tr')[1].xpath('td')[1].xpath('a/@href') # Drawing information titles\n artist_values = data[1].xpath('//table[@class=\"ok-drawing-info\"]/tr')[1].xpath('td')[1].xpath('a/text()') # Drawing information values\n else: # If drawing is not based off another drawing\n artist_links = data[1].xpath('//table[@class=\"ok-drawing-info\"]/tr')[0].xpath('td')[1].xpath('a/@href') # Drawing information titles\n artist_values = data[1].xpath('//table[@class=\"ok-drawing-info\"]/tr')[0].xpath('td')[1].xpath('a/text()') # Drawing information values\n\n artist_text = '[' + artist_values[0] + '](' + base_link + artist_links[0][1:] + ') [' + artist_values[1] + '(' + base_link + artist_links[1][1:] + ')]' # [Artist Name](Link to Artist) [gallery](Link to Artist gallery) | Formats to Artist Name [gallery]\n\n embed = discord.Embed(title=oekaki_title, colour=0x4ba139, url=link) # Create embed\n embed.add_field(name='Artist', value=artist_text) # Add Artist field\n embed.set_footer(text=warning_text, icon_url=\"https://vignette.wikia.nocookie.net/pufflescp/images/6/68/Red_Warning_Triangle.png/revision/latest?cb=20160718024653&format=original\") # Add warning text to footer\n embed.set_image(url=image) # Add drawing to embed\n embed.set_thumbnail(url=user_icon) # Set thumbnail as user profile picture\n\n await ctx.send(embed=embed) # Send embed\n else: # If data is not valid\n await ctx.send(embed=data[1]) # Send embed\n\n\ndef setup(bot):\n bot.add_cog(Oekaki(bot))\n","sub_path":"cogs/oekaki.py","file_name":"oekaki.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"209437983","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/mercury_api/exceptions.py\n# Compiled at: 2018-06-20 15:42:58\n# Size of source mod 2**32: 1130 bytes\n\n\nclass HTTPError(Exception):\n __doc__ = '\\n Generic exception to be used when raising http errors in the application\\n and transforms the message into a dictionary to be used by the app error\\n handler.\\n '\n\n def __init__(self, message, status_code=400):\n Exception.__init__(self)\n self.message = message\n self.status_code = status_code\n\n def to_dict(self):\n payload = {'error':True, \n 'message':self.message}\n return payload","sub_path":"pycfiles/mercury_api-0.1.3-py3.7/exceptions.cpython-37.py","file_name":"exceptions.cpython-37.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"59216970","text":"'''\n ╔╦╗╔═╗ ╔═╗┌─┐┬ ┬ ┌─┐┌─┐┌┬┐┌─┐┬─┐\n ║║╠═╝ ║ │ ││ │ ├┤ │ │ │ │├┬┘\n ═╩╝╩ ╚═╝└─┘┴─┘┴─┘└─┘└─┘ ┴ └─┘┴└─\n'''\nfrom django.db import models\nfrom django.contrib import admin\nimport random\nimport math\n\nclass Config(models.Model):\n class Meta:\n ordering = ['title', 'epic'] \n from scenarist.models.epics import Epic\n from scenarist.models.dramas import Drama\n title = models.CharField(default='', max_length=128, blank=True, unique=True)\n epic = models.ForeignKey(Epic, null=True, blank=True, on_delete=models.SET_NULL)\n description = models.TextField(max_length=128,default='',blank=True)\n gamemaster = models.CharField(default='zaffarelli@gmail.com', max_length=128, blank=True)\n is_active = models.BooleanField(default=False)\n smart_code = models.CharField(default='xxxxxx', max_length=6, blank=True)\n current_drama = models.ForeignKey(Drama, null=True, blank=True, on_delete=models.SET_NULL)\n \n def __str__(self):\n return '%s' % (self.title)\n\n def parse_details(self):\n \"\"\" Return details from the config epic, dramas and acts \n \"\"\"\n from scenarist.models.epics import Epic\n from scenarist.models.dramas import Drama\n from scenarist.models.acts import Act\n from scenarist.models.events import Event\n from collector.utils.fs_fics7 import get_keywords\n \n epic = Epic.objects.get(title = self.epic.title)\n dramas = Drama.objects.filter(epic = epic).order_by('chapter','date')\n context_dramas =[]\n for drama in dramas:\n context_acts = []\n acts = Act.objects.filter(drama = drama).order_by('chapter','date')\n for act in acts: \n context_events = []\n events = Event.objects.filter(act = act).order_by('chapter','date')\n for event in events:\n context_event = {'title':event.title, 'data': event}\n context_events.append(context_event)\n context_act = {'title':act.title, 'data': act, 'events': context_events}\n context_acts.append(context_act)\n context_drama = {'title':drama.title, 'data': drama, 'acts': context_acts}\n context_dramas.append(context_drama)\n context = {'title':epic.title, 'data': epic, 'dramas': context_dramas}\n context['keywords'] = get_keywords()\n #print(context)\n return context\n\n def prepare_colorset(self, size = 16): \n colorset = []\n hcolorset = []\n idx = 0\n circ = 360.0\n vmin, vmax = 0X33, 0xcc\n colval = [vmin,vmin,vmin]\n try:\n angle_inc = (circ*math.pi * 2) / (size)\n #print('ok')\n except:\n #print('paf')\n return [],[]\n #print('Full circle=%0.4f'%(math.pi * 2))\n angle_step = (circ*math.pi * 2) / 8\n #compo_range = (vmax-vmin)/angle_step\n target_component = [\n [2,+1], # 0 0 0 0\n [1,+1], # 0 0 1 1\n [2,-1], # 0 1 1 3\n [0,+1], # 0 1 0 2\n [2,+1], # 1 1 0 6\n [1,-1], # 1 1 1 7\n [2,-1], # 1 0 1 5\n [0,-1] # 1 0 0 4\n ]\n comp = 0\n while idx < size:\n angle = angle_inc * (idx % size)\n angle_steps_covered = int(angle / angle_step)\n inc = (vmax-vmin)*6/size #(angle - int(angle_steps_covered)*angle_step)/angle_step * (vmax-vmin)\n\n cv = target_component[comp][0]\n if target_component[comp][1] > 0:\n colval[cv] += int(inc)\n if colval[cv]+inc>vmax:\n comp += 1 \n else:\n colval[cv] -= int(inc)\n if colval[cv]-inc 1:\n value = par.split(' / ')[0] \n if arrfetch.get(value) is None: \n arrfetch[value] = 1\n else:\n arrfetch[value] += 1 \n for x in arrfetch:\n inside_labels.append(x)\n dat.append(arrfetch[x])\n border.append('#C0C0C0C0')\n colors, hoverColors = self.prepare_colorset(len(border))\n inside_datasets = [{\n 'data': dat,\n 'backgroundColor': colors ,\n 'hoverBackgroundColor': hoverColors,\n 'borderColor': border,\n 'hoverBorderColor': colors,\n 'borderWidth': 1\n }]\n data = {\n 'labels': inside_labels,\n 'datasets': inside_datasets\n }\n full_data = {\n 'name':sp,'data': {\n 'type': ty,\n 'data': data,\n 'options': {\n 'title': {\n 'display': True,\n 'text': search_pattern,\n 'fontColor':'#fff',\n },\n 'legend': {\n 'display': False,\n 'position':'right',\n 'labels':{\n 'fontColor':'#fff',\n }\n }, \n 'circumference': math.pi,\n 'rotation': -math.pi,\n 'cutoutPercentage': 40,\n }\n }\n }\n return full_data\n\n\n\nclass ConfigAdmin(admin.ModelAdmin):\n ordering = ['title']\n\n\n","sub_path":"collector/models/configs.py","file_name":"configs.py","file_ext":"py","file_size_in_byte":6033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"19925780","text":"from abc import ABCMeta, abstractproperty\nimport re\nfrom core.errors import SuchStateNotExistError, TransionBetweenStatesNotExistError\n\n\nclass FiniteStateMachine(metaclass=ABCMeta):\n \"\"\"\n Base class for creating FSM\n \"\"\"\n __metaclass__ = ABCMeta\n\n def __init__(self):\n self.current_state = self.start_state\n\n self._compiled_input_alphabet = {}\n for state, pattern in self.input_alphabet.items():\n self._compiled_input_alphabet[state] = re.compile(pattern)\n\n @abstractproperty\n def state_transition_map(self):\n \"\"\"\n Format:\n [\n ...,\n ('STATE_1', 'STATE_2')\n ...,\n ]\n :return: list Should be list of tuples\n \"\"\"\n pass\n\n @abstractproperty\n def input_alphabet(self):\n \"\"\"\n Format:\n {\n ...,\n 'STATE_1': '\\d'\n ...,\n }\n :return: dictionary Dictionary where key is some state and key is regex pattern\n \"\"\"\n pass\n\n @abstractproperty\n def start_state(self):\n pass\n\n def make_next_step(self, character):\n \"\"\"\n Validate that character move current state on next valid state.\n Return string and move current state\n :param character: string\n :raise TransionBetweenStatesNotExistError\n :return: string\n \"\"\"\n next_state = self._get_next_state(character)\n if (self.current_state, next_state) not in self.state_transition_map:\n raise TransionBetweenStatesNotExistError\n\n should_change_state = True\n try:\n method_name = 'move_from_{}_state'.format(self.current_state.lower())\n move_method = getattr(self, method_name)\n should_change_state = move_method(character, next_state)\n except AttributeError:\n pass\n\n if should_change_state:\n self.current_state = next_state\n return True\n\n def _get_next_state(self, character):\n \"\"\"\n Get next state by character and _compiled_input_alphabet dict\n :param character:\n :raise SuchStateNotExistError\n :return: string\n \"\"\"\n for state, regex in self._compiled_input_alphabet.items():\n if regex.match(character):\n return state\n raise SuchStateNotExistError\n\n\nclass CalculatorFSM(FiniteStateMachine):\n def __init__(self):\n super(CalculatorFSM, self).__init__()\n self.calculation_string = '0'\n\n state_transition_map = [\n ('START', 'NUMBER'),\n ('START', 'DOT'),\n ('START', 'START'),\n ('START', 'RESULT'),\n ('START', 'CALCULATION'),\n ('NUMBER', 'NUMBER'),\n ('NUMBER', 'CALCULATION'),\n ('NUMBER', 'DOT'),\n ('NUMBER', 'RESULT'),\n ('NUMBER', 'START'),\n ('DOT', 'NUMBER'),\n ('DOT', 'RESULT'),\n ('DOT', 'START'),\n ('CALCULATION', 'NUMBER'),\n ('CALCULATION', 'RESULT'),\n ('CALCULATION', 'START'),\n ('CALCULATION', 'CALCULATION'),\n ('RESULT', 'NUMBER'),\n ('RESULT', 'DOT'),\n ('RESULT', 'CALCULATION'),\n ('RESULT', 'START'),\n ('RESULT', 'RESULT'),\n ]\n\n input_alphabet = {\n 'NUMBER': '^\\d$',\n 'CALCULATION': '^(/|\\*|-|\\+)$',\n 'RESULT': '^=$',\n 'START': '^C$',\n 'DOT': '^\\.$',\n }\n\n start_state = 'START'\n\n def move_from_start_state(self, character, next_state):\n \"\"\"\n :param character:\n :return: bool\n \"\"\"\n if (next_state == 'NUMBER' and character != '0') or (next_state == 'CALCULATION' and character == '-'):\n self.calculation_string = character\n return True\n if next_state == 'DOT':\n self.calculation_string += '.'\n return True\n if next_state == 'CALCULATION' and character != '-':\n raise TransionBetweenStatesNotExistError\n return True\n if next_state == 'RESULT':\n return True\n return False\n\n def move_from_number_state(self, character, next_state):\n \"\"\"\n :param character:\n :return: bool\n \"\"\"\n is_valid_number_for_replace = (next_state == 'NUMBER' and self.calculation_string == '0')\n if is_valid_number_for_replace:\n self.calculation_string = character\n return True\n\n is_valid_number = (next_state == 'NUMBER' and (character != '0' or self.calculation_string != '0'))\n last_number = re.split(r'(/|\\*|-|\\+)', self.calculation_string)[-1]\n is_valid_dot = (next_state == 'DOT' and '.' not in last_number)\n if is_valid_number or next_state == 'CALCULATION' or is_valid_dot:\n self.calculation_string += character\n return True\n\n if next_state == 'START':\n self.calculation_string = '0'\n return True\n\n if next_state == 'RESULT':\n self.calculation_string = self.calculate()\n return True\n\n return False\n\n def move_from_dot_state(self, character, next_state):\n if next_state == 'NUMBER':\n self.calculation_string += character\n return True\n\n if next_state == 'START':\n self.calculation_string = '0'\n return True\n\n if next_state == 'RESULT':\n self.calculation_string = self.calculate()\n return True\n return False\n\n def move_from_calculation_state(self, character, next_state):\n if next_state == 'NUMBER' or (next_state == 'CALCULATION' and character == '-' and self.calculation_string[-1] != '-'):\n self.calculation_string += character\n return True\n if next_state == 'START':\n self.calculation_string = '0'\n return True\n if next_state == 'RESULT':\n self.calculation_string = self.calculation_string[0:-1]\n self.calculation_string = self.calculate()\n return True\n if next_state == 'CALCULATION' and character != '-':\n raise TransionBetweenStatesNotExistError\n return False\n\n def move_from_result_state(self, character, next_state):\n is_valid_dot = (next_state == 'DOT' and '.' not in self.calculation_string)\n is_valid_number = (next_state == 'NUMBER' and character != '0' and self.calculation_string != '0')\n if is_valid_dot or is_valid_number or next_state == 'CALCULATION':\n self.calculation_string += character\n return True\n\n is_number_for_replace = (next_state == 'NUMBER' and self.calculation_string == '0')\n if is_number_for_replace:\n self.calculation_string = character\n return True\n\n if next_state == 'START':\n self.calculation_string = '0'\n return True\n\n if next_state == 'RESULT':\n return True\n return False\n\n def calculate(self):\n result = repr(eval(self.calculation_string))\n\n if '.' in result:\n while result.endswith('0') or result.endswith('.'):\n result = result[0:-1]\n\n return result\n","sub_path":"calculator/apps/core/finite_state_machine.py","file_name":"finite_state_machine.py","file_ext":"py","file_size_in_byte":7176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"169917166","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql import Row\n\nMOVIE_INDEX = {}\n\n\ndef loadMovieNamesFromIndexFile(movie_index_file):\n with open(movie_index_file) as index_file_object:\n for line in index_file_object:\n split_fields = line.split(\"|\")\n MOVIE_INDEX[int(split_fields[0])] = split_fields[1]\n\n\ndef build_row_tuple_for_rating_data(line):\n _, movie_id, rating, _ = line.split(\"\\t\")\n return Row(movie_id=int(movie_id), rating=int(rating))\n\n\nif __name__ == \"__main__\":\n spark_session = SparkSession.builder.appName(\"Lowest Rated Movies\").getOrCreate()\n\n sc = spark_session.sparkContext\n\n lines = sc.textFile(\"hdfs:///movie_data/u.data\")\n\n row_objects = lines.map(build_row_tuple_for_rating_data)\n\n rating_dataframes = spark_session.createDataFrame(row_objects)\n\n avg_movie_rating_dff = rating_dataframes.groupBy(\"movie_id\").avg(\"rating\")\n\n count_ratings = rating_dataframes.groupBy(\"movie_id\").count()\n\n averages_and_counts = count_ratings.join(avg_movie_rating_dff, \"movie_id\")\n\n ordered_results = averages_and_counts.orderBy(\"avg(rating)\").take(10)\n\n loadMovieNamesFromIndexFile(\"u.item\")\n\n for movie in ordered_results:\n print (MOVIE_INDEX[movie[0]], movie[1], movie[2])\n\n sc.stop()","sub_path":"hadoop_examples/spark_examples/lowest_rated_movies_using_dataframes.py","file_name":"lowest_rated_movies_using_dataframes.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"497248893","text":"class Solution(object):\n def findLadders(self, beginWord, endWord, wordList):\n \"\"\"\n :type beginWord: str\n :type endWord: str\n :type wordlist: Set[str]\n :rtype: List[List[int]]\n \"\"\"\n wordList.add(endWord)\n level={beginWord}\n parents=collections.defaultdict(set)\n while level and endWord not in parents:\n next_level=collections.defaultdict(set)\n for node in level:\n for c in string.ascii_lowercase:\n for i in range(len(beginWord)):\n n=node[:i]+c+node[i+1:]\n if n in wordList and n not in parents:\n next_level[n].add(node)\n level=next_level\n parents.update(next_level)\n rst=[[endWord]]\n while rst and rst[0][0]!=beginWord:\n rst=[[p]+r for r in rst for p in parents[r[0]]]\n return rst ","sub_path":"126-Word-Ladder-II/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"638985345","text":"import sys, os\nsys.path.append(os.getcwd() + r'\\Modules')\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport Hubber_SubGD as hs\nimport Linear_Regression_Class as lr\nfrom sklearn.preprocessing import StandardScaler\n\ndef generate_samples(m, k):\n \"\"\" 产生含有k个异常数据、m个正常线性数据的数据集 \"\"\"\n X_normal = 2* (np.random.rand(m, 1) - 0.5)\n y_normal = X_normal + np.random.normal(0, 0.1, (m, 1))\n X_outlier = 2* (np.random.rand(k, 1) - 0.5)\n y_outlier = X_outlier + np.random.normal(3, 0.1, (k, 1))\n X = np.concatenate((X_normal, X_outlier), axis=0)\n y = np.concatenate((y_normal, y_outlier), axis=0)\n return X, y\n# end\n\ndef process_features(X):\n \"\"\" 加全1列 \"\"\"\n m, n = X.shape\n X = np.c_[np.ones((m, 1)), X] # 注意:这一步必须在标准化之后实施\n return X\n# end\n\nnp.random.seed(0)\nnormal_spn = 100 # 正常数据数量\noutlin_spn = 10 # 异常数据数量\nX, y = generate_samples(normal_spn, outlin_spn)\nX = X.reshape(normal_spn + outlin_spn, -1)\ny = y.reshape(normal_spn + outlin_spn, -1)\n\nX_proc = process_features(X)\n\n# print(X.shape, y.shape, X_proc.shape)\nmodel_l = lr.LinearRegression() # 使用普通线性回归模型作为对照\nmodel_l.fit(X_proc, y)\n\nmodel_h = hs.Hubber_SubGD(epsilon=0.2)\nmodel_h.fit(X_proc, y, eta=0.01, N=4000)\n\nfig, ax = plt.subplots(1, 1, figsize=(5, 4))\nax.scatter(X, y, s=5, c='b')\nLX = np.linspace(-1, 1, 500).reshape(500, 1)\n\nLX_proc = process_features(LX)\npred_l = model_l.predict(LX_proc)\npred_h = model_h.predict(LX_proc)\n\nax.plot(LX, pred_l, label=\"LinearRegression model\", color='red')\nax.plot(LX, pred_h, label=\"Hubber_SubGD model\", color='green')\nax.legend()\n\nplt.show()\n","sub_path":"Project/Hubber/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"26728050","text":"import cv2\nimport numpy as np\nimport sqlite3\nimport os\n\nconn = sqlite3.connect('database.db')\nc = conn.cursor()\n\nfname = \"recognizer/trainingData.yml\"\nif not os.path.isfile(fname):\n\tprint(\"Please train the data first\")\n\texit(0)\n\n#using the same method to detect the face\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\ncap = cv2.VideoCapture(0)\n#using the same method to extract the features\nrecognizer = cv2.face.LBPHFaceRecognizer_create()\n#get the features from the file data - file.yml\nrecognizer.read(fname)\n\nwhile True:\n\tret, img = cap.read()\n\tif ret == True:\n\t\tgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\t\tfaces = face_cascade.detectMultiScale(gray, 1.3, 5)\n\t\tfor(x,y,w,h) in faces:\n\t\t\tcv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 3)\n\t\t\t#with the recognizer we trained then we predict an unknown image.\n\t\t\tids, conf = recognizer.predict(gray[y:y+h,x:x+w])\n\t\t\tc.execute(\"select name from users where id = (?);\", (ids,))\n\t\t\tresult = c.fetchall()\n\t\t\tname = result[0][0]\n\t\t\tif conf < 50:\n\t\t\t\tcv2.putText(img, name, (x+2,y+h-5), cv2.FONT_HERSHEY_SIMPLEX, 1, (150,255,0), 2)\n\t\t\telse:\n\t\t\t\tcv2.putText(img, 'Unkown', (x+2,y+h-5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255),2)\n\n\t\tcv2.imshow('Face Recognizer', img)\n\t\tk = cv2.waitKey(30) & 0xff\n\t\tif k == 27:\n\t\t\tbreak\n\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"face_recognition/detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"103166453","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef pplot():\n a = 10\n E = 0.9\n V_0 = 1\n h = 1\n m = 1\n\n k_0 = np.sqrt(2*m*E/h**2+0J)\n k_1 = np.sqrt(-2*m*(E-V_0)/h**2+0J)\n\n print(\"k_0 =\",k_0)\n print(\"k_1 =\",k_1)\n\n\n t = (4*k_0*k_1*np.exp(-1J*a*(k_0-k_1)))/((k_0+k_1)**2 - np.exp(2*1J*a*k_1)*(k_0-k_1)**2)\n r = ((k_0**2 - k_1**2)*np.sin(a*k_1))/(2*1J*k_0*k_1*np.cos(a*k_1)+(k_0**2+k_1**2)*np.sin(a*k_1))\n\n\n print(\"t=\",t)\n print(\"r=\",r)\n\n A_r = 1\n A_l = r\n C_l = 0\n C_r = t\n B_l = (1+r)*(k_1-k_0)/(2*k_1)\n B_r = 1+r - B_l\n\n\n psi_I = lambda x: A_r *np.exp(1J*k_0*x) + A_l *np.exp(-1J*k_0*x)\n\n psi_II = lambda x: B_r *np.exp(1J*k_1*x) + B_l *np.exp(-1J*k_1*x) \n\n psi_III= lambda x: C_r *np.exp(1J*k_0*x) + C_l *np.exp(-1J*k_0*x) \n\n x1 = np.linspace(-3,0,100)\n x2 = np.linspace(0,a,100)\n x3 = np.linspace(a,a+5,100)\n\n plt.figure()\n plt.plot(x1,np.absolute(psi_I(x1)))\n plt.plot(x2,np.absolute(psi_II(x2)))\n plt.plot(x3,np.absolute(psi_III(x3)))\n plt.show()\ndef plot_T(a,c):\n m= 1\n h = 1\n V_0 = 1\n E = np.arange(0,1,0.001)\n E2 = np.arange(1,2,0.001)\n\n k = np.sqrt(2*m*E/h**2)\n kappa = np.sqrt(2*m*(V_0-E)/h**2)\n T = 1/ (1 + ((k**2+kappa**2)/(2*k*kappa))**2 * np.sinh(kappa*a)**2)\n\n k2 = np.sqrt(2*m*E2/h**2)\n kappa2 = np.sqrt(2*m*(E2-V_0)/h**2)\n T2 = 1/ (1 + ((k2**2-kappa2**2)/(2*k2*kappa2))**2 * np.sin(kappa2*a)**2)\n\n #T2 = (1 - E2/V_0)/((1-E2/V_0) - (V_0 / (4*E2)*np.sinh(k_1b*a)**2))\n plt.plot(E,T, c=c,label=\"a=\"+str(a))\n plt.plot(E2,T2,c=c)\nplt.figure()\nplot_T(3,\"r\")\nplot_T(4,\"b\")\nplot_T(5,\"g\")\nplt.ylabel(\"Durchgangswahrscheinlichkeit $T$\")\nplt.xlabel(\"$E/V_0$\")\nplt.legend(loc=7)\nplt.grid(True)\nplt.savefig(\"tunnel1.pdf\")\nplt.show()\n\n","sub_path":"rtm/RTM_03.09/tunneln.py","file_name":"tunneln.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"93518980","text":"#!/usr/bin/env python3\r\n\r\n\"\"\"\r\nCreated on Fri Feb 17 09:20:21 2017\r\n\r\n@author: Josh\r\n\r\nProgram to solve problem 5 from the week 3 exercises.\r\n\"\"\"\r\n\r\n\r\ndef prime(n):\r\n \"\"\"\r\n Determine if n is prime\r\n Parameters\r\n ----------\r\n n : int\r\n Returns\r\n -------\r\n prime : bool\r\n True if n prime, False otherwise\r\n \"\"\"\r\n\r\n if n < 2:\r\n return False\r\n\r\n # When checking for divisors, only need to go up to the square\r\n # root of n since if ab = n & a > sqrt(n) then b < sqrt(n)\r\n for x in range(2, int(n**0.5)+1):\r\n if n % x == 0:\r\n return False\r\n return True\r\n\r\n\r\ndef f(x):\r\n \"\"\"\r\n Function detailed in w2e5\r\n\r\n Parameters\r\n ----------\r\n x : int\r\n\r\n Returns\r\n -------\r\n f : int\r\n \"\"\"\r\n\r\n if x < 2:\r\n return f(17-abs(x))\r\n\r\n elif not prime(x):\r\n maxDivisor = 0\r\n # Divisors will all be less than x/2\r\n for div in range(1, int(x/2)+1):\r\n if x % div == 0 and div > maxDivisor:\r\n maxDivisor = div\r\n return f(maxDivisor)\r\n\r\n else:\r\n return x\r\n\r\n\r\nnumbers = []\r\nwhile True:\r\n try:\r\n inputNumber = int(input(\"Enter an integer: \"))\r\n if inputNumber == 0:\r\n break\r\n numbers.append(inputNumber)\r\n except ValueError:\r\n print(\"Inputs must be integers\")\r\n\r\nfor x in numbers:\r\n print(\"f(%s) = %s\" % (x, f(x)))\r\n","sub_path":"files/3/ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"500939157","text":"'''\n fmt = getattr(settings, 'LOG_FORMAT', None)\n lvl = getattr(settings, 'LOG_LEVEL', logging.DEBUG)\n\n logging.basicConfig(format=fmt, level=lvl)\n logging.debug(newobject.OrderId.id)\n '''\n\nfrom django.shortcuts import render\nfrom django.shortcuts import get_object_or_404\nfrom django.http import JsonResponse\nfrom django.template.loader import render_to_string\nimport os\nimport jdatetime\nfrom django.http import HttpResponseRedirect\nfrom django.http import HttpResponse\nfrom django.views.decorators import csrf\nimport django.core.serializers\nimport logging\nfrom django.conf import settings\nfrom cmms.models.business import *\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.utils.decorators import method_decorator\nfrom django.views import View\n#from django.core import serializers\nimport json\nfrom django.forms.models import model_to_dict\nfrom cmms.forms import BusinessFileForm\nfrom django.views.decorators.http import require_POST\nfrom django.core.files.storage import default_storage\n\n###################################################################\ndef list_businessFile(request,id=None):\n books = BusinessFile.objects.all()\n return render(request, 'cmms/business_file/businessFileList.html', {'businessFiles': books})\n\n\n###################################################################\ndef js_list_businessFile(request,woId):\n data=dict()\n books=BusinessFile.objects.filter(businessFileBusinessId=woId)\n\n data['html_businessFile_list']= render_to_string('cmms/business_file/partialBusinessFilelist.html', {\n 'businessFiles': books\n })\n data['form_is_valid']=True\n return JsonResponse(data)\n\n\n################################################################### ###################################################################\n@csrf_exempt\ndef save_businessFile_form(request, form, template_name,woId=None):\n data = dict()\n if (request.method == 'POST'):\n if form.is_valid():\n form.save()\n data['form_is_valid'] = True\n fmt = getattr(settings, 'LOG_FORMAT', None)\n lvl = getattr(settings, 'LOG_LEVEL', logging.DEBUG)\n logging.basicConfig(format=fmt, level=lvl)\n logging.debug( woId)\n books = WorkorderFile.objects.filter(businessFileBusinessId=woId)\n data['html_businessFile_list'] = render_to_string('cmms/workorder_file/partialBusinessFilelist.html', {\n 'businessFiles': books\n })\n else:\n fmt = getattr(settings, 'LOG_FORMAT', None)\n lvl = getattr(settings, 'LOG_LEVEL', logging.DEBUG)\n logging.basicConfig(format=fmt, level=lvl)\n logging.debug( form.errors)\n\n context = {'form': form}\n data['html_businessFile_form'] = render_to_string(template_name, context, request=request)\n return JsonResponse(data)\n###################################################################\n\n\ndef businessFile_delete(request, id):\n comp1 = get_object_or_404(WorkorderFile, id=id)\n data = dict()\n\n if (request.method == 'POST'):\n comp1.delete()\n data['form_is_valid'] = True # This is just to play along with the existing code\n companies = WorkorderFile.objects.all()\n data['html_businessFile_list'] = render_to_string('cmms/workorder_file/partialBusinessFilelist.html', {\n 'businessFile': companies\n })\n else:\n context = {'businessFile': comp1}\n data['html_businessFile_form'] = render_to_string('cmms/workorder_file/partialBusinessFileDelete.html',\n context,\n request=request,\n )\n return JsonResponse(data)\n###################################################################\n@csrf_exempt\ndef businessFile_create(request):\n woId=-1\n fmt = getattr(settings, 'LOG_FORMAT', None)\n lvl = getattr(settings, 'LOG_LEVEL', logging.DEBUG)\n logging.basicConfig(format=fmt, level=lvl)\n logging.debug( \"dasdsadasdsa\")\n if (request.method == 'POST'):\n body_unicode = request.body.decode('utf-8')\n body = json.loads(body_unicode)\n\n\n data = request.POST.dict()\n\n data['businessFileBusinessId']=body['businessFileBusinessId']\n data['woNotifUser']=body['woNotifUser']\n data['woNotifOnAssignment']=True if body['woNotifOnAssignment']=='true' else False\n data['woNotifOnStatusChange']=True if body['woNotifOnStatusChange']=='true' else False\n data['woNotifOnCompletion']=True if body['woNotifOnCompletion']=='true' else False\n data['woNotifOnTaskCompleted']=True if body['woNotifOnTaskCompleted']=='true' else False\n data['woNotifOnOnlineOffline']=True if body['woNotifOnOnlineOffline']=='true' else False\n\n woId=body['businessFileBusinessId']\n\n form = BusinessFileForm(data)\n\n else:\n form = BusinessFileForm()\n return save_businessFile_form(request, form, 'cmms/workorder_file/partialBusinessFileCreate.html',woId)\n###################################################################\n\n@csrf_exempt\ndef businessFile_update(request, id):\n company= get_object_or_404(WorkorderFile, id=id)\n woId=company.businessFileBusinessId\n if (request.method == 'POST'):\n body_unicode = request.body.decode('utf-8')\n body = json.loads(body_unicode)\n\n data = request.POST.dict()\n\n data['businessFileBusinessId']=body['businessFileBusinessId']\n data['woNotifUser']=body['woNotifUser']\n data['woNotifOnAssignment']=True if body['woNotifOnAssignment']=='true' else False\n data['woNotifOnStatusChange']=True if body['woNotifOnStatusChange']=='true' else False\n data['woNotifOnCompletion']=True if body['woNotifOnCompletion']=='true' else False\n data['woNotifOnTaskCompleted']=True if body['woNotifOnTaskCompleted']=='true' else False\n data['woNotifOnOnlineOffline']=True if body['woNotifOnOnlineOffline']=='true' else False\n\n\n\n form = BusinessFileForm(data, instance=company)\n else:\n form = BusinessFileForm(instance=company)\n return save_businessFile_form(request, form, 'cmms/workorder_file/partialBusinessFileUpdate.html',woId)\n\n\nclass BusinessFileUploadView(View):\n def get(self, request):\n books = BusinessFile.objects.all()\n return render(request, 'cmms/business_file/businessFileList.html', {'businessFiles': books})\n\n def post(self, request,Id=None):\n from django.core.exceptions import ValidationError\n data=dict()\n fmt = getattr(settings, 'LOG_FORMAT', None)\n lvl = getattr(settings, 'LOG_LEVEL', logging.DEBUG)\n company= get_object_or_404(Business, id=Id)\n logging.basicConfig(format=fmt, level=lvl)\n logging.debug( request.FILES)\n valid_extensions = ['.pdf', '.doc', '.docx', '.jpg', '.png', '.xlsx', '.xls']\n ext = os.path.splitext(request.FILES['businessFile'].name)[1]\n if not ext.lower() in valid_extensions:\n raise ValidationError(u'Unsupported file extension.')\n else:\n save_path = os.path.join(settings.MEDIA_ROOT,'documents', request.FILES['businessFile'].name)\n path = default_storage.save(save_path, request.FILES['businessFile'])\n document = BusinessFile.objects.create(businessFile=r'documents/'+request.FILES['businessFile'].name, businessFileBusinessId=company)\n #data = {'is_valid': True, 'name': document.businessFile.name, 'url': document.businessFile.url,'ext':ext,'size':\" MB {0:.2f}\".format(document.businessFile.size/1048576)}\n books = BusinessFile.objects.filter(businessFileBusinessId=Id)\n data['html_businessFile_list'] = render_to_string('cmms/business_file/partialBusinessFilelist.html', {\n 'businessFiles': books})\n data['is_valid']=True\n\n return JsonResponse(data)\n","sub_path":"cmms/views/businessfileview.py","file_name":"businessfileview.py","file_ext":"py","file_size_in_byte":7839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"449393276","text":"import random\n\nannounce = \"\"\ngame_state = True\n\n# Classe responsável pelo jogador\n\nclass Jogador(Mao):\n\n vitorias = 0\n derrotas = 0\n num_cartas = 0\n\n def __init__(self, nome, apostas = 10, saldo = 0):\n self.nome = nome.upper\n \n\n def set_apostas(self, apostas):\n self.apostas = apostas\n\n def set_saldo(self, saldo):\n self.saldo = saldo\n\n def get_nome(self):\n return self.nome\n\n def get_apostas(self):\n return self.apostas\n\n\n# Classe responsável pelo dealer\n\nclass Dealer(Mao):\n\n def __init__(self):\n return super().__init__()\n\n# Classe responsável pelo baralho\n\nclass Baralho(object):\n\n def __init__(self):\n self.cartas = self.baralho = [Cartas('Espadas') + Cartas('Copas') + Cartas('Ouros') + Cartas('Paus')]\n\n def embaralhar_cartas(self):\n #Embaralha randomicamente o baralho\n self.baralho = random.shuffle(self.cartas)\n return self.baralho\n\n def tirar_carta(self):\n return self.baralho.pop\n\n\n# Classe responsável pela construção do baralho dividido por naipes\n\nclass Cartas(object):\n\n def __init__(self, naipe):\n self.naipe = naipe\n return [Carta('A', self.naipe), Carta('K', self.naipe), Carta('J', self.naipe), Carta('Q', self.naipe),\n ('10', self.naipe), ('9', self.naipe), ('8', self.naipe),('7', self.naipe), ('6', self.naipe), ('5', self.naipe),\n ('4', self.naipe), ('3', self.naipe), ('2', self.naipe)]\n\n# Classe responsável pela carta\n\nclass Carta(Cartas):\n\n def __init__(self, nome):\n self.nome = nome\n self.naipe = Cartas.naipe\n self.valor = 0\n\n def __str__(self):\n return \"carta:{}, naipe:{}\".format(self.nome, self.naipe)\n\n def get_carta(self):\n return (self.nome, self.naipe)\n\n# Classe e métodos responsáveis pela mão\n\ndef calcular_valor_da_carta(carta):\n nova_carta = carta\n if nova_carta.nome == 'A':\n while True:\n try:\n pontuacao = int(input(\"Digite o valor que deseja para o ás nessa carta (1 ou 11): \"))\n if pontuacao == 1 or pontuacao == 11:\n nova_carta.pontuacao = pontuacao\n break\n else:\n print(\"Valor inválido, por favor insira um valor entre 1 e 11!\")\n continue\n except:\n print(\"O valor inserido não foi númerico, por favor insira um valor numérico (1 ou 11)!\")\n continue\n elif nova_carta.nome == 'K' or nova_carta.nome == 'J' or nova_carta.nome == 'Q':\n nova_carta.pontuacao = 10\n else:\n nova_carta.pontuacao == int(nova_carta.nome)\n\n return nova_carta.pontuacao\n\nclass Mao(object):\n\n def __init__(self):\n self.pontuacao_da_mao = 0\n self.mao = []\n\n def primeira_jogada(self):\n carta1 = Baralho.tirar_carta()\n carta1.valor = calcular_valor_da_carta(carta1)\n self.mao.append(carta1)\n\n carta2 = Baralho.tirar_carta()\n carta2.valor = calcular_valor_da_carta(carta2)\n self.mao.append(carta2)\n\n def get_pontuacao_da_mao(self):\n for carta in mao:\n self.pontuacao_da_mao += carta.pontuacao\n \n return self.pontuacao_da_mao\n\n def proxima_carta(self, baralho):\n carta = Baralho.tirar_carta()\n carta.valor = calcular_valor_da_carta(carta)\n self.mao.append(carta)\n\n# Função responsável por checar se a pontuação da mão é um 21\n\ndef is_blackjack(jogador):\n return jogador.pontuacao_da_mao == 21\n\n# Função responsável por checar se a pontuação da mão é uma derrota ou não\n\ndef not_blackjack(jogador):\n return jogador.pontuacao_da_mao > 21\n\n# Função responsável por checar se a pontuação de uma mão é maior do que de outra\n\ndef jogador_vs_dealer(jogador, dealer):\n global announce\n if jogador.pontuacao_da_mao > dealer.pontuacao_da_mao:\n announce = \"Parabéns \" + jogador.nome + \", você venceu a mesa nesta rodada!\"\n jogador.set_saldo += jogador.get_apostas\n return True\n else:\n announce = \"Que pena \" + jogador.nome + \", você perdeu para a mesa nessa rodada\"\n jogador.set_saldo -= jogador.get_apostas\n return False\n\n# Função responsável por checar se ainda é possível jogar\n\ndef check_saldo(jogador):\n return jogador.saldo >= jogador.get_apostas\n\n\n# Função responsável por checar se quer continuar o jogo\n\ndef replay():\n resposta = ''\n while resposta != 's' or resposta != 'n' or resposta != ' ':\n print(\"Você deseja jogar outra rodada? Pressione 'Espaço' para encerrar o jogo\")\n resposta = input(\"[s|n|Espaço]: \")[0]\n\n return resposta\n\n\n# Função responsável pelo jogo\n\ndef game():\n\n print(\"Bem vindo à mesa de blackjack!\")\n nome_do_jogador = input(\"Primeiro sente-se confortavelmente e insira seu nome: \")\n saldo = int(input(\"Por favor, nos diga quanto dinheiro você tem disponível para jogar: \"))\n\n while True:\n \n apostas = int(input(\"Ótimo! Agora diga quanto gostaria de apostar nesta rodada: \"))\n jogador = Jogador(nome_do_jogador, apostas, saldo)\n dealer = Dealer()\n\n turno = random.choice([jogador, dealer])\n baralho = Baralho()\n baralho = baralho.embaralhar_cartas()\n\n print(\"Vamos lá!\")\n\n while True:\n if turno == jogador:\n jogador.primeira_jogada()\n\n while not is_blackjack or not_blackjack:\n \n fechar_mao = input(\"Deseja encerrar a jogada? 'n' para pedir a próxima carta \")\n if fechar_mao == 'n':\n break\n else:\n jogador.proxima_carta()\n","sub_path":"Blackjack-Python.py","file_name":"Blackjack-Python.py","file_ext":"py","file_size_in_byte":5770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"270399719","text":"#!/usr/bin/env python\n\n#GroupTaxon by Keith Yamada (19.1.2016)\n#Usage GroupTaxon.py INPUT.txt OUTPUT.txt\n\n# Takes Blast file with columns: query name, accession, subject name, taxonomy, hsp expect\n# Groups taxonomy information\n\n\nimport sys\n\nIN = open(sys.argv[1],'r')\nOUT = open(sys.argv[2],'w')\n\nIN.readline() #remove column headers\n\ngroups = {}\nlines = IN.readlines()\nfor line in lines:\n tax = line.split('\\t')[3]\n if groups.has_key(tax): # if taxon is already in the dictionary\n groups[tax] += 1 # increase value by 1\n else: # else taxon is not in the dictionary\n groups[tax] = 1 # add taxon to the dictionary\n\norder = sorted(groups.items(), key=lambda x:x[1], reverse=True)\nfor i in order:\n OUT.write(i[0]+'\\t'+str(i[1])+'\\n')\n\n\nOUT.close()\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n","sub_path":"Annotation/blastx2nr/scripts/GroupTaxon.py","file_name":"GroupTaxon.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"483425807","text":"import component\nimport course\nimport helpers\n\nPAGES_PATH=course.COURSE_PATH+\"/pages\"\nPAGE_PATH=PAGES_PATH+\"/{}\"\n\nclass Page(component.Component):\n\n def __init__(self, url=None, title=None, created_at=None, updated_at=None,\n body=None, published=None, front_page=None, todo_date=None,\n editing_roles=None, notify_of_update=None):\n component.Component.__init__(self, PAGES_PATH)\n self.url = url\n self.title = title\n self.published = published\n self.front_page = front_page\n self.todo_date = todo_date\n self.editing_roles = editing_roles\n self.notify_of_update = notify_of_update\n if body:\n self.body = helpers.md2html(body.strip())\n else:\n self.body = body\n\n def __iter__(self):\n fields = dict(super().__iter__())\n wrapped = {\"wiki_page\": fields}\n yield from wrapped.items()\n\n def __repr__(self):\n return f\"Page(title={self.title}, published={self.published})\"\n\n\n# Needed for custom yaml tag\ndef constructor(loader, node):\n return Page(**loader.construct_mapping(node))\n","sub_path":"py/page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"38309975","text":"import logging\nimport time\nfrom typing import Type\nimport pygame\nfrom ppb.abc import Engine, Scene\n\n\nclass GameEngine(Engine):\n\n def __init__(self, first_scene: Type, *, delta_time=0.016, resolution=(600, 400), flags=0, depth=0, log_level=logging.WARNING, **kwargs):\n super(GameEngine, self).__init__()\n\n # Engine Configuration\n self.delta_time = delta_time\n self.resolution = resolution\n self.flags = flags\n self.depth = depth\n self.log_level = log_level\n self.first_scene = first_scene\n logging.basicConfig(level=self.log_level)\n\n # Engine State\n self.scenes = []\n self.unused_time = 0\n self.last_tick = None\n self.running = False\n self.display = None\n\n def __enter__(self):\n logging.getLogger(self.__class__.__name__).info(\"Entering context.\")\n pygame.init()\n self.display = pygame.display.set_mode(self.resolution,\n self.flags,\n self.depth)\n self.update_input()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n logging.getLogger(self.__class__.__name__).info(\"Exiting context\")\n pygame.quit()\n\n def start(self):\n self.running = True\n self.last_tick = time.time()\n self.activate({\"scene_class\": self.first_scene})\n\n def manage_scene(self, scene_running, next_scene):\n if not scene_running:\n self.scenes.pop()\n if next_scene:\n self.activate(next_scene)\n\n def run(self):\n self.start()\n while self.running:\n time.sleep(.0000000001)\n scene = self.current_scene\n if scene is None:\n return\n self.manage_scene(*scene.change())\n pygame.display.update(list(scene.render()))\n tick = time.time()\n self.unused_time += tick - self.last_tick\n self.last_tick = tick\n while self.unused_time >= self.delta_time:\n for event in pygame.event.get():\n scene.handle_event(event)\n if event.type == pygame.QUIT:\n return\n self.update_input()\n scene.simulate(self.delta_time)\n self.unused_time -= self.delta_time\n\n @property\n def current_scene(self):\n try:\n return self.scenes[-1]\n except IndexError:\n return None\n\n def activate(self, next_scene: dict):\n scene = next_scene[\"scene_class\"]\n if scene is None:\n return\n args = next_scene.get(\"arguments\", [])\n kwargs = next_scene.get(\"keyword_arguments\", {})\n self.scenes.append(scene(self, *args, **kwargs))\n\n def update_input(self):\n self.mouse[\"x\"], self.mouse[\"y\"] = pygame.mouse.get_pos()\n self.mouse[1], self.mouse[2], self.mouse[3] = pygame.mouse.get_pressed()\n","sub_path":"ppb/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"653826747","text":"import logging\nfrom ..core import Menu\nfrom . import User\nfrom . import Group\nfrom . import Permission\nfrom . import Ldap\n\nclass Security(Menu):\n def __init__(self, scr):\n Menu.__init__(self, scr, \"Migrate Security\")\n self.log = logging.getLogger(__name__)\n self.log.debug(\"Initializing Security Menu.\")\n self.hasldap = None\n self.users = self.mkopt('u', \"Users Migration Setup\",\n [User(self.scr, self), self.refresh])\n self.groups = self.mkopt('g', \"Groups Migration Setup\",\n [Group(self.scr, self), self.refresh])\n self.perms = self.mkopt('p', \"Permissions Migration Setup\",\n [Permission(self.scr, self), self.refresh])\n self.opthead = [\n self.users,\n self.groups,\n self.perms]\n self.opttail = [\n None,\n self.mkopt('h', \"Help\", '?'),\n self.mkopt('q', \"Back\", None, hdoc=False)]\n self.ldapmenu = self.mkopt('l', \"LDAP Migration Setup\", None)\n self.ldapmenu['act'][0] = Ldap(self.scr, self.ldapmenu)\n self.opts = []\n self.log.debug(\"Security Menu initialized.\")\n\n def initialize(self):\n hasldap = self.scr.nexus.ldap.ldap != None\n self.ldapmenu['act'][0].updateparent()\n if self.hasldap == hasldap: return\n self.log.debug(\"Readying Security Menu for display (ldap=%s).\", hasldap)\n self.hasldap = hasldap\n self.opts = self.opthead[:]\n if self.hasldap: self.opts.append(self.ldapmenu)\n self.opts.extend(self.opttail)\n self.log.debug(\"Security Menu ready for display.\")\n\n def refresh(self, _=None):\n self.verify()\n self.scr.msg = None\n\n def applyconf(self, conf):\n if \"LDAP Migration Setup\" in conf:\n self.ldapmenu['act'][0].applyconf(conf[\"LDAP Migration Setup\"])\n del conf[\"LDAP Migration Setup\"]\n Menu.applyconf(self, conf)\n","sub_path":"nex2art/menu/Security.py","file_name":"Security.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"143489868","text":"import os\r\nfrom collections import defaultdict\r\nfrom prettytable import PrettyTable\r\nfrom typing import DefaultDict, Dict, Tuple, List, Iterator\r\nfrom HW08_Himanshu import file_reader\r\n\r\nclass Student:\r\n \"\"\" Store everything about a single student \"\"\"\r\n\r\n def __init__(self, cwid: str, name: str, major: str) -> None:\r\n \"\"\" store every info about a student \"\"\"\r\n self._cwid: str = cwid\r\n self._name: str = name\r\n self._major: str = major\r\n self._course: Dict[str, str] = dict()\r\n\r\n def store_course_grade(self, course: str, grade:str) -> None:\r\n \"\"\" store grade with respect to course student has taken \"\"\"\r\n if grade != '':\r\n self._course[course] = grade\r\n else:\r\n raise ValueError(\"Grade is empty !!!\")\r\n # print(self._course)\r\n\r\n def student_info(self) -> Tuple[str, str, List[str]]:\r\n \"\"\" return information needed for student pretty table \"\"\"\r\n return self._cwid, self._name, sorted(self._course.keys())\r\n\r\nclass Instructor:\r\n \"\"\"Store instructor inforamtion\"\"\"\r\n\r\n def __init__(self, cwid: str, name:str, major:str ) -> None:\r\n \"\"\" store every info about a instructor \"\"\"\r\n self._cwid: str = cwid\r\n self._name: str = name\r\n self._major: str = major\r\n # self._courses: DefaultDict[str, str] = defaultdict(int)\r\n self._courses: DefaultDict[str, int] = defaultdict(int)\r\n \r\n def store_course_students(self, course: str) -> None:\r\n \"\"\" counting how many students are in a particular course instructor is taking \"\"\"\r\n self._courses[course] += 1\r\n \r\n def instructor_info(self) -> Iterator[Tuple[str, str, str, str, int]]:\r\n \"\"\" return information needed for instructor pretty table \"\"\"\r\n # list_inst: list = list()\r\n for course, student_number in self._courses.items():\r\n # list_inst.append([self._cwid, self._name, self._major, course, student_number])\r\n yield self._cwid, self._name, self._major, course, student_number\r\n # return list_inst\r\n\r\nclass University:\r\n \"\"\" Repository to store students instructors for university and print pretty table \"\"\"\r\n\r\n def __init__(self, path: str)->None:\r\n \"\"\" store students, instructors and pretty table \"\"\"\r\n self._path = path\r\n self._students: Dict[str, Student] = dict()\r\n self._instructors: Dict[str, Instructor] = dict()\r\n self._read_students()\r\n self._read_instructors()\r\n self._read_grades()\r\n \r\n def _read_students(self) -> None:\r\n \"\"\" read student file and assigning values to dictionary \"\"\"\r\n try:\r\n directory: str = os.path.join(self._path, 'students.txt')\r\n except(FileNotFoundError) as e:\r\n print(e)\r\n else:\r\n for cwid, name, major in file_reader(directory, 3, sep = '\\t', header = False):\r\n self._students[cwid] = Student(cwid, name, major)\r\n # return self._students\r\n # print(self._students)\r\n \r\n def _read_instructors(self) -> None:\r\n \"\"\" read instructor file and assigning values to dictionary \"\"\"\r\n try:\r\n directory: str = os.path.join(self._path, 'instructors.txt')\r\n except(FileNotFoundError) as e:\r\n print(e)\r\n else:\r\n for cwid, name, major in file_reader(directory, 3, sep = '\\t', header = False):\r\n self._instructors[cwid] = Instructor(cwid, name, major)\r\n # print(self._instructors)\r\n # return self._instructors\r\n\r\n def _read_grades(self) -> None:\r\n \"\"\" read grades file and assigning values to dictionary \"\"\"\r\n try:\r\n directory: str = os.path.join(self._path, 'grades.txt')\r\n except(FileNotFoundError) as e:\r\n print(e)\r\n else:\r\n for student_cwid, course, grade, instructor_cwid in file_reader(directory, 4, sep = '\\t', header = False):\r\n if student_cwid in self._students.keys():\r\n self._students[student_cwid].store_course_grade(course, grade)\r\n # return grade\r\n else:\r\n raise ValueError(f\"student with id: {student_cwid} is not matched with any data\")\r\n\r\n if instructor_cwid in self._instructors.keys():\r\n self._instructors[instructor_cwid].store_course_students(course)\r\n # return self._instructors\r\n else:\r\n raise ValueError(f\"professor with id: {instructor_cwid} is not matched with any data\")\r\n\r\n def student_prettytable(self):\r\n \"\"\"Sends the student data to the pretty table and prints it\"\"\"\r\n pretty_table1: PrettyTable = PrettyTable(field_names=['CWID', 'Name', 'Completed Courses'])\r\n for student in self._students.values(): \r\n pretty_table1.add_row(student.student_info())\r\n print(pretty_table1)\r\n \r\n def instructor_prettytable(self):\r\n \"\"\"Sends the instructors data to the pretty table and prints it\"\"\"\r\n pretty_table2: PrettyTable = PrettyTable(field_names=['CWID', 'Name', 'Dept', 'Course', 'Students'])\r\n for instructor in self._instructors.keys():\r\n for c in self._instructors[instructor].instructor_info():\r\n pretty_table2.add_row(c)\r\n print(pretty_table2)\r\n \r\n \r\n# def main():\r\n# \"\"\" define the repositiry \"\"\"\r\n# stevens: University = University(\"C:\\\\Users\\\\Himan\\\\Desktop\\\\Semester 2\\\\SSW 810\\\\HW\\\\Assignment\")\r\n# # nyu: University = University(\"put the path in here\").\r\n# stevens.student_prettytable()\r\n# stevens.instructor_prettytable()\r\n\r\n# if __name__ == \"__main__\":\r\n# main()\r\n","sub_path":"HW09_Himanshu.py","file_name":"HW09_Himanshu.py","file_ext":"py","file_size_in_byte":6040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"44711678","text":"import unittest\n\nfrom src.Constants.FileLocationConstants import FolderLocationConstants\nfrom src.Data.FileManager import FileManager\n\n\nclass TestFileManager(unittest.TestCase):\n\n\n def test_createNewFolder(self):\n folderLocation = FolderLocationConstants()\n fileManager = FileManager()\n retVal = fileManager.create_folder(folderLocation.get_temp_folder())\n self.assertEqual(retVal, 1)\n\n def test_removeNewFolder(self):\n folderLocation = FolderLocationConstants()\n fileManager = FileManager()\n retVal = fileManager.delete_folder(folderLocation.get_temp_folder())\n self.assertEqual(retVal, 1)\n\n # def test_deleteFolder(self):\n\n\n\n\n\n\nexistFolder = unittest.TestSuite()\nexistFolder.addTest(TestFileManager('test_createNewFolder'))\nexistFolder.addTest(TestFileManager('test_removeNewFolder'))\n\n\nrunner = unittest.TextTestRunner()\nrunner.run(existFolder)\n\n","sub_path":"src/UnitTests/Test_FileManager.py","file_name":"Test_FileManager.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"439165652","text":"\nfrom os.path import join\nimport logging\n\nfrom src.settings import types\nfrom src.utils import click_utils\n\n# -----------------------------------------------------------------------------\n# Enun lists used for custom Click Params\n# -----------------------------------------------------------------------------\n\nLogLevelVar = click_utils.ParamVar(types.LogLevel)\n\n# # data_store\nDATA_STORE_WORKSHOP = 'data_store_workshop'\nDIR_MODELS = join(DATA_STORE_WORKSHOP,'models')\n# Frameworks\nDIR_MODELS_CAFFE = join(DIR_MODELS,'caffe')\n\n# -----------------------------------------------------------------------------\n# click chair settings\n# -----------------------------------------------------------------------------\nDIR_COMMANDS_WORKSHOP = 'commands/workshop'\n\n# -----------------------------------------------------------------------------\n# Logging options exposed for custom click Params\n# -----------------------------------------------------------------------------\nLOGGER_NAME = 'vframe'\nLOGLEVELS = {\n types.LogLevel.DEBUG: logging.DEBUG,\n types.LogLevel.INFO: logging.INFO,\n types.LogLevel.WARN: logging.WARN,\n types.LogLevel.ERROR: logging.ERROR,\n types.LogLevel.CRITICAL: logging.CRITICAL\n}\nLOGLEVEL_OPT_DEFAULT = types.LogLevel.DEBUG.name\n\nLOGFILE_FORMAT = \"%(log_color)s%(levelname)-8s%(reset)s %(cyan)s%(filename)s:%(lineno)s:%(bold_cyan)s%(funcName)s() %(reset)s%(message)s\"\n\n","sub_path":"vframe/src/settings/app_cfg.py","file_name":"app_cfg.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"240145966","text":"import platform\nimport os\nif platform.system() == 'Darwin':\n PLATFORM = 'osx'\nelse:\n PLATFORM = 'win'\n\ndef createSql():\n movie_list_path = os.path.join(os.getcwd(), 'movie_list.txt')\n\n with open('movie.sql', 'w') as f:\n f.write('''use movee; LOAD DATA LOCAL INFILE '{}' INTO TABLE movie_movie\n Fields TERMINATED BY ';' LINES TERMINATED BY '\\\\n' (name, mtime, size, path);'''.format(movie_list_path))\n\nif __name__ == '__main__':\n createSql()","sub_path":"movie/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"344109077","text":"#assessors for challenges\nfrom challenge.models import *\nfrom django.contrib.auth.models import User\n#this shouldn't be here\nfrom csuf_user.models import CSUF_UserProfile as Profile\n\n\ndef all_complete(challenge_sub):\n complete = True\n for problem_sub in challenge_sub.problem_submission_set.all():\n if problem_sub.status == 'incorrect' or problem_sub.status == 'inactive':\n complete = False\n \n #if it's done and not already finished before\n if complete and challenge_sub.verdict != 'complete':\n challenge_sub.verdict = 'complete'\n user = challenge_sub.user\n p = Profile.objects.get(user=user)\n p.hacker_score += challenge_sub.challenge.reward\n p.save()\n #user.profile.hacker_score += challenge_sub.challenge.reward\n challenge_sub.save()\n \n","sub_path":"Hacker_Board/challenge/assessors.py","file_name":"assessors.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"109836317","text":"from flask import render_template, flash, redirect, session, url_for, request, g, abort\nfrom flask.ext.login import login_user, logout_user, current_user, login_required\nfrom app import app, db, lm\nfrom .forms import LoginForm, RegisterForm, WalletForm\nfrom .models import User, Wallet, WContents\n\n\n@lm.user_loader\ndef load_user(id):\n return User.query.get(int(id))\n\n@app.before_request\ndef before_request():\n g.user = current_user\n \n@app.route('/')\n@app.route('/home')\ndef home():\n return render_template('index.html',\n title='Home')\n\n@app.route('/get_started')\ndef get_started():\n return render_template('get_started.html',\n title='Get Started')\n\n@app.route('/about')\ndef about():\n return render_template('about_us.html',\n title='About')\n\n@app.route('/register' , methods=['GET','POST'])\ndef register():\n form = RegisterForm()\n if request.method == 'GET':\n return render_template('register.html',\n title='Sign Up',\n form=form)\n user = User(username=form.username.data,\n password=form.password.data,\n email=form.email.data)\n db.session.add(user)\n db.session.commit()\n return redirect(url_for('login'))\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n #if g.user is not None and g.user.is_authenticated:\n # return redirect(url_for('home'))\n \n form = LoginForm()\n\n if request.method == 'GET':\n return render_template('login.html',\n title='Sign In',\n form=form)\n \n if form.validate_on_submit():\n\n session['remember_me'] = form.remember_me.data\n user = User.query.filter_by(username=form.username.data).first()\n \n if user is None:\n return redirect(url_for('register'))\n \n login_user(user)\n\n return redirect('/myhome')\n\n@app.route(\"/logout\")\n@login_required\ndef logout():\n logout_user()\n return redirect('/home')\n\n@app.route('/myhome')\n@login_required\ndef user():\n user = g.user\n wallets = Wallet.query.filter_by(user_id=user.userid).all()\n\n if type(wallets) != list:\n wids = [wallets.wallet_id]\n else:\n wids = [wallet.wallet_id for wallet in wallets]\n\n if len(wids) < 1:\n trade = False\n else:\n trade = True\n \n wcontents = WContents.query.filter(WContents.wallet_id.in_(wids))\n \n return render_template('user.html',\n wallets=wallets,\n wcontents=wcontents,\n trade=trade,\n title='My Home',\n user=user)\n\n@app.route('/trade')\n@login_required\ndef trade():\n user = g.user\n wallets = Wallet.query.filter_by(user_id=user.userid).all()\n\n if type(wallets) != list:\n wallets = [wallets]\n \n return render_template('trade.html',\n wallets=wallets)\n\n@app.route('/create_wallet' , methods=['GET','POST'])\n@login_required\ndef createwallet():\n form = WalletForm()\n userid = g.user.userid\n if request.method == 'GET':\n return render_template('createwallet.html',\n title='Create Wallet',\n form=form)\n wallet = Wallet(user_id=userid,\n nickname=form.nickname.data)\n db.session.add(wallet)\n db.session.commit()\n return redirect('/myhome')\n\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"168315549","text":"__author__ = 'Max'\nfrom log2report.DatasetLoader import DatasetLoader2\nimport xlrd\n\ndef download_roi_data():\n loader=DatasetLoader2(\"data\",False)\n\n loader.download(\"ProjectsAndTags.xlsx\",\"0Ao993IR9m-38dFpiZmpqbkhxUnNZNHBFSTVDa3NFMnc\")\n loader.download(\"roi/ROI_AccountingData.xlsx\",\"0Ao993IR9m-38dEpXSUU3cDlCdnZpRnlDUjZybllpb0E\")\n\n\ndownload_roi_data()","sub_path":"roi_download.py","file_name":"roi_download.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"215923593","text":"\"\"\"\nThe Structure of our game\n1.First of all, we created 5 digits from the bottom up and right to the left where our game will be played (we did this with 0 numbers).\n2.we then placed our ship in a random place using functions and modules.\n3.We asked the user to have two predictions, from right to left and from top to bottom.\n4.For this, we gave only 4 chances by specifying the range (4).\n5.Whether the prediction will be the same as where the computer is positioning the ship.\n6.we wrote our functions controlling it, and accordingly we printed our inputs and prints.\n7.After trying 4 rights we finished with the game over.\n\n\"\"\"\nfrom random import randint#It means that I will only use randint from the random module.\n\nfrom board import * #we created a board module ourselves and transferred all the functions inside it with '*'.\n\n# defining where the ship is\ndef random_row(board):#Here he chooses a layout from top to bottom.\n return randint(0, len(board) - 1)\n\ndef random_col(board):#Here he chooses a layout from left to right.\n return randint(0, len(board[0]) - 1)\n\nship_row = random_row(board)\nship_col = random_col(board)\n\n# asking the user for a guess\nfor turn in range(4):#For this, we gave only 4 chances by specifying the range (4).\n guess_row = int(input(\"Guess Row:\"))\n guess_col = int(input(\"Guess Col:\"))\n\n # if the user's right, the game ends\n if guess_row == ship_row and guess_col == ship_col:\n print(\"Congratulations! You sunk my battleship!\")\n break\n else:\n # warning if the guess is out of the board\n if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):\n print(\"Oops, that's not even in the ocean.\")\n\n # warning if the guess was already made\n elif (board[guess_row][guess_col] == \"X\"):\n print(\"You guessed that one already.\")\n\n # if the guess is wrong, mark the point with an X and start again\n else:\n print(\"You missed my battleship!\")\n board[guess_row][guess_col] = \"X\"\n\n # Print turn and board again here\n print(\"Turn \" + str(turn + 1) + \" out of 4.\")\n print_board(board)\n\n# if the user have made 4 tries, it's game over\nif turn >= 3:\n print(\"Game Over\")","sub_path":"question5.py","file_name":"question5.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"188331017","text":"__author__ = 'Einsiedler'\n\nimport platform\nimport pickle\nimport tornado.httpclient\n\nfrom xml.dom.minidom import parseString\n#from src.native.Client import Client as GeoClient\nfrom src.mock.ServerProxyBase import ServerProxyBase\nfrom src.mock.ServerProxyWin import ServerProxyWin\nfrom src.utils.ResponseDecoder import ResponseDecoder\n\nfrom src.mock.server.configuration import MockConfiguration\nfrom src.mock.server.webservicehandlers import LicenseService\nfrom src.mock.server.databaseaccessor import DatabaseAccessor\nfrom src.mock.server.defaults import Config\n\nimport time\nimport tempfile\nfrom robot.api import logger\n\nimport sys\nreload(sys)\nsys.setdefaultencoding(\"ISO-8859-1\")\n\n\nclass ServerProxy(object):\n \"\"\"This class is a cross-platform implementation of the simulator for GeoComply Web-Services.\n\n Notes:\n To enable extended logs of the simulator you should put to the ./log folder a file with a name\n 'ServerSimulatorApp.log', to disable that - just remove a corresponding log file.\n\n Attributes:\n server_impl (object): the platform specific instance of the simulator.\n \"\"\"\n\n def __init__(self):\n super(ServerProxy, self).__init__()\n if platform.system() == \"Darwin\":\n self.server_impl = ServerProxyBase()\n elif platform.system() == \"Windows\":\n self.server_impl = ServerProxyWin()\n\n def initialize(self, xml_path=None):\n \"\"\" This method is used for cleaning up overall logs from the previous session and initializing of a concrete\n platform specific implementation of the simulation local Http/Https-server. It produces a separate child\n process for a running of the server.\n\n Args:\n xml_path (str): If this parameter is set to not None, this method tries to load a configuration of the server\n from the XML-file; by default it uses a set of values for the configuration that is set up in the code.\n\n Returns:\n None\n \"\"\"\n temp_file_dump = tempfile.NamedTemporaryFile(delete=False, mode='wb')\n Config.serialize(temp_file_dump)\n defaults_file_name = temp_file_dump.name\n temp_file_dump.close()\n\n if platform.system() == \"Darwin\":\n self.server_impl = ServerProxyBase()\n elif platform.system() == \"Windows\":\n self.server_impl = ServerProxyWin()\n\n self.clear_remote_logs()\n self.server_impl.initialize(xml_path, defaults_file=defaults_file_name)\n\n return self.get_status()\n\n def shutdown(self):\n \"\"\" This method is used for shutting down of the server after calling to this method the Http/Https-server is\n not available at the local device. The corresponding process should be stopped and unloaded from the system.\n\n Returns:\n None\n \"\"\"\n if self.server_impl:\n self.server_impl.shutdown()\n self.server_impl = None\n\n def get_status(self):\n http_client_dummy = tornado.httpclient.HTTPClient()\n\n attempts = 3\n while 0 < attempts:\n try:\n url = \"http://%s:%s/%s\" % (Config.HOST_ADDRESS, Config.HOST_PORT, Config.CMD_HTTP_SERVICE)\n resp = http_client_dummy.fetch(tornado.httpclient.HTTPRequest(url, method='GET'))\n http_client_dummy.close()\n return True\n except tornado.httpclient.HTTPError as e:\n logger.info(\"The mock server has a status code=%s.\" % e.code)\n except Exception as unexpected:\n logger.info(unexpected.message.replace('[', '-').replace(']', '-'))\n\n time.sleep(1)\n attempts -= 1\n\n http_client_dummy.close()\n return False\n\n def get_port(self):\n \"\"\" This method is a getter for the port number on which the server's process starts the Http/Https-server.\n\n Returns:\n The port number as an integer value.\n \"\"\"\n return self.server_impl.get_port()\n\n def get_license(self):\n \"\"\" This method is a getter for the pre-configured license string. You can control a content of this license\n by changing a corresponding configuration section of the simulator.\n\n Returns:\n The license string.\n \"\"\"\n return self.server_impl.get_license()\n\n def add_default_stage_for(self, config_name):\n \"\"\" This method adds an additional stage to the default behavior of the simulator. The supported values for\n a configuration name are next:\n \"license\" - to add a stage for the License service behavior;\n \"configuration\" - to add a stage for the Configuration service behavior;\n \"engine\" - to add a stage for the GeoEngine service behavior;\n \"trueip\" - to add a stage for the TrueIp service behavior;\n \"wifigsm\" - to add a stage for the GeoLocation service behavior;\n \"logging\" - to add a stage for the Remote logging service behavior.\n\n Args:\n config_name (str): the one of predefined values for identifying of the service type.\n\n Returns:\n The index of newly created configuration stage.\n \"\"\"\n return self.server_impl.add_default_stage_for(config_name)\n\n def set_value_for(self, config_name, parameter, value, stage_index=0):\n \"\"\" This method allows to set a value for any parameter of an existing stage of a service's behavior.\n\n Args:\n config_name (str): the one of predefined values for identifying of the service type;\n parameter (str): the name of a parameter to be reset to the new value;\n value (str,boolean, integer): the value for a parameter to be set;\n stage_index (integer): the index for a configuration in a behavior internally.\n\n Returns:\n True if succeed; otherwise False.\n \"\"\"\n return self.server_impl.set_value_for(config_name, parameter, value, stage_index)\n\n def reset_to_default(self):\n \"\"\" This method reset an overall configuration of the simulator to the default one.\n\n Notes:\n This method has an effect if you call it before initialize of the simulator or you must call to initialize()\n method once again to apply a default configuration.\n\n Returns:\n None\n \"\"\"\n self.server_impl.reset_to_default()\n\n @staticmethod\n def get_request_by_id(request_id):\n \"\"\" This method allows to get the GeoRequest using a corresponding transaction identifier that can be gotten\n from the GeoResponse.\n\n Args:\n request_id (str): the identifier of the GeoResponse.\n\n Returns:\n The raw GeoPacket for the corresponding GeoResponse identifier.\n \"\"\"\n db = DatabaseAccessor()\n raw_data = db.query_geo_trans(request_id)\n return raw_data['geo_request']\n\n @staticmethod\n def get_transmission_by_id(request_id, clear_logs=False):\n \"\"\" This method allows to get an overall transmission including internal services requests/responses as\n a dictionary.\n\n Notes:\n If you call to this method with a request_id=None, you will get an overall transmission anyway. It allows to\n get an overall transmission independently of whether the GeoResponse was gotten or not.\n\n Args:\n request_id (str): the identifier of the GeoResponse.\n clear_logs (Boolean): instructs whether the logs has to be cleared afterwards.\n\n Returns:\n The dictionary with an overall transmission. Its structure is declared below:\n {'transaction_id': 'TRANSACTION_IDENTIFIER',\n 'services_transmission': 'HEX_ENCODED_TRANSMISSION_DATA',\n 'geo_response': 'GEO_RESPONSE_ENCODED',\n 'geo_request': 'GEO_REQUEST_ENCODED',\n 'aes_key': 'AES_KEY',\n 'aes_iv': 'AES_IV'\n }\n \"\"\"\n if request_id is None:\n http_client_dummy = tornado.httpclient.HTTPClient()\n try:\n http_client_dummy.fetch(tornado.httpclient.HTTPRequest(\"http://%s:%s/%s\" %\n (Config.HOST_ADDRESS,\n Config.HOST_PORT,\n Config.CMD_SYNC_TRANSACTIONS),\n method=\"GET\"))\n except Exception:\n # There is no need in handling a such exception as an error of the mock server run.\n pass\n http_client_dummy.close()\n\n db = DatabaseAccessor()\n raw_data = db.query_geo_trans(Config.NON_TRANSACTION_ID)\n\n if clear_logs:\n db.remove_transaction_data(Config.NON_TRANSACTION_ID)\n if raw_data:\n return pickle.loads(raw_data[Config.DB_COL_SERVICES_TRANSMISSION].decode('hex'))\n else:\n def_dict = {'transaction_id': '',\n 'services_transmission': '',\n 'geo_response': '',\n 'geo_request': '',\n 'aes_key': '',\n 'aes_iv': ''}\n return def_dict\n else:\n db = DatabaseAccessor()\n raw_data = db.query_geo_trans(request_id)\n return pickle.loads(raw_data[Config.DB_COL_SERVICES_TRANSMISSION].decode('hex'))\n\n @staticmethod\n def get_last_remote_logs():\n \"\"\" This methods allows to get all logs that was sent to the Remote Logging server in case of errors to be\n logged. These logs can be sent in case the 'enable_extended_log' parameter is set to '1'.\n\n Returns:\n The array of remote logs.\n \"\"\"\n result = \"\"\n errors = DatabaseAccessor().query_engine_err()\n for item in errors:\n result += item['engine_err'].decode('hex')\n return result\n\n @staticmethod\n def clear_remote_logs():\n \"\"\" This method clears a cache with remote logs collected.\n\n Returns:\n None\n \"\"\"\n DatabaseAccessor().remove_engine_err()\n\n\nif __name__ == '__main__':\n from src.utils.Utilities import Utilities\n #Utilities.set_logs_for(\"client\", \"ON\")\n\n mock_server = ServerProxy()\n\n MockConfiguration.instance().initialize()\n\n mock_server.clear_remote_logs()\n\n # result = config.set_value_for(\"license\", \"response.timeout\", 20, 0)\n # print MockConfiguration.instance().license\n\n stage_one = 0\n\n # MockConfiguration.instance().set_value_for(\"configuration\", \"response.settings.retransmission_attempts_count\", 4,\n # stage_one)\n # MockConfiguration.instance().set_value_for(\"engine\", \"response_delay\", -1, stage_one)\n # MockConfiguration.instance().set_value_for(\"configuration\", \"response.settings.engine_timeout\", 10, stage_one)\n # MockConfiguration.instance().set_value_for(\"engine\", \"response.error_code\", 5, stage_one)\n # ############################\n # MockConfiguration.instance().set_value_for(\"configuration\", \"response.settings.wifi_realm\", \"\",\n # stage_one)\n # MockConfiguration.instance().set_value_for(\"configuration\", \"response.settings.wifi_username\", \"\",\n # stage_one)\n # MockConfiguration.instance().set_value_for(\"configuration\", \"response.settings.geolocation_methods\", \"S\",\n # stage_one)\n # MockConfiguration.instance().set_value_for(\"configuration\", \"response.settings.geolocation_sh_access\", \"\",\n # stage_one)\n\n\n MockConfiguration.instance().set_value_for(\"configuration\", \"response.settings.geolocation_methods\", \"G\",\n stage_one)\n MockConfiguration.instance().set_value_for(\"engine\", \"response.error_code\", 0, stage_one)\n\n stage_two = MockConfiguration.instance().add_default_stage_for(\"configuration\")\n MockConfiguration.instance().set_value_for(\"configuration\", \"response.settings.geolocation_methods\", \"S\",\n stage_two)\n stage_three = MockConfiguration.instance().add_default_stage_for(\"configuration\")\n MockConfiguration.instance().set_value_for(\"configuration\", \"response.settings.geolocation_methods\", \"S\",\n stage_three)\n\n stage_e_two = MockConfiguration.instance().add_default_stage_for(\"engine\")\n MockConfiguration.instance().set_value_for(\"engine\", \"response.error_code\", 14,\n stage_e_two)\n stage_e_three = MockConfiguration.instance().add_default_stage_for(\"engine\")\n MockConfiguration.instance().set_value_for(\"engine\", \"response.error_code\", 0,\n stage_e_three)\n\n mock_server.initialize()\n\n mock_server.get_status()\n '''\n # =========================\n\n # mock_server.shutdown()\n\n xml_response = LicenseService.instance().get_response().msg\n dom = parseString(xml_response.encode('utf8'))\n license_string = dom.getElementsByTagName('license')[0].firstChild.nodeValue\n # print license_string\n gc = GeoClient()\n\n gc.initialize(Utilities.get_native_library_path())\n gc.set_license(license_string)\n gc.request_geolocation()\n\n rc = gc.wait_for_events()\n\n gc.shutdown()\n gc = None\n\n decoded_data = None\n if rc['Data']:\n decoded_data = ResponseDecoder().decode(rc['Data'])\n print \"RESP:\", decoded_data\n else:\n print rc\n\n from lxml import etree\n\n transaction_id = None\n if decoded_data:\n resp_dom = etree.fromstring(decoded_data)\n transaction_id = resp_dom.xpath('//gc_transaction')[0].text\n print transaction_id\n #from src.utils.Utilities import Utilities\n #import os\n #print Utilities.get_process_memory_usage(os.getpid())\n trans = mock_server.get_transmission_by_id(transaction_id, clear_logs=False)\n print \"Transmission ID: %s\" % trans\n\n print \"First Attempt to read:\"\n for item in trans:\n #print item\n if item['service'] == 'engine':\n encrypted_data = item['request']['body']\n plain_data = ResponseDecoder().decode_internal(encrypted_data)\n try:\n xml_tree = etree.fromstring(plain_data)\n print \"MacAddr: %s\" % xml_tree.xpath('//data//mac//text()')\n except Exception as excp:\n print excp.message\n\n mock_server.shutdown()\n\n # print \"Overall logs data is : \\n\", Utilities.get_overall_logs_data(\"client\")\n # Utilities.set_logs_for(\"client\", \"OFF\")\n #\n # print mock_server.get_last_remote_logs()\n '''","sub_path":"src/mock/ServerProxy.py","file_name":"ServerProxy.py","file_ext":"py","file_size_in_byte":14923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"602632792","text":"class Solution:\n def findNthDigit(self, n: int) -> int:\n n -= 1\n for digit in range(1, 12):\n first_num = pow(10, digit-1)\n\n if n < 9 * first_num * digit:\n return int(str(first_num + n // digit)[n % digit])\n n -= 9 * first_num * digit\n return 0\n\n\ndef test(test_name, n, expected):\n res = Solution().findNthDigit(n)\n if res == expected:\n print(test_name + ' success.')\n else:\n print(test_name + ' failed.')\n\nif __name__ == \"__main__\":\n n1 = 3\n expected1 = 3\n test(\"test1\", n1, expected1)\n\n n2 = 11\n expected2 = 0\n test(\"test2\", n2, expected2)\n\n n3 = 365\n expected3 = 5\n test(\"test3\", n3, expected3)\n\n# 数字以0123456789101112131415…的格式序列化到一个字符序列中。\n# 在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。\n\n# 请写一个函数,求任意第n位对应的数字。\n\n# 示例 1:\n# 输入:n = 3\n# 输出:3\n\n# 示例 2:\n# 输入:n = 11\n# 输出:0\n\n# 限制:\n# 0 <= n < 2^31\n","sub_path":"of44_数字序列中某一位的数字/Solution1.py","file_name":"Solution1.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"372672182","text":"import sys\nfrom PyQt4 import QtGui, QtCore\nfrom datetime import date\n\nclass Window(QtGui.QWidget):\n\n def __init__(self):\n super().__init__()\n self.btn= self.crea_boton(\"Apríetame\")\n self.setWindowIcon(QtGui.QIcon('Flag_of_Mexico.png'))\n self.ajusta_tamano()\n self.etq= self.crea_etiqueta()\n self.btn2= self.crea_quit('Quit')\n\n def crea_boton(self, mensaje):\n self.btn= QtGui.QPushButton(mensaje, self)\n self.btn.move(100, 100)\n self.btn.clicked.connect(self.on_clicked_button)\n\n def crea_quit(self, mensaje):\n self.btn2= QtGui.QPushButton(mensaje, self)\n self.btn2.move(200, 100)\n self.btn2.clicked.connect(QtCore.QCoreApplication.instance().quit)\n\n def on_clicked_button(self):\n dias= obten_dias()\n print('Faltan '+dias+' para la independencia')\n\n def ajusta_tamano(self):\n self.resize(300, 200)\n\n def crea_etiqueta(self):\n label=\"\"\"\n Miguel Hidalgo\n Josefa Ortiz de Domínguez\n Juan Aldama\n \"\"\"\n self.etq= QtGui.QLabel(self)\n self.etq.setText(label)\n self.etq.move(20, 20)\n\ndef obten_dias():\n hoy= date.today()\n independencia= date(hoy.year, 9, 15)\n dias= (independencia - hoy).days\n if dias < 0:\n independencia= date(hoy.year+1, 9, 15)\n dias= (independencia-hoy).days\n return str(dias)\n\ndef main():\n app= QtGui.QApplication(sys.argv)\n window= Window()\n window.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()\n","sub_path":"VivaMexico.py","file_name":"VivaMexico.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"95505996","text":"# python setup.py sdist bdist_wheel\n#twine upload dist/*\n\nfrom setuptools import setup, find_packages\nimport os\nwith open('src/DeepMatter/requirements.txt') as f:\n requirements = f.read().splitlines()\n\nsetup(\n name='DeepMatter',\n version='0.0.59',\n packages=find_packages(where=\"src\"),\n url='https://github.com/m3-learning/DeepMatter.git',\n install_requires=requirements,\n license=' BSD-3-Clause',\n author='Joshua C. Agar, Shuyu Qin',\n author_email='jca318@lehigh.edu, shq219@lehigh.edu',\n description='Tool for machine learning in materials Science',\n classifiers = [\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: OS Independent\",\n ],\n package_dir = {\"\": \"src\"},\n python_requires = \">=3.6\",\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"28182047","text":"'''\n File: basics-functions.py\n Source: stackskills.com\n Author: troys\n Date: March 31st, 2016\n'''\n\n# Declare a functions\ndef example():\n x = 1\n y = 3\n print(x+y)\n\n# Execute the function\nexample()\n\n# Declare an addition function\ndef addition(num1,num2,num3,num4):\n answer = num1+num2+num3+num4\n return answer\n\nx=addition(5,6,6,5)\nprint(x)\n\n# A more elaborate example\ndef website(font='TNR',\n background_color='white',\n font_size=11,\n font_color='black'):\n print('font',font)\n print('bg:',background_color)\n print('Font size:',font_size)\n print('Font color:',font_color)\n\nwebsite('Courier','red','20','cyan')\nwebsite()\n\n\n\n","sub_path":"basics-functions.py","file_name":"basics-functions.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"50117246","text":"import secrets\nfrom zoopla import Zoopla\n\nzoopla = Zoopla(api_key=secrets.key)\n\nsearch = zoopla.property_listings({\n 'minimum_beds': 2,\n 'minimum_price': 800,\n #'page_size': 100,\n 'listing_status': 'rent',\n 'area': 'Oxford'\n})\n\nfor result in search.listing:\n print(result.price)\n print(result.description)\n print(result.image_url)\n #print(result.longitude)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"124754339","text":"class Solution(object):\n def maximumGap(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # use bucket-sort\n if len(nums) < 2: return 0\n # use 5 buckets\n minE = min(nums)\n maxE = max(nums)\n n = len(nums)\n buckets = [[] for _ in xrange(n)] # buckets[min,max]\n delta = max(1, (maxE - minE)/n) # at least delta is 1; Why not arbitrary # of buckets? precision of divide?\n for num in nums:\n bid = min((num-minE)/delta, n-1) # should set an upper-bound for bid as n-1\n if not buckets[bid]:\n buckets[bid] = [num, num]\n elif num > buckets[bid][1]:\n buckets[bid][1] = num\n elif num < buckets[bid][0]:\n buckets[bid][0] = num\n buckets = filter(lambda x: len(x), buckets)\n maxGap = buckets[0][1]- buckets[0][0]\n last = 0\n for i in xrange(1, len(buckets)):\n maxGap = max(maxGap, buckets[i][0]-buckets[i-1][1]) # min[i] - max[i-1]\n return maxGap","sub_path":"164_maximum_gap/prac4.py","file_name":"prac4.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"153764148","text":"import os\nimport time\nimport argparse\nimport pandas as pd\n\n\ndef reFilterData(filter_conf, doc_topics):\n start_time = time.time()\n for index, row in filter_conf.iterrows():\n topic_name = row[\"topic_name\"]\n threshold = row[\"threshold\"]\n keep_or_delete = row[\"keep\"]\n if keep_or_delete == 1: # keep\n doc_topics = doc_topics[doc_topics[topic_name] >= threshold]\n else: # delete\n doc_topics = doc_topics[~(doc_topics[topic_name] >= threshold)]\n\n end_time = time.time()\n print(\"filtered in {} seconds\"\n .format(end_time - start_time))\n\n return doc_topics[\"docID\"].tolist()\n\n\ndef parseParameters():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--input_data_dir',\n type=str,\n default='./Data_in',\n help='Directory to put the input data.'\n )\n parser.add_argument(\n '--output_data_dir',\n type=str,\n default='./Data_out',\n help='Directory to put the log data.'\n )\n parser.add_argument(\n '--year',\n type=int,\n default=2008,\n help='year of data.'\n )\n\n return parser.parse_known_args()\n\nif __name__ == \"__main__\":\n FLAGS, unparsed = parseParameters()\n input_dir = FLAGS.input_data_dir\n output_dir = FLAGS.output_data_dir\n year = FLAGS.year\n\n already_deleted_file = \"{}/deleted_docID_{}.csv\".format(input_dir, year)\n posts_bak_file = \"{}/Posts_old_{}.csv\".format(input_dir, year)\n deleted_posts_file = \"{}/Posts_deleted_{}.csv\".format(input_dir, year)\n posts_file = \"{}/Posts_{}.csv\".format(input_dir, year)\n doc_topics_file = \"{}/stackoverflow_topic_coverage_{}.csv\".format(output_dir, year)\n filter_conf_file = \"{}/topic_filter_conf_{}.csv\".format(output_dir, year)\n\n df_filter_conf = pd.read_csv(filter_conf_file, sep=',', encoding=\"utf-8\")\n df_doc_topics = pd.read_csv(doc_topics_file, sep=',', encoding=\"utf-8\")\n keepDocIDs = reFilterData(df_filter_conf, df_doc_topics)\n print(\"filtered, doc_topics {}, keep {}\".format(df_doc_topics.shape[0], len(keepDocIDs)))\n\n df_year = pd.read_csv(posts_file, sep=',', encoding=\"utf-8\")\n # backup the old file\n try:\n os.replace(posts_file, posts_bak_file)\n except Exception as e:\n print(e)\n df_year.to_csv(posts_bak_file, sep=',', encoding=\"utf-8\", index=False)\n\n df_year_left = df_year[df_year[\"docID\"].isin(keepDocIDs)]\n df_year_left.to_csv(posts_file, sep=',', encoding=\"utf-8\", index=False)\n print(\"filtered, before {}, after {}\".format(df_year.shape[0], df_year_left.shape[0]))\n del df_year_left\n\n df_deleted_already = pd.DataFrame(columns=[\"docID\"])\n if os.path.isfile(already_deleted_file):\n df_deleted_already = pd.read_csv(already_deleted_file, sep=',', encoding=\"utf-8\")\n\n df_year_deleted = df_year[~(df_year[\"docID\"].isin(keepDocIDs))]\n if df_year_deleted.shape[0] > 0:\n df_year_deleted.to_csv(deleted_posts_file, sep=',', encoding=\"utf-8\", index=False)\n print(\"deleted {}\".format(df_year_deleted.shape[0]))\n concat_df = [df_deleted_already, df_year_deleted]\n df_deleted_already = df_deleted_already.append(pd.DataFrame(df_year_deleted[\"docID\"], columns=[\"docID\"]))\n df_deleted_already = df_deleted_already.drop_duplicates([\"docID\"])\n df_deleted_already.to_csv(already_deleted_file, sep=',', encoding=\"utf-8\", index=False)\n print(\"already deleted {}\".format(df_deleted_already.shape[0]))\n","sub_path":"projects/stackoverflow/filterByTopic.py","file_name":"filterByTopic.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"259975589","text":"'''Write Python code that asks a user how many pizza slices they want.\nThe pizzeria charges Rs 123.00 a slice. \nif user order even number of slices, price per slice is Rs 120.00. \nPrint the total price depending on how many slices user orders.\n'''\n\nprint(\"Enter the number of slices: \")\nslices = int(input())\nprice_slice = 123.00\nif(slices % 2 == 0):\n price_slice = 120.00\ntotal_amount = slices * price_slice\nprint(\"Total amount for the entered slices is: %.2f\" % total_amount)","sub_path":"Python_Prog_Submissions/If-elif-else/pizza_slice.py","file_name":"pizza_slice.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"497882872","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nimport logging\nimport os\nfrom .util_misc import CockpitSingleton\n\n\nclass UserInput(CockpitSingleton):\n @classmethod\n def get_project_name(cls):\n proj_list = os.listdir('projects')\n logging.debug(proj_list)\n if len(proj_list) == 0:\n return None\n\n for index, name in enumerate(proj_list):\n print(f'{index}): {name}')\n\n try:\n project = int(input(\"\\nPlease select the project: \"))\n print(f'Your input is {project}): {proj_list[project]}')\n return proj_list[project]\n except Exception as e:\n print(e.args)\n logging.error('Please select right project')\n return None\n","sub_path":"project/cockpit_build/utils/user_input.py","file_name":"user_input.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"13221939","text":"import pygame\nimport random\nimport math\nfrom typing import List, Tuple\nfrom collections import deque\nfrom numpy.random import choice\n\nfrom ..Common import Constants\nfrom ..Common.Common_Types import *\nfrom ..SimpleFigures.Rectangle import Rectangle\n\n\n# Returns the Euclidean distance between two points.\ndef L2(a: Point, b: Point) -> float:\n return math.sqrt(math.pow((a.x-b.x), 2) + math.pow((a.y-b.y), 2))\n\n\n# Returns the L infinite between two points.\n# L infinite is commonly the max, not the min.\ndef Linf(a: Point, b: Point) -> int:\n return min(abs(a.x-b.x), abs(a.y-b.y))\n\n\n# Returns the closest corner L2 distance between two Rectangles.\ndef closest_L2(a: Rectangle, b: Rectangle) -> float:\n a_corners = a.get_corners()\n b_corners = b.get_corners()\n\n minimum = 10000\n for first in a_corners:\n for second in b_corners:\n current = L2(first, second)\n minimum = min(current, minimum)\n return minimum\n\n\n# Returns the closest corner Linf distance between two Rectangles.\ndef closest_Linf(a: Rectangle, b: Rectangle) -> int:\n a_corners = a.get_corners()\n b_corners = b.get_corners()\n\n minimum = 10000\n for first in a_corners:\n for second in b_corners:\n current = Linf(first, second)\n minimum = min(current, minimum)\n return minimum\n\n\n# Returns the indexes of the rectangles that are within the r area.\ndef all_within_r_L2(a: Rectangle, bs: List[Rectangle], r: int) -> List[int]:\n closests = []\n center = a.get_center()\n x_min = center.x - r\n x_max = center.x + r\n for i in range(len(bs)):\n lim = bs[i].get_limits()\n if lim.x_max < x_min:\n continue\n elif lim.x_min > x_max:\n break\n closests.append(i)\n closests.sort(key=lambda x: closest_L2(bs[x], a))\n return closests\n\n\n# Returns the closest rectangle to a in L2 distance.\ndef closest_of_all_L2(a: Rectangle, bs: List[Rectangle], r: int) -> Rectangle:\n closest_d = 10000\n center = a.get_center()\n x_min = center.x - r\n x_max = center.x + r\n closest = bs[0]\n for b in bs:\n lim = b.get_limits()\n if lim.x_max < x_min:\n continue\n elif lim.x_min > x_max:\n break\n current_d = closest_L2(a, b)\n if current_d < closest_d:\n closest_d = current_d\n closest = b\n return closest\n\n\n# Returns the closest rectangle to a in Linf distance, and the distance.\ndef closest_of_all_Linf(a: Rectangle, bs: List[Rectangle]) -> Tuple[Rectangle,\n int]:\n closest_d = 10000\n closest = bs[0]\n for b in bs:\n current_d = closest_Linf(a, b)\n if current_d < closest_d:\n closest_d = current_d\n closest = b\n return closest, closest_d\n\n\n# Returns the direction [dx, dy] from point a to point b.\ndef direction_to_point(a: Point, b: Point) -> Direction:\n dx = b.x - a.x\n dy = b.y - a.y\n total = abs(dx) + abs(dy)\n\n if total == 0:\n return Direction(0, 0)\n dx = float(dx) / float(total)\n dy = float(dy) / float(total)\n\n return Direction(dx, dy)\n\n\n# Returns the direction [dx, dy] from object a to object b.\n# If it's not within the sensing radius r, it returns a random movement.\n# It also returns True if it is within the area.\ndef sensing_direction(a: Rectangle, b: Rectangle, r: int) -> \\\n Tuple[Direction, bool]:\n a_center = a.get_center()\n corners = b.get_corners()\n for corner in corners:\n if r < L2(a_center, corner):\n return get_weighted_random_move(a.get_center(),\n a.get_direction()), False\n\n return direction_to_point(a_center, b.get_center()), True\n\n\ndef cardinal_system_direction(a: Rectangle, b: Rectangle) -> Direction:\n corners = b.get_corners()\n vip = a.get_corners()\n vip = vip[0]\n\n right = 0\n left = 0\n down = 0\n up = 0\n for corner in corners:\n if vip[0] <= corner[0]:\n right += 1\n if vip[0] >= corner[0]:\n left += 1\n if vip[1] <= corner[1]:\n down += 1\n if vip[1] >= corner[1]:\n up += 1\n\n if right == 4:\n return Direction(1, 0)\n elif left == 4:\n return Direction(-1, 0)\n elif down == 4:\n return Direction(0, 1)\n elif up == 4:\n return Direction(0, -1)\n return get_weighted_random_move(a.get_center(), a.get_direction())\n\n\n# Returns the index of which direction is the optimal to go.\n# 0 = up, 1 = up-right\n# 2 = right, 3 = down-right\n# 4 = down, 5 = down-left\n# 6 = left, 7 = up-left\ndef index_direction_to_point(a: Point, b: Point) -> int:\n dx, dy = direction_to_point(a, b)\n if -0.25 < dx <= 0.25: # This means dx = 0 or does not move in x.\n if dy > 0: # It should go down.\n return 4\n else: # It should go up.\n return 0\n elif 0.25 < dx <= 0.75: # This means dx = 0.5 or goes right.\n if dy > 0: # It should go down.\n return 3\n else: # It should go up.\n return 1\n elif -0.75 < dx <= -0.25: # This means dx = -0.5 or goes left.\n if dy > 0: # It should go down.\n return 5\n else: # It should go up.\n return 7\n elif 0.75 < dx: # This means dx = 1 or goes completely right.\n return 2\n else: # This means dx = -1 or goes completely left.\n return 6\n\n\n# Returns a random weighted movement towards the direction.\ndef get_weighted_random_move(a: Point, direction: int) -> Direction:\n index = index_direction_to_point(a, Constants.INTEREST_POINTS[direction])\n index = get_weighted_index(Constants.PROBABILITIES_MOVES,\n index,\n Constants.MOVES_INDEXES)\n return Constants.POSSIBLE_MOVES[index]\n\n\ndef get_weighted_index(probabilities: List[float],\n rotate_index: int,\n choices: List[int]) -> int:\n probabilities = deque(probabilities)\n probabilities.rotate(rotate_index)\n return choice(choices, 1, False, probabilities)[0]\n\n\ndef smart_collide(character: Rectangle, foods: List[Rectangle]) -> List[int]:\n indexes = []\n lim = character.get_limits()\n for i in range(len(foods)):\n f_lim = foods[i].get_limits()\n if f_lim.x_max < lim.x_min:\n continue\n elif f_lim.x_min > lim.x_max:\n return indexes\n if character.collides(foods[i]):\n indexes.append(i)\n return indexes\n","sub_path":"FlappyBird/pkg/Math/Distances.py","file_name":"Distances.py","file_ext":"py","file_size_in_byte":6551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"200947861","text":"from setuptools import find_packages, setup\n\nwith open(\"README.rst\") as readme_file:\n readme = readme_file.read()\n\nsetup(\n name=\"workflows\",\n description=\"Data processing in distributed environments\",\n long_description=readme,\n url=\"https://github.com/DiamondLightSource/python-workflows\",\n author=\"Markus Gerstel\",\n author_email=\"scientificsoftware@diamond.ac.uk\",\n download_url=\"https://github.com/DiamondLightSource/python-workflows/releases\",\n version=\"2.2\",\n install_requires=[\"setuptools\", \"stomp.py\"],\n python_requires=\">=3.6\",\n packages=find_packages(),\n license=\"BSD\",\n entry_points={\n \"console_scripts\": [\n \"workflows.validate_recipe = workflows.recipe.validate:main\"\n ],\n \"libtbx.dispatcher.script\": [\n \"workflows.validate_recipe = workflows.validate_recipe\"\n ],\n \"libtbx.precommit\": [\"workflows = workflows\"],\n \"workflows.services\": [\n \"SampleConsumer = workflows.services.sample_consumer:SampleConsumer\",\n \"SampleProducer = workflows.services.sample_producer:SampleProducer\",\n \"SampleTxn = workflows.services.sample_transaction:SampleTxn\",\n \"SampleTxnProducer = workflows.services.sample_transaction:SampleTxnProducer\",\n ],\n \"workflows.transport\": [\n \"StompTransport = workflows.transport.stomp_transport:StompTransport\"\n ],\n },\n tests_require=[\"pytest\"],\n zip_safe=False,\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"License :: OSI Approved :: BSD License\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Operating System :: OS Independent\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"41799883","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('reimsite', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Application',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('date', models.DateField(verbose_name=b'Apply date')),\n ('days', models.IntegerField(default=0)),\n ('category', models.CharField(max_length=20)),\n ('name', models.CharField(max_length=20)),\n ('total', models.IntegerField(default=0)),\n ('others', models.CharField(max_length=50)),\n ('remain', models.CharField(max_length=50)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Detail',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('source', models.CharField(max_length=10)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Funds',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('credit', models.CharField(max_length=20)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Item',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('money', models.IntegerField(default=0)),\n ('detail', models.ForeignKey(to='reimsite.Detail')),\n ('record', models.ForeignKey(to='reimsite.Application')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Reim',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('number', models.CharField(max_length=10)),\n ('funds', models.ForeignKey(to='reimsite.Funds')),\n ('record', models.OneToOneField(to='reimsite.Application')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.RemoveField(\n model_name='restaurant',\n name='place',\n ),\n migrations.DeleteModel(\n name='Place',\n ),\n migrations.RemoveField(\n model_name='waiter',\n name='restaurant',\n ),\n migrations.DeleteModel(\n name='Restaurant',\n ),\n migrations.DeleteModel(\n name='Waiter',\n ),\n ]\n","sub_path":"reimsite/migrations/0002_auto_20150318_0344.py","file_name":"0002_auto_20150318_0344.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"419716284","text":"# This takes a sequence of eliminated numbers and then returns a q that gives this sequence\n# Test sequences: \n\n# q = 62981\n# removes: [1, 16, 14, 9, 15, 8, 2]\n# should leave: [3, 4, 5, 6, 7, 10, 11, 12, 13, 17, 18, 19, 20]\n\n# q = 39283\n# removes: [3, 13, 20, 15, 18, 14, 11]\n# should leave: [12, 16, 17, 19, 1, 2, 4, 5, 6, 7, 8, 9, 10]\n\nfrom itertools import combinations, permutations\nfrom time import time\nfrom docplex.mp.model import Model\nfrom math import gcd\n\ndef one_step(numbers, q):\n x = q%len(numbers)\n x = x-1 if x > 0 else len(numbers)-1\n new_numbers = numbers[x+1:] + numbers[:x]\n return new_numbers\n \ndef simulate(numbers, q, steps, output = True):\n for i in range(steps):\n numbers = one_step(numbers, q)\n if output:\n print(numbers)\n return sorted(numbers)\n \ndef reconstruct(numbers, seq):\n m = Model()\n vv = m.integer_var()\n a = len(numbers)\n b = numbers.index(seq[0])+1\n numbers = one_step(numbers, b)\n coefficients = []\n for n in seq[1:]:\n i = numbers.index(n)\n d = 0 \n e = 0\n for qq in range(1,100):\n qqq = (a*qq+b-(i+1))/len(numbers)\n if qqq == int(qqq):\n if d:\n e = qq\n break\n else:\n d = qq\n if not d:\n return None\n v = m.integer_var()\n m.add(d+v*(e-d) == vv)\n v2 = m.integer_var()\n m.add(v2*len(numbers) + i + 1 == vv*a+b)\n if coefficients: # We are applying the euclydian algorithm here to check if overlaps are at all possible: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm , https://math.stackexchange.com/questions/1656120/formula-to-find-the-first-intersection-of-two-arithmetic-progressions\n for cs in coefficients:\n divisor = gcd(cs[0], len(numbers))\n if (i+1-cs[1])/divisor != int((i+1-cs[1])/divisor):\n return None\n coefficients.append((len(numbers), i+1))\n numbers = one_step(numbers, i+1)\n m.minimize(vv)\n solution = m.solve(log_output = True)\n if solution:\n return vv.solution_value*a+b\n else:\n return None\n \ndef check_unwinnable(numbers, uwnumbers):\n to_eliminate = [n for n in numbers if n not in uwnumbers]\n count = 0\n for perm in permutations(to_eliminate):\n print(count)\n count += 1\n tt = reconstruct(numbers, perm)\n if tt:\n print('This set is winnable with the following q: '+str(tt))\n return False\n print('This set is unwinnable')\n return True \n\n\nn = 20\nnumbers = [i+1 for i in range(n)]\nuwnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 11, 14, 15, 16, 17] # unwinnable\n#uwnumbers = [4, 5, 6, 7, 10, 13, 14, 15, 16, 17, 18, 19, 20] # unwinnable\n#uwnumbers = [1, 5, 6, 7, 10, 13, 14, 15, 16, 17, 18, 19, 20] # winnable\n#uwnumbers = [1, 2, 3, 4, 5, 6, 7, 9, 11, 14, 15, 16, 17] # winnable\na = check_unwinnable(numbers, uwnumbers)","sub_path":"2021-04/2_check_unwinnable.py","file_name":"2_check_unwinnable.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"647072786","text":"#!/usr/bin/env python\n# coding: utf-8\nimport sys\nfrom typing import List, Any, Dict, Union, Optional\nfrom copy import deepcopy\nfrom ast import literal_eval\nfrom pathlib import Path\nfrom typing import Tuple\nimport json\nimport yaml\n\nimport pandas as pd\nfrom dask.distributed import Client\nfrom dask.distributed import as_completed\nimport numpy as np\nimport msgpack\n\nfor path in [\n Path.home() / \"Developer\" / \"stsievert\" / \"salmon\",\n Path.home() / \"salmon\",\n]:\n sys.path.append(str(path / \"examples\"))\n\nimport run\nimport offline\n\nDIR = Path(\"io/2021-03-27\")\n\ndef _check_version():\n import salmon\n\n assert \"v0.5.2+22\" in salmon.__version__\n return True\n\n\ndef _literal_eval(x):\n try:\n return literal_eval(x)\n except ValueError:\n return x\n\n\ndef _get_dict(s: str) -> dict:\n k_v = [kv.split(\"=\") for kv in s.split(\"-\")]\n k_v2 = {k: _literal_eval(v) for k, v in k_v}\n return k_v2\n\n\ndef _ident(d: dict) -> str:\n d2 = sorted(tuple(d.items()))\n d3 = [f\"{k}={v}\" for k, v in d2]\n return \"-\".join(d3)\n\n\ndef _serialize(d):\n if isinstance(d, np.integer):\n return int(d)\n if isinstance(d, np.float):\n return float(d)\n if isinstance(d, list):\n return [_serialize(_) for _ in d]\n if isinstance(d, dict):\n return {k: _serialize(v) for k, v in d.items()}\n return d\n\n\ndef _prep():\n import os\n import torch\n\n threads = int(os.environ.get(\"OMP_NUM_THREADS\", 1))\n torch.set_num_threads(max(threads, 1))\n return threads\n\n\ndef _flatten(d, prefix=\"\"):\n if isinstance(d, (int, str, bytes, float)):\n return d\n elif isinstance(d, dict):\n return {k: _flatten(v, prefix=f\"{k}__\") for k, v in d.items()}\n elif isinstance(d, (list, tuple)):\n raise ValueError()\n raise ValueError()\n\n\ndef _get_kwargs(nm: str) -> Dict[str, Any]:\n # From section 3.2 of NEXT paper (last full paragraph on page 6)\n if nm == \"CKL\":\n return {\"module__mu\": 0.05}\n\n assert nm in (\"SOE\", \"GNMDS\", \"TSTE\")\n return {}\n\n\ndef _get_config(suffix: str, targets=False):\n with open(DIR / f\"config_{suffix}.yaml\") as f:\n raw = yaml.safe_load(f)\n if targets:\n return raw[\"targets\"]\n raw.pop(\"targets\")\n rare = _flatten(raw)\n return rare\n\n\ndef _get_futures(client, dfs, random_state: int, d=2, config=None):\n for k, df in dfs.items():\n if \"RR\" in k:\n continue\n elif \"RandomSampling\" in k:\n df = df.sample(frac=1, random_state=random_state)\n else:\n raise ValueError(f\"unrecognized algorithm in key {k}\")\n\n cols = [\"head\", \"winner\", \"loser\"]\n datasets = {k: df[cols].to_numpy() for k, df in dfs.items()}\n html_targets = _get_config(\"RandomSampling-5\", targets=True)\n targets = [t.split(\"/\")[-2].strip(\"i.png '\") for t in html_targets]\n print([len(v) for v in datasets.values()])\n X_test = run._X_test()\n\n print([len(v) for v in datasets.values()])\n print(f\"Total of {len(datasets)} items\")\n\n NUM_ANS = [n * i for i in range(1, 10)]\n NUM_ANS += [n * i for i in range(10, 20, 2)]\n NUM_ANS += [n * i for i in range(20, 50, 5)]\n NUM_ANS += [n * i for i in range(50, 100, 10)]\n NUM_ANS += [n * i for i in range(100, 400, 20) if n * i <= 7000]\n assert max(NUM_ANS) <= 6600\n NUM_ANS += [7000]\n\n static = dict(\n X_test=X_test,\n dwell=1000,\n verbose=1000,\n random_state=random_state,\n max_epochs=400_000,\n d=d,\n )\n\n if random_state == 1:\n keys = [k for k in datasets.keys() if \"RR\" in k]\n a_datasets = {k: client.scatter(datasets[k]) for k in keys}\n active_futures = [\n client.submit(\n offline._get_trained_model,\n a_datasets[k],\n n_responses=n_ans,\n meta=config or {},\n noise_model=nm,\n ident=f\"active-{nm}\",\n alg=\"active\",\n fname=k,\n priority=np.random.uniform(low=0.5, high=1),\n **static,\n **_get_kwargs(nm),\n )\n for n_ans in deepcopy(NUM_ANS)\n for nm in [\"TSTE\", \"SOE\", \"CKL\", \"GNMDS\"]\n for k in keys\n ]\n print(\"len(af)\", len(active_futures))\n else:\n active_futures = []\n\n assert all(\"Random\" in k or \"RR\" in k for k in dfs.keys())\n fname = \"RandomSampling-5_responses\"\n r_dataset = client.scatter(datasets[fname])\n random_futures = [\n client.submit(\n offline._get_trained_model,\n r_dataset,\n n_responses=n_ans,\n meta=config or {},\n noise_model=nm,\n ident=f\"random-{nm}\",\n alg=\"random\",\n fname=fname,\n priority=np.random.uniform(low=0.5, high=0.6) if random_state == 1 else 0,\n **static,\n **_get_kwargs(nm),\n )\n for n_ans in deepcopy(NUM_ANS)\n for nm in [\"TSTE\", \"SOE\", \"CKL\", \"GNMDS\"]\n ]\n\n futures = random_futures + active_futures\n print(f\"len(futures) = {len(futures)}\")\n return futures\n\n\nif __name__ == \"__main__\":\n\n DIR = Path(\"io/2021-03-27/\")\n # From run.py\n config = {\n \"n\": 30,\n \"d\": 2,\n \"R\": 1,\n \"dataset\": \"alien_eggs\",\n \"random_state\": 42,\n \"reaction_time\": 0.0,\n \"init\": True,\n \"max_queries\": 7000,\n \"fname\": \"{alg}-{responses_per_sec}\",\n }\n noise = \"human\"\n n = 30\n d = 2\n dfs = {\n f.name.replace(\".csv\", \"\"): pd.read_csv(f) for f in DIR.glob(\"*_responses.csv\")\n }\n print([len(df) for df in dfs.values()])\n assert all(\"7\" not in k for k in dfs.keys()), dfs.keys()\n\n # offline._get_trained_model(\n # datasets[\"responses_RandomSampling\"],\n # n_responses=10_000,\n # meta=_get_config(\"RandomSampling\"),\n # noise_model=\"CKL\",\n # module__mu=0.05,\n # **static,\n # )\n # sys.exit(0)\n # breakpoint()\n # r_dataset = datasets[\"responses_RandomSampling\"]\n\n client = Client(\"localhost:8786\")\n client.upload_file(\"offline.py\")\n _d = client.run(_check_version)\n _d = client.run(_prep)\n _d = list(_d.values())\n assert all(_d), _d\n print(_d)\n\n SEEDS = [s + 1 for s in range(10)]\n assert 1 in SEEDS and SEEDS[0] == 1\n _futures = [\n _get_futures(client, dfs, random_state=rs, d=d, config=config) for rs in SEEDS\n ]\n futures = sum(_futures, [])\n\n for i, future in enumerate(as_completed(futures)):\n est, meta = future.result()\n meta = _serialize(meta)\n fname = _ident(meta) + \".csv\"\n save = {\n \"embedding\": est.embedding_.tolist(),\n \"meta\": meta,\n \"performance\": _serialize(est.history_[-1]),\n \"history\": _serialize(est.history_),\n }\n _show = {k: est.history_[-1][k] for k in [\"score_test\", \"loss_test\"]}\n show = {k: f\"{v:0.3f}\" for k, v in _show.items()}\n print(i, meta[\"alg\"], meta[\"ident\"], meta[\"n_train\"], show)\n with open(f\"/scratch/ssievert/io/alien-eggs/{i}.msgpack\", \"wb\") as f2:\n msgpack.dump(save, f2)\n","sub_path":"response-rate/generate-embeddings.py","file_name":"generate-embeddings.py","file_ext":"py","file_size_in_byte":7125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"327764826","text":"#!/usr/bin/env python\n# Author P G Jones - 21/06/2012 : First revision\n# Produces a generic environment file\nimport os\n\nclass EnvFileBuilder( object ):\n \"\"\" Builds the env file for rat.\"\"\"\n def __init__( self, comment = None ):\n \"\"\" Initialise the env file text.\"\"\"\n self._BashEnv = \"#!/bin/bash\\n\"\n self._CshEnv = \"#!/bin/csh\\n\"\n if comment:\n self._BashEnv += comment\n self._CshEnv += comment\n self._LibraryPath = \"\"\n self._Path = \"\"\n self._PythonPath = \"\"\n self._BashFinal = \"\"\n self._CshFinal = \"\"\n return\n def AddSource( self, envFilePath, envFileName ):\n \"\"\" Add a source command.\"\"\"\n self._BashEnv += \"source %s/%s.sh\\n\" % ( envFilePath, envFileName )\n self._CshEnv += \"source %s/%s.csh\\n\" % ( envFilePath, envFileName )\n return\n def AddFinalSource( self, envFilePath, envFileName ):\n \"\"\" Add a source command to the end of the file.\"\"\"\n self._BashFinal += \"source %s/%s.sh\\n\" % ( envFilePath, envFileName )\n self._CshFinal += \"source %s/%s.csh\\n\" % ( envFilePath, envFileName )\n return\n def AddEnvironment( self, key, value ):\n \"\"\" Add an environment variable.\"\"\"\n self._BashEnv += \"export %s=%s\\n\" % ( key, value )\n self._CshEnv += \"setenv %s %s\\n\" % ( key, value )\n return\n def AppendLibraryPath( self, path ):\n \"\"\" Append a path to the library paths.\"\"\"\n self._LibraryPath += \"%s:\" % path\n return\n def AppendPath( self, path ):\n \"\"\" Append a path to the PATH.\"\"\"\n self._Path += \"%s:\" % path\n return\n def AppendPythonPath( self, path ):\n \"\"\" Append a path to the PYTHPNPATH.\"\"\"\n self._PythonPath += \"%s:\" % path\n return\n def WriteEnvFiles( self, directory, name ):\n \"\"\" Write the env files to the directory.\"\"\"\n # Strip the trailing :\n self._LibraryPath = self._LibraryPath[0:-1]\n self._Path = self._Path[0:-1]\n self._PythonPath = self._PythonPath[0:-1]\n # First add the Path\n self._BashEnv += \"export PATH=%s:$PATH\\n\" % self._Path\n self._CshEnv += \"setenv PATH %s:${PATH}\\n\" % self._Path\n # Next add the python path\n self._BashEnv += \"export PYTHONPATH=%s:$PYTHONPATH\\n\" % self._PythonPath\n self._CshEnv += \"if(${?PYTHONPATH}) then\\nsetenv PYTHONPATH %s:${PYTHONPATH}\\nelse\\nsetenv PYTHONPATH %s\\nendif\\n\" % (self._PythonPath, self._PythonPath)\n # Next add the libraries (Harder for cshell)\n self._BashEnv += \"export LD_LIBRARY_PATH=%s:$LD_LIBRARY_PATH\\n\" % self._LibraryPath\n self._BashEnv += \"export DYLD_LIBRARY_PATH=%s:$DYLD_LIBRARY_PATH\\n\" % self._LibraryPath\n self._CshEnv += \"if(${?LD_LIBRARY_PATH}) then\\nsetenv LD_LIBRARY_PATH %s:${LD_LIBRARY_PATH}\\nelse\\nsetenv LD_LIBRARY_PATH %s\\nendif\\n\" % ( self._LibraryPath, self._LibraryPath )\n self._CshEnv += \"if(${?DYLD_LIBRARY_PATH}) then\\nsetenv DYLD_LIBRARY_PATH %s:${DYLD_LIBRARY_PATH}\\nelse\\nsetenv DYLD_LIBRARY_PATH %s\\nendif\\n\" % (self._LibraryPath, self._LibraryPath )\n # Finnally add the rat\n self._BashEnv += self._BashFinal\n self._CshEnv += self._CshFinal\n # Now write the files\n bashFile = open( os.path.join( directory, \"%s.sh\" % name ), \"w\" )\n bashFile.write( self._BashEnv )\n bashFile.close()\n cshFile = open( os.path.join( directory, \"%s.csh\" % name ), \"w\" )\n cshFile.write( self._CshEnv )\n cshFile.close()\n return\n","sub_path":"core/EnvFileBuilder.py","file_name":"EnvFileBuilder.py","file_ext":"py","file_size_in_byte":3572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"422597198","text":"class Solution:\n def solveNQueens(self, n: int) -> List[List[str]]:\n if n == 0:\n return [[]]\n if n == 1:\n return [[\"Q\"]]\n \n configs = []\n xy_diff, xy_sum = set(), set()\n cols = collections.OrderedDict()\n self.dfs(cols, n, configs, xy_diff, xy_sum)\n \n return [[\".\" * col + \"Q\" + \".\" * (n - col - 1) for col in config] for config in configs]\n \n def dfs(self, cols, n, configs, xy_diff, xy_sum):\n row = len(cols)\n if row == n:\n configs.append([key for key, _ in cols.items()])\n \n for col in range(n):\n if col not in cols and row + col not in xy_sum and row - col not in xy_diff:\n cols[col] = 1\n xy_sum.add(row + col)\n xy_diff.add(row - col)\n self.dfs(cols, n, configs, xy_diff, xy_sum)\n del cols[col]\n xy_sum.remove(row + col)\n xy_diff.remove(row - col)\n","sub_path":"Python/51N-Queens.py","file_name":"51N-Queens.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"106592601","text":"#!/usr/bin/python3\n\"\"\" This module contains a single function.\n\"\"\"\n\n\ndef number_of_lines(filename=\"\"):\n \"\"\"\n Returns the number of lines of text file.\n \"\"\"\n\n line_numbers = 0\n with open(filename, mode='r', encoding='utf-8') as f:\n for line in f:\n line_numbers += 1\n\n return line_numbers\n","sub_path":"0x0B-python-input_output/1-number_of_lines.py","file_name":"1-number_of_lines.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"110053079","text":"from __future__ import absolute_import\n\nfrom django.core.mail import send_mail\nfrom celery.decorators import periodic_task\nfrom celery.schedules import crontab\nfrom Practice_Referral import settings\nfrom tracking.models import ReferringReportSetting, ClinicReportSetting, \\\n Clinic, ReportSetting\nfrom tracking.reports import ReportManager, InvalidReportException\nfrom tracking.reports.referring_reports import REPORT_TYPE \\\n as REFERRING_REPORT_TYPE\nfrom tracking.reports.clinic_reports import REPORT_TYPE \\\n as CLINIC_REPORT_TYPE\nfrom celery.utils.log import get_task_logger\n\nlogger = get_task_logger(__name__)\n\n\ndef _send_report(report, email):\n ''' send a report to an email '''\n if report.skipped():\n logger.info('Report %s skipped!', report)\n return\n\n subject = report.get_subject()\n body = report.get_body()\n logger.info('Sending Email from %s to %s: subject: %s, body: %s',\n settings.DEFAULT_EMAIL_FROM, email, subject, body)\n send_mail(subject, body, settings.DEFAULT_EMAIL_FROM, [email],\n fail_silently=True, html_message=body)\n\n\ndef send_referring_reports(period):\n '''\n handle sending of referring report by given report settings objects\n '''\n referring_report_settings = _get_referring_report_setting(period)\n logger.info('**** Handling %s referring_report_settings...',\n len(referring_report_settings))\n for report_setting in referring_report_settings:\n referring_entity = report_setting.referring_entity\n email = referring_entity.entity_email\n if not email:\n logger.warn('No entity_email for [%s]!', referring_entity)\n continue\n try:\n ReportClass = ReportManager.get_report_cls(\n REFERRING_REPORT_TYPE, name=report_setting.report_name)\n except InvalidReportException:\n logger.warn('Unknown report [%s]!', report_setting.report_name)\n continue\n\n report = ReportClass(referring_entity=report_setting.referring_entity,\n logger=logger)\n _send_report(report, email)\n\n\ndef send_clinic_reports(period):\n '''\n handle sending of clinic report by given period\n '''\n clinics = Clinic.objects.all()\n for clinic in clinics:\n clinic_report_settings = _get_clinic_report_setting(\n period=period, clinic=clinic)\n logger.info('**** clinic: %s - Handling %s clinic_report_settings...',\n clinic, len(clinic_report_settings))\n reports_map = {}\n for report_setting in clinic_report_settings:\n clinic_user = report_setting.clinic_user\n email = clinic_user.user.email\n if not email:\n logger.warn('No email for [%s]!', clinic_user)\n continue\n report = reports_map.get(report_setting.report_name, None)\n if not report:\n try:\n ReportClass = ReportManager.get_report_cls(\n CLINIC_REPORT_TYPE, name=report_setting.report_name)\n except InvalidReportException:\n logger.warn('Unknown report [%s]!',\n report_setting.report_name)\n continue\n report = ReportClass(clinic=clinic, logger=logger)\n reports_map[report_setting.report_name] = report\n _send_report(report, email)\n\n\ndef _get_referring_report_setting(period):\n return ReferringReportSetting.objects.filter(\n period=period, enabled=True).all()\n\n\ndef _get_clinic_report_setting(period, clinic):\n return ClinicReportSetting.objects.filter(\n period=period, enabled=True, clinic=clinic).all()\n\n\ndef _send_all_reports(period):\n try:\n send_referring_reports(period=period)\n except Exception as e:\n logger.exception(e)\n\n try:\n send_clinic_reports(period=period)\n except Exception as e:\n logger.exception(e)\n\n\n# @periodic_task(run_every=crontab(minute='*/1'))\n@periodic_task(run_every=crontab(minute=0, hour=0))\ndef daily_reports_handler():\n '''\n daily reports handler\n python manage.py celeryd -B -l info\n '''\n _send_all_reports(ReportSetting.PERIOD_DAILY)\n\n\n# @periodic_task(run_every=crontab(minute='*/1'))\n@periodic_task(run_every=crontab(hour=0, minute=0, day_of_week=1))\ndef weekly_reports_handler():\n '''\n weekly reports handler\n python manage.py celeryd -B -l info\n '''\n _send_all_reports(ReportSetting.PERIOD_WEEKLY)\n\n\n# @periodic_task(run_every=crontab(minute='*/1'))\n@periodic_task(run_every=crontab(hour=0, minute=0, day_of_month=1))\ndef monthly_reports_handler():\n '''\n monthly reports handler\n python manage.py celeryd -B -l info\n '''\n _send_all_reports(ReportSetting.PERIOD_MONTHLY)\n\n\n@periodic_task(run_every=crontab(hour=0, minute=0, day_of_month=1,\n month_of_year='*/3'))\ndef quarterly_reports_handler():\n '''\n quarterly reports handler\n python manage.py celeryd -B -l info\n '''\n _send_all_reports(ReportSetting.PERIOD_QUARTERLY)\n\n\n@periodic_task(run_every=crontab(hour=0, minute=0, day_of_month=1,\n month_of_year=1))\ndef yealy_reports_handler():\n '''\n yearly reports handler\n python manage.py celeryd -B -l info\n '''\n _send_all_reports(ReportSetting.PERIOD_YEARLY)\n","sub_path":"tracking/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":5387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"577744707","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom tapi_server.models.base_model_ import Model\nfrom tapi_server.models.tapi_common_capacity import TapiCommonCapacity # noqa: F401,E501\nfrom tapi_server.models.tapi_common_capacity_pac import TapiCommonCapacityPac # noqa: F401,E501\nfrom tapi_server.models.tapi_common_global_class import TapiCommonGlobalClass # noqa: F401,E501\nfrom tapi_server.models.tapi_common_name_and_value import TapiCommonNameAndValue # noqa: F401,E501\nfrom tapi_server.models.tapi_topology_cost_characteristic import TapiTopologyCostCharacteristic # noqa: F401,E501\nfrom tapi_server.models.tapi_topology_inter_rule_group import TapiTopologyInterRuleGroup # noqa: F401,E501\nfrom tapi_server.models.tapi_topology_latency_characteristic import TapiTopologyLatencyCharacteristic # noqa: F401,E501\nfrom tapi_server.models.tapi_topology_node_edge_point_ref import TapiTopologyNodeEdgePointRef # noqa: F401,E501\nfrom tapi_server.models.tapi_topology_node_rule_group_ref import TapiTopologyNodeRuleGroupRef # noqa: F401,E501\nfrom tapi_server.models.tapi_topology_risk_characteristic import TapiTopologyRiskCharacteristic # noqa: F401,E501\nfrom tapi_server.models.tapi_topology_risk_parameter_pac import TapiTopologyRiskParameterPac # noqa: F401,E501\nfrom tapi_server.models.tapi_topology_rule import TapiTopologyRule # noqa: F401,E501\nfrom tapi_server.models.tapi_topology_transfer_cost_pac import TapiTopologyTransferCostPac # noqa: F401,E501\nfrom tapi_server.models.tapi_topology_transfer_timing_pac import TapiTopologyTransferTimingPac # noqa: F401,E501\nfrom tapi_server import util\n\n\nclass TapiTopologyNodeRuleGroup(Model):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(self, available_capacity=None, total_potential_capacity=None, name=None, uuid=None, risk_characteristic=None, cost_characteristic=None, latency_characteristic=None, inter_rule_group=None, rule=None, composed_rule_group=None, node_edge_point=None): # noqa: E501\n \"\"\"TapiTopologyNodeRuleGroup - a model defined in OpenAPI\n\n :param available_capacity: The available_capacity of this TapiTopologyNodeRuleGroup. # noqa: E501\n :type available_capacity: TapiCommonCapacity\n :param total_potential_capacity: The total_potential_capacity of this TapiTopologyNodeRuleGroup. # noqa: E501\n :type total_potential_capacity: TapiCommonCapacity\n :param name: The name of this TapiTopologyNodeRuleGroup. # noqa: E501\n :type name: List[TapiCommonNameAndValue]\n :param uuid: The uuid of this TapiTopologyNodeRuleGroup. # noqa: E501\n :type uuid: str\n :param risk_characteristic: The risk_characteristic of this TapiTopologyNodeRuleGroup. # noqa: E501\n :type risk_characteristic: List[TapiTopologyRiskCharacteristic]\n :param cost_characteristic: The cost_characteristic of this TapiTopologyNodeRuleGroup. # noqa: E501\n :type cost_characteristic: List[TapiTopologyCostCharacteristic]\n :param latency_characteristic: The latency_characteristic of this TapiTopologyNodeRuleGroup. # noqa: E501\n :type latency_characteristic: List[TapiTopologyLatencyCharacteristic]\n :param inter_rule_group: The inter_rule_group of this TapiTopologyNodeRuleGroup. # noqa: E501\n :type inter_rule_group: List[TapiTopologyInterRuleGroup]\n :param rule: The rule of this TapiTopologyNodeRuleGroup. # noqa: E501\n :type rule: List[TapiTopologyRule]\n :param composed_rule_group: The composed_rule_group of this TapiTopologyNodeRuleGroup. # noqa: E501\n :type composed_rule_group: List[TapiTopologyNodeRuleGroupRef]\n :param node_edge_point: The node_edge_point of this TapiTopologyNodeRuleGroup. # noqa: E501\n :type node_edge_point: List[TapiTopologyNodeEdgePointRef]\n \"\"\"\n self.openapi_types = {\n 'available_capacity': TapiCommonCapacity,\n 'total_potential_capacity': TapiCommonCapacity,\n 'name': List[TapiCommonNameAndValue],\n 'uuid': str,\n 'risk_characteristic': List[TapiTopologyRiskCharacteristic],\n 'cost_characteristic': List[TapiTopologyCostCharacteristic],\n 'latency_characteristic': List[TapiTopologyLatencyCharacteristic],\n 'inter_rule_group': List[TapiTopologyInterRuleGroup],\n 'rule': List[TapiTopologyRule],\n 'composed_rule_group': List[TapiTopologyNodeRuleGroupRef],\n 'node_edge_point': List[TapiTopologyNodeEdgePointRef]\n }\n\n self.attribute_map = {\n 'available_capacity': 'available-capacity',\n 'total_potential_capacity': 'total-potential-capacity',\n 'name': 'name',\n 'uuid': 'uuid',\n 'risk_characteristic': 'risk-characteristic',\n 'cost_characteristic': 'cost-characteristic',\n 'latency_characteristic': 'latency-characteristic',\n 'inter_rule_group': 'inter-rule-group',\n 'rule': 'rule',\n 'composed_rule_group': 'composed-rule-group',\n 'node_edge_point': 'node-edge-point'\n }\n\n self._available_capacity = available_capacity\n self._total_potential_capacity = total_potential_capacity\n self._name = name\n self._uuid = uuid\n self._risk_characteristic = risk_characteristic\n self._cost_characteristic = cost_characteristic\n self._latency_characteristic = latency_characteristic\n self._inter_rule_group = inter_rule_group\n self._rule = rule\n self._composed_rule_group = composed_rule_group\n self._node_edge_point = node_edge_point\n\n @classmethod\n def from_dict(cls, dikt) -> 'TapiTopologyNodeRuleGroup':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The tapi.topology.NodeRuleGroup of this TapiTopologyNodeRuleGroup. # noqa: E501\n :rtype: TapiTopologyNodeRuleGroup\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def available_capacity(self):\n \"\"\"Gets the available_capacity of this TapiTopologyNodeRuleGroup.\n\n\n :return: The available_capacity of this TapiTopologyNodeRuleGroup.\n :rtype: TapiCommonCapacity\n \"\"\"\n return self._available_capacity\n\n @available_capacity.setter\n def available_capacity(self, available_capacity):\n \"\"\"Sets the available_capacity of this TapiTopologyNodeRuleGroup.\n\n\n :param available_capacity: The available_capacity of this TapiTopologyNodeRuleGroup.\n :type available_capacity: TapiCommonCapacity\n \"\"\"\n\n self._available_capacity = available_capacity\n\n @property\n def total_potential_capacity(self):\n \"\"\"Gets the total_potential_capacity of this TapiTopologyNodeRuleGroup.\n\n\n :return: The total_potential_capacity of this TapiTopologyNodeRuleGroup.\n :rtype: TapiCommonCapacity\n \"\"\"\n return self._total_potential_capacity\n\n @total_potential_capacity.setter\n def total_potential_capacity(self, total_potential_capacity):\n \"\"\"Sets the total_potential_capacity of this TapiTopologyNodeRuleGroup.\n\n\n :param total_potential_capacity: The total_potential_capacity of this TapiTopologyNodeRuleGroup.\n :type total_potential_capacity: TapiCommonCapacity\n \"\"\"\n\n self._total_potential_capacity = total_potential_capacity\n\n @property\n def name(self):\n \"\"\"Gets the name of this TapiTopologyNodeRuleGroup.\n\n List of names. A property of an entity with a value that is unique in some namespace but may change during the life of the entity. A name carries no semantics with respect to the purpose of the entity. # noqa: E501\n\n :return: The name of this TapiTopologyNodeRuleGroup.\n :rtype: List[TapiCommonNameAndValue]\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this TapiTopologyNodeRuleGroup.\n\n List of names. A property of an entity with a value that is unique in some namespace but may change during the life of the entity. A name carries no semantics with respect to the purpose of the entity. # noqa: E501\n\n :param name: The name of this TapiTopologyNodeRuleGroup.\n :type name: List[TapiCommonNameAndValue]\n \"\"\"\n\n self._name = name\n\n @property\n def uuid(self):\n \"\"\"Gets the uuid of this TapiTopologyNodeRuleGroup.\n\n UUID: An identifier that is universally unique within an identifier space, where the identifier space is itself globally unique, and immutable. An UUID carries no semantics with respect to the purpose or state of the entity. UUID here uses string representation as defined in RFC 4122. The canonical representation uses lowercase characters. Pattern: [0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-' + '[0-9a-fA-F]{4}-[0-9a-fA-F]{12} Example of a UUID in string representation: f81d4fae-7dec-11d0-a765-00a0c91e6bf6 # noqa: E501\n\n :return: The uuid of this TapiTopologyNodeRuleGroup.\n :rtype: str\n \"\"\"\n return self._uuid\n\n @uuid.setter\n def uuid(self, uuid):\n \"\"\"Sets the uuid of this TapiTopologyNodeRuleGroup.\n\n UUID: An identifier that is universally unique within an identifier space, where the identifier space is itself globally unique, and immutable. An UUID carries no semantics with respect to the purpose or state of the entity. UUID here uses string representation as defined in RFC 4122. The canonical representation uses lowercase characters. Pattern: [0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-' + '[0-9a-fA-F]{4}-[0-9a-fA-F]{12} Example of a UUID in string representation: f81d4fae-7dec-11d0-a765-00a0c91e6bf6 # noqa: E501\n\n :param uuid: The uuid of this TapiTopologyNodeRuleGroup.\n :type uuid: str\n \"\"\"\n\n self._uuid = uuid\n\n @property\n def risk_characteristic(self):\n \"\"\"Gets the risk_characteristic of this TapiTopologyNodeRuleGroup.\n\n A list of risk characteristics for consideration in an analysis of shared risk. Each element of the list represents a specific risk consideration. # noqa: E501\n\n :return: The risk_characteristic of this TapiTopologyNodeRuleGroup.\n :rtype: List[TapiTopologyRiskCharacteristic]\n \"\"\"\n return self._risk_characteristic\n\n @risk_characteristic.setter\n def risk_characteristic(self, risk_characteristic):\n \"\"\"Sets the risk_characteristic of this TapiTopologyNodeRuleGroup.\n\n A list of risk characteristics for consideration in an analysis of shared risk. Each element of the list represents a specific risk consideration. # noqa: E501\n\n :param risk_characteristic: The risk_characteristic of this TapiTopologyNodeRuleGroup.\n :type risk_characteristic: List[TapiTopologyRiskCharacteristic]\n \"\"\"\n\n self._risk_characteristic = risk_characteristic\n\n @property\n def cost_characteristic(self):\n \"\"\"Gets the cost_characteristic of this TapiTopologyNodeRuleGroup.\n\n The list of costs where each cost relates to some aspect of the TopologicalEntity. # noqa: E501\n\n :return: The cost_characteristic of this TapiTopologyNodeRuleGroup.\n :rtype: List[TapiTopologyCostCharacteristic]\n \"\"\"\n return self._cost_characteristic\n\n @cost_characteristic.setter\n def cost_characteristic(self, cost_characteristic):\n \"\"\"Sets the cost_characteristic of this TapiTopologyNodeRuleGroup.\n\n The list of costs where each cost relates to some aspect of the TopologicalEntity. # noqa: E501\n\n :param cost_characteristic: The cost_characteristic of this TapiTopologyNodeRuleGroup.\n :type cost_characteristic: List[TapiTopologyCostCharacteristic]\n \"\"\"\n\n self._cost_characteristic = cost_characteristic\n\n @property\n def latency_characteristic(self):\n \"\"\"Gets the latency_characteristic of this TapiTopologyNodeRuleGroup.\n\n The effect on the latency of a queuing process. This only has significant effect for packet based systems and has a complex characteristic. # noqa: E501\n\n :return: The latency_characteristic of this TapiTopologyNodeRuleGroup.\n :rtype: List[TapiTopologyLatencyCharacteristic]\n \"\"\"\n return self._latency_characteristic\n\n @latency_characteristic.setter\n def latency_characteristic(self, latency_characteristic):\n \"\"\"Sets the latency_characteristic of this TapiTopologyNodeRuleGroup.\n\n The effect on the latency of a queuing process. This only has significant effect for packet based systems and has a complex characteristic. # noqa: E501\n\n :param latency_characteristic: The latency_characteristic of this TapiTopologyNodeRuleGroup.\n :type latency_characteristic: List[TapiTopologyLatencyCharacteristic]\n \"\"\"\n\n self._latency_characteristic = latency_characteristic\n\n @property\n def inter_rule_group(self):\n \"\"\"Gets the inter_rule_group of this TapiTopologyNodeRuleGroup.\n\n none # noqa: E501\n\n :return: The inter_rule_group of this TapiTopologyNodeRuleGroup.\n :rtype: List[TapiTopologyInterRuleGroup]\n \"\"\"\n return self._inter_rule_group\n\n @inter_rule_group.setter\n def inter_rule_group(self, inter_rule_group):\n \"\"\"Sets the inter_rule_group of this TapiTopologyNodeRuleGroup.\n\n none # noqa: E501\n\n :param inter_rule_group: The inter_rule_group of this TapiTopologyNodeRuleGroup.\n :type inter_rule_group: List[TapiTopologyInterRuleGroup]\n \"\"\"\n\n self._inter_rule_group = inter_rule_group\n\n @property\n def rule(self):\n \"\"\"Gets the rule of this TapiTopologyNodeRuleGroup.\n\n none # noqa: E501\n\n :return: The rule of this TapiTopologyNodeRuleGroup.\n :rtype: List[TapiTopologyRule]\n \"\"\"\n return self._rule\n\n @rule.setter\n def rule(self, rule):\n \"\"\"Sets the rule of this TapiTopologyNodeRuleGroup.\n\n none # noqa: E501\n\n :param rule: The rule of this TapiTopologyNodeRuleGroup.\n :type rule: List[TapiTopologyRule]\n \"\"\"\n\n self._rule = rule\n\n @property\n def composed_rule_group(self):\n \"\"\"Gets the composed_rule_group of this TapiTopologyNodeRuleGroup.\n\n none # noqa: E501\n\n :return: The composed_rule_group of this TapiTopologyNodeRuleGroup.\n :rtype: List[TapiTopologyNodeRuleGroupRef]\n \"\"\"\n return self._composed_rule_group\n\n @composed_rule_group.setter\n def composed_rule_group(self, composed_rule_group):\n \"\"\"Sets the composed_rule_group of this TapiTopologyNodeRuleGroup.\n\n none # noqa: E501\n\n :param composed_rule_group: The composed_rule_group of this TapiTopologyNodeRuleGroup.\n :type composed_rule_group: List[TapiTopologyNodeRuleGroupRef]\n \"\"\"\n\n self._composed_rule_group = composed_rule_group\n\n @property\n def node_edge_point(self):\n \"\"\"Gets the node_edge_point of this TapiTopologyNodeRuleGroup.\n\n none # noqa: E501\n\n :return: The node_edge_point of this TapiTopologyNodeRuleGroup.\n :rtype: List[TapiTopologyNodeEdgePointRef]\n \"\"\"\n return self._node_edge_point\n\n @node_edge_point.setter\n def node_edge_point(self, node_edge_point):\n \"\"\"Sets the node_edge_point of this TapiTopologyNodeRuleGroup.\n\n none # noqa: E501\n\n :param node_edge_point: The node_edge_point of this TapiTopologyNodeRuleGroup.\n :type node_edge_point: List[TapiTopologyNodeEdgePointRef]\n \"\"\"\n\n self._node_edge_point = node_edge_point\n","sub_path":"RI/flask_server/tapi_server/models/tapi_topology_node_rule_group.py","file_name":"tapi_topology_node_rule_group.py","file_ext":"py","file_size_in_byte":15991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"305217841","text":"# Blob Detection Example\n#通讯test\n\nimport sensor, image, time,pyb\nfrom pyb import UART\nfrom pyb import LED\nimport json\n\n\ntest_threshold = (65, 69, -12, -2, 32, 57)\n\n#EXPOSURE_TIME_SCALE = 0.48\n\nsensor.reset() # 初始化sensor\nsensor.set_pixformat(sensor.RGB565) # use RGB565.\nsensor.set_framesize(sensor.QQVGA) # 使用QQVGA的速度。(160*120)\n#设置图像像素大小\n\n# 打印出初始曝光时间以进行比较。\n#print(\"Initial exposure == %d\" % sensor.get_exposure_us())\n\nsensor.skip_frames(30) # 等待设置生效。\nclock = time.clock() # 创建一个时钟对象来跟踪FPS帧率。\n\n# 您必须关闭自动增益控制和自动白平衡,否则他们将更改图像增益以撤消您放置的任何曝光设置...\nsensor.set_auto_gain(False)\nsensor.set_auto_whitebal(False)\n# 需要让以上设置生效\nsensor.skip_frames(time = 500)\n\n#clock = time.clock() # 跟踪FPS帧率\n#current_exposure_time_in_microseconds = sensor.get_exposure_us()\n#print(\"Current Exposure == %d\" % current_exposure_time_in_microseconds)\n\n# 默认情况下启用自动曝光控制(AEC)。调用以下功能可禁用传感器自动曝光控制。\n# 另外“exposure_us”参数在AEC被禁用后覆盖自动曝光值。\n#sensor.set_auto_exposure(False, \\\n #exposure_us = int(current_exposure_time_in_microseconds * EXPOSURE_TIME_SCALE))\n\n#串口初始化Openmv\nuart = UART(3, 115200) ##串口3,波特率115200\nuart.init(115200, bits=8, parity=None, stop=1) #8位数据位,无校验位,1位停止位\n\n\nwhile(True):\n clock.tick() # 追踪两个snapshots()之间经过的毫秒数.\n img = sensor.snapshot() # 拍一张照片并返回图像。\n\n blobs = img.find_blobs([test_threshold],pixels_threshold=25, area_threshold=25)\n\n if blobs:\n #如果找到了目标颜色\n for b in blobs:\n #迭代找到的目标颜色区域\n print(\"1\")\n data0=8 #校验位,为x坐标+y坐标 的低八位\n data1=360\n data2=1\n checkout=(data1+data2) #取其低八位\n data = bytearray([0xAA,data0,data1, data2,checkout,0x54])#转成16进制\n #如果识别的坐标大于255,建议除以2之后再发,因为一个字节范围只有0-255\n uart.write(data)#通过串口发送出去数据\n #print(clock.fps()) # 注意: 当连接电脑后,OpenMV会变成一半的速度。当不连接电脑,帧率会增加\n","sub_path":"通信/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"246387274","text":"import os\nimport numpy as np\nimport cv2 as cv\n\nimages_path_1 = 'dataset/obtained_data/'\nimages1 = sorted(os.listdir(images_path_1))\n\ntrain_labels_file = open('dataset/train_labels2.txt', 'w')\nvalid_labels_file = open('dataset/valid_labels2.txt', 'w')\ntest_labels_file = open('dataset/test_labels2.txt', 'w')\n\nlabels1 = np.load('dataset/labels.npy')\nsize1 = len(labels1)\nlimit1, limit2 = int(0.7*size1), int(0.9*size1)\ntrain_labels1, train_images1 = labels1[0:limit1], images1[0 : limit1]\nval_labels1, val_images1 = labels1[limit1:limit2], images1[limit1:limit2]\ntest_labels1, test_images1 = labels1[limit2:], images1[limit2:]\n\ntotal_train_labels = []\ntotal_val_labels = []\ntotal_test_labels = []\n\nfor i in range(len(train_images1)):\n\timg_path = os.path.join(images_path_1, train_images1[i])\n\ttext = str(img_path + '\\t' + train_labels1[i] + '\\n')\n\tprint('Processing:', text, end='')\n\ttotal_train_labels.append(text)\n\nfor i in range(len(val_images1)):\n\timg_path = os.path.join(images_path_1, val_images1[i])\n\ttext = str(img_path + '\\t' + val_labels1[i] + '\\n')\n\tprint('Processing:', text, end='')\n\ttotal_val_labels.append(text)\n\nfor i in range(len(test_images1)):\n\timg_path = os.path.join(images_path_1, test_images1[i])\n\ttext = str(img_path + '\\t' + test_labels1[i] + '\\n')\n\tprint('Processing:', text, end='')\n\ttotal_test_labels.append(text)\n\n\ntrain_labels2 = open('dataset/orig_dataset/annotation_train.txt', 'r').readlines()\nval_labels2 = open('dataset/orig_dataset/annotation_val.txt', 'r').readlines()\ntest_labels2 = open('dataset/orig_dataset/annotation_test.txt', 'r').readlines()\n\n\nfor i in range(min(len(train_labels2), len(train_labels1) * 9)):\n\timg_path, label = train_labels2[i].split(' ')\n\tlimit1 = img_path.find('_')\n\tlimit2 = img_path.rfind('_')\n\tlabel = img_path[limit1 + 1:limit2]\n\tif img_path[0] == '.':\n\t\timg_path = 'dataset/orig_dataset' + img_path[1:]\n\ttext = str(img_path + '\\t' + label + '\\n')\n\tprint('Processing:', text, end='')\n\ttotal_train_labels.append(text)\n\nfor i in range(min(len(val_labels2), len(val_labels1) * 9)):\n\timg_path, label = val_labels2[i].split(' ')\n\tlimit1 = img_path.find('_')\n\tlimit2 = img_path.rfind('_')\n\tlabel = img_path[limit1 + 1:limit2]\n\tif img_path[0] == '.':\n\t\timg_path = 'dataset/orig_dataset' + img_path[1:]\n\ttext = str(img_path + '\\t' + label + '\\n')\n\tprint('Processing:', text, end='')\n\ttotal_val_labels.append(text)\n\nfor i in range(min(len(test_labels2), len(test_labels1) * 9)):\n\timg_path, label = test_labels2[i].split(' ')\n\tlimit1 = img_path.find('_')\n\tlimit2 = img_path.rfind('_')\n\tlabel = img_path[limit1 + 1:limit2]\n\tif img_path[0] == '.':\n\t\timg_path = 'dataset/orig_dataset' + img_path[1:]\n\ttext = str(img_path + '\\t' + label + '\\n')\n\tprint('Processing:', text, end='')\n\ttotal_test_labels.append(text)\n\n\nnp.random.shuffle(total_train_labels)\nnp.random.shuffle(total_val_labels)\nnp.random.shuffle(total_test_labels)\n\nprint('\\nSaving train dataset of size:', len(total_train_labels))\nfor i in range(len(total_train_labels)):\n\ttrain_labels_file.write(total_train_labels[i])\nprint('Saving validation dataset of size:', len(total_val_labels))\nfor i in range(len(total_val_labels)):\n\tvalid_labels_file.write(total_val_labels[i])\nprint('Saving test dataset of size:', len(total_test_labels))\nfor i in range(len(total_test_labels)):\n\ttest_labels_file.write(total_test_labels[i])\n","sub_path":"create_label_file.py","file_name":"create_label_file.py","file_ext":"py","file_size_in_byte":3335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"116772765","text":"#!/usr/bin/python\nimport urllib2,json,time,vdrlogo,os\n\ndef lyngsat_download(country_list):\n\t#Download logo HTML\n\tcode_list = country_list.split(\",\")\n\n\tfor num in range(0,len(code_list)):\n\t\tvdrlogo.run_cmd(\"wget -q \" + vdrlogo.lyngsat_logo_URL + code_list[num] + \".html -O out.html\")\n\t\tvdrlogo.run_cmd('cat out.html | grep \"\\\\../logo/tv\" >> work.html')\n\t\tvdrlogo.run_cmd(\"rm out.html\")\n\t\n\tf = open(\"work.html\")\n\tsource = f.readlines()\n\tf.close()\n\n\tget_urls(source)\n\n\t#delete temp files\n\tvdrlogo.run_cmd(\"rm *.html\")\n\ndef get_urls(source):\n\n\tfor num in range(0,len(source)):\n\t\tif(source[num].find(\"../logo\")):\n\t\t\tfirstposition = source[num].index(\"../logo\")\n\t\t\tlastposition =source[num].index(\".png\")\n\t\t\tdirtypath=source[num][firstposition:lastposition+4]\n\n\t\t\t#Cleaning\n\t\t\tsource[num]=source[num][firstposition:lastposition+4].replace(\"..\",\"http://www.lyngsat-logo.com\")\n\n\t\t\t#Download\n\t\t\tlastslashposition = source[num].rindex(\"/\") +1\n\t\t\tfilename = source[num][lastslashposition:len(source[num])]\n\n\t\t\t#Cleaning tools\n\t\t\tif not(filename.find(\"_hu\") == -1):\n\t\t\t\tfilename = filename.replace(\"hu\",\"\")\n\t\t\telif not(filename.find(\"_ro\") == -1):\n\t\t\t\tfilename = filename.replace(\"ro\",\"\") \n\t\t\telif not(filename.find(\"_eu\")) == -1:\n\t\t\t\tfilename = filename.replace(\"eu\",\"\")\n\t\t\telif not(filename.find(\"_us\")) == -1:\n\t\t\t\tfilename = filename.replace(\"us\",\"\")\n\t\t\telif not(filename.find(\"_ce\")) == -1:\n\t\t\t\tfilename = filename.replace(\"ce\",\"\")\n\n\t\t\tfilename = filename.replace(\" \",\"\")\n\t\t\tfilename = filename.replace(\"_\",\" \")\n\t\t\tfilename = filename.replace(\" .\",\".\")\n\n\t\t\tvdrlogo.run_cmd('wget -q '+source[num]+' -O \"'+vdrlogo.workfoldername+filename.lower()+'\"')\n\t\t\t\n\ndef google_download(channel_name):\n\tprint(channel_name)\n\turl = ('https://ajax.googleapis.com/ajax/services/search/images?' + 'v=1.0&q='+channel_name+'&as_filetype=png&as_sitesearch=http://www.lyngsat-logo.com')\n\trequest = urllib2.Request(url, None)\n\tresponse = urllib2.urlopen(request)\n\n\t# Process the JSON string.\n\tresults = json.load(response)\n\t# now have some fun with the results...\n\ttry:\n\t\tpix_url = results['responseData']['results'][0]['url']\n\t\tif pix_url is not None:\n\t\t\tprint(\"Downloaded with googlesearch: \" +channel_name)\n\t\t\treturn pix_url\t\n\t\telse:\n\t\t\treturn vdrlogo.not_found_URL\n\t\t\n\texcept IndexError:\n\t\tprint(\"Not found on Google\")\n\t\treturn vdrlogo.not_found_URL\n\n\n","sub_path":"downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"20515435","text":"class CWSMetric(object):\r\n def __init__(self, *names):\r\n super(CWSMetric, self).__init__()\r\n self.names = names\r\n self.sum_metric = None\r\n self.num_inst = None\r\n self.reset()\r\n \r\n\r\n def update(self, pred, label):\r\n assert isinstance(pred, list) or isinstance(pred, tuple), 'pred should be list or tuple'\r\n assert isinstance(label, list) or isinstance(label, tuple), 'label should be list or tuple'\r\n pred = set(pred)\r\n label = set(label)\r\n n = len(pred & label)\r\n N = len(label)\r\n M = len(pred)\r\n for i, name in enumerate(self.names):\r\n if name == 'P':\r\n self.sum_metric[i] += float(n)/float(N)\r\n elif name == 'R':\r\n self.sum_metric[i] += float(n)/float(M)\r\n elif name == 'F1':\r\n P = float(n)/(float(N) + 1e-7)\r\n R = float(n)/(float(M) + 1e-7)\r\n self.sum_metric[i] += 2 * P * R / (P + R+ 1e-7)\r\n self.num_inst += 1\r\n\r\n def reset(self):\r\n if self.sum_metric is None:\r\n self.sum_metric = [0] * len(self.names)\r\n else:\r\n assert len(self.metric) == len(self.names)\r\n for metric in self.sum_metric:\r\n metric = 0\r\n self.num_inst = 0\r\n\r\n def get(self, name=None):\r\n if name is not None:\r\n assert name in self.names\r\n return (name, self.sum_metric[self.names.find(name)] / self.num_inst)\r\n else:\r\n return self.getall()\r\n \r\n\r\n def getall(self):\r\n if self.num_inst == 0:\r\n return zip(self.names, [float('nan')] * len(self.names))\r\n else:\r\n return zip(self.names, [metric / self.num_inst for metric in self.sum_metric])","sub_path":"Metric.py","file_name":"Metric.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"459698647","text":"\n\nclass MAStrategy:\n def __init__(self, priceInfos):\n self.priceInfos = priceInfos # 按照最新(离当前时间最近)到最旧的顺序传入\n\n def calc_average_price(self, ma_days, priceInfos):\n if not ma_days:\n print('ma_days is null')\n return False\n if not self.priceInfos:\n print('priceInfos is null')\n return False\n if not priceInfos:\n priceInfos = self.priceInfos\n if len(priceInfos) < 6:\n print('priceInfos is', len(priceInfos), ', not enough')\n return False\n\n\n totalPrice = 0.0\n count = 1\n for priceInfo in priceInfos:\n if count > ma_days:\n break\n\n totalPrice += priceInfo.price\n count += 1\n averagePrice = totalPrice / ma_days\n return averagePrice\n\n # do strategy\n def do(self, ma_days):\n newest_ma = self.do_latest_day(ma_days)\n second_ma = self.do_last_day(ma_days, self.priceInfos[1:])\n\n if len(self.priceInfos) < 2:\n return False\n # add price limit\n newest_price = self.priceInfos[0].price\n second_price = self.priceInfos[1].price\n is_add_percent_good = False\n diff_price = newest_price - second_price\n if diff_price / second_price > 0.016:\n is_add_percent_good = True\n return newest_ma and second_ma and is_add_percent_good\n\n # 最新日\n def do_latest_day(self, ma_days, priceInfos = None):\n if not priceInfos:\n priceInfos = self.priceInfos\n average_price = self.calc_average_price(ma_days, priceInfos)\n if not average_price:\n return False\n\n newestPrice = priceInfos[0].price\n diffPrice = newestPrice - average_price\n if diffPrice < 0:\n return False # 坚决不要低于5日均线的\n diffPercent = diffPrice / average_price\n if diffPercent < 0.06 and diffPercent > 0.01: # 暂定\n #if diffPercent < 0.03 : # 暂定\n return True\n return False\n\n # 上一日\n def do_last_day(self, ma_days, priceInfos):\n if not priceInfos:\n return False\n average_price = self.calc_average_price(ma_days, priceInfos)\n if not average_price:\n return False\n price = priceInfos[0].price\n diffPrice = price - average_price\n if diffPrice < 0:\n return False # 坚决不要closePrice低于5日均线的\n diffPercent = diffPrice / average_price\n if diffPercent < 0.03 and diffPercent > 0.005: # 暂定,这个值动态可调\n return True\n return False\n","sub_path":"GCF/strategy/MAStrategy.py","file_name":"MAStrategy.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"603205229","text":"from misc.singleton import Singleton\nfrom tools.copyfiles.config import Config\n\n\n@Singleton\nclass SourcesHandlersFactory:\n \"\"\" Factory class that creates the sources and handlers from the configuration, conveniently grouped together.\"\"\"\n\n def __init__(self):\n \"\"\" Default constructor that gets the sources and handlers from a configuration. \"\"\"\n self._config = Config.instance()\n self._sourceshandlers = self._config.sources_handlers\n\n @property\n def sources_handlers(self):\n \"\"\" @property-decorated method that retrieves the sources and handlers objects.\"\"\"\n return self._sourceshandlers\n","sub_path":"tools/copyfiles/sourceshandlersfactory.py","file_name":"sourceshandlersfactory.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"183984275","text":"import rospy\nfrom std_msgs.msg import Int32\nfrom sensor_msgs.msg import LaserScan\nfrom nav_msgs.msg import Odometry\nimport random\nfrom map import Map, Lane\n\nclass LaneChange:\n\n def __init__(self):\n rospy.init_node(\"current_lane\", anonymous=False)\n self.rate = rospy.Rate(10)\n self.lane_publisher = rospy.Publisher(\"/current_lane\", Int32, queue_size=10)\n self.laser_scan_sub = rospy.Subscriber(\"/sensors/rplidar/scan\", LaserScan, self.laser_scan, queue_size=10)\n self.localization_sub = rospy.Subscriber(\"/sensors/localization/filtered_map\", Odometry, self.localization, queue_size=1)\n\n self.rate = rospy.Rate(100)\n self.scan = LaserScan()\n self.pose = Odometry()\n self.lanes = [0,1]\n self.lane = random.choice(self.lanes)\n\n self.timer = rospy.Timer(rospy.Duration.from_sec(0.01), self.on_control) \n \n while not rospy.is_shutdown():\n self.rate.sleep()\n\n def laser_scan(self, msg):\n self.scan = msg\n \n def localization(self, msg):\n self.pose = msg\n\n def is_obstacle(self):\n\n current_position = np.array([self.pose.pose.pose.position.x, self.pose.pose.pose.position.y])\n orientation_angle = 2*np.arccos(self.pose.pose.pose.orientation.w)*np.sign(self.pose.pose.pose.orientation.z)\n transformation_matrix = np.array([[np.cos(orientation_angle), -np.sin(orientation_angle), 0, current_position[0]], [np.sin(orientation_angle), np.cos(orientation_angle), 0, current_position[1]], [0, 0, 1, 0], [0, 0, 0, 1]])\n \n scan_points_MapFrame = np.zeros((len(self.ranges),2))\n for r in range(len(self.ranges)):\n scan_point = np.array([self.ranges[r] * np.cos(self.scan.angle_min + r * self.scan.angle_increment), self.ranges[r] * np.sin(self.scan.angle_min + r * self.scan.angle_increment), 0, 1])\n scan_point_MapFrame = np.dot(transformation_matrix, scan_point)\n scan_points_MapFrame[r,:] = scan_point_MapFrame[:2]\n\n map = Map()\n closest_point_car, _ = map.lanes[self.lane].closest_point(current_position)\n closest_point_scan = np.zeros((scan_points_MapFrame.shape[0],2))\n for i in range(closest_point_scan.shape[0]):\n closest_point_scan[i,:] = map.lanes[self.lane].closest_point(scan_points_MapFrame[i,:])[0]\n\n distances = np.zeros((len(self.ranges),2))\n for d in range(distances.shape[0]):\n distances[d,:] = np.sqrt((closest_point_scan[d,0] - closest_point_car[0,0])**2 + (closest_point_scan[d,1] - closest_point_car[0,1])**2)\n \n if np.any(np.any(distances < 0.15, axis=1)):\n self.lane = list(self.lanes[i] for i in self.lanes if self.lanes[i] != self.lane)[0]\n else:\n self.lane = self.lane\n \n self.lane_publisher.publish(data = self.lane) \n \n \nif __name__ == \"__main__\":\n LaneChange()\n","sub_path":"src/asgn12/src/lane_change.py","file_name":"lane_change.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"593249232","text":"import torch\nfrom torch.nn.functional import (softmax)\nfrom sklearn.metrics import (roc_auc_score, confusion_matrix, f1_score, average_precision_score)\nimport matplotlib.pyplot as plt\nimport seaborn as sn\nimport numpy as np\n\n\ndef post_process_output(output):\n # implementation based on problem statement\n THRESHOLD = 0.8\n intermediate = torch.sigmoid(output) > THRESHOLD\n # intermediate = output > THRESHOLD\n \n return intermediate.float()\n\n# def post_process_output(output):\n# # implementation based on problem statement\n# return softmax(output, dim=1)\n\n\ndef onehot_converter(V, classes):\n # Create zero vector of desired shape\n OHV = torch.zeros((V.size()[0], classes))\n\n # Convert from ndarray to array\n V_a = V.view(-1)\n\n # Fill ones where the label as index\n OHV[range(V.size()[0]), V_a.long()] = 1\n\n return OHV\n\ndef mAP(output_list, target_list):\n output_list = torch.sigmoid(output_list)\n AP_score = average_precision_score(\n target_list.numpy(),\n output_list.numpy(),\n average=None\n )\n mAP_score = AP_score.mean()\n return mAP_score\n\ndef acc(output_list, target_list):\n acc = torch.argmax(target_list, dim=1).eq(torch.argmax(post_process_output(output_list), dim=1))\n return 1.0 * torch.sum(acc.int()).item() / output_list.size()[0]\n\n\ndef f1(output_list, target_list, threshold=0.8):\n output_list = torch.sigmoid(output_list) > threshold\n # output_list = output_list > threshold\n\n output_list = output_list.float().numpy()\n target_list = target_list.float().numpy()\n return f1_score(target_list, output_list, average=\"samples\")\n\ndef f1best(output_list,target_list,threshold=0.5):\n score=0\n for th in np.linspace(0.5,0.9,20):\n out = torch.sigmoid(output_list) > threshold\n out = out.float().numpy()\n target_list = target_list.float().numpy()\n score=max(score,f1_score(target_list, out, average=\"samples\"))\n return score\n\ndef aroc(output_list, target_list):\n output_list = post_process_output(output_list)\n target_list = onehot_converter(target_list, output_list.shape[1])\n return roc_auc_score(\n target_list.numpy(),\n output_list.numpy(),\n average=\"macro\"\n )\n\n\ndef confusion_matrix_generator(output_list, target_list, experiment_name):\n output_list = post_process_output(output_list)\n matrix = confusion_matrix(\n torch.argmax(target_list, dim=1).numpy(),\n torch.argmax(output_list, dim=1).numpy()\n )\n\n labels = ['H', 'MD', 'R', 'S']\n plt.figure()\n figure = sn.heatmap(matrix, xticklabels=labels,\n yticklabels=labels, annot=True)\n plt.savefig('./results/' + experiment_name + '/confusion_matrix.jpg')\n","sub_path":"utils/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"405467807","text":"# Citation 550 - Linear simulation\r\n\r\n# xcg = 0.25 * c\r\n\r\nimport numpy as np\r\nfrom flight_parameters import flight_parameters\r\nfrom data_extractor import data_extractor\r\nimport control.matlab as control \r\nfrom fuel_calc import fuel_calc\r\nfrom postflightdata import post_flight_data\r\n\r\n'''Choose Time'''\r\nt0 = 1200\r\n\r\n''' Getting the flight data from both sources''' \r\nflightdata = data_extractor() \r\ntestdata = post_flight_data()\r\n# (h,m,theta,alpha,tdata,t)\r\n''' Getting the time data from the flight data ''' \r\ntimedata = flightdata.get('time') \r\n\r\n''' Example of plotting two variables against eachother ''' \r\nvariable1 = flightdata.get('time') \r\nvariable2 = flightdata.get('delta_a')\r\nalt = flightdata.get('Dadc1_bcAlt')\r\n\r\n''' Calculating the fuel left in the tanks ''' \r\nfuel_used_l = flightdata.get('lh_engine_FU') \r\nfuel_used_r = flightdata.get('rh_engine_FU') \r\ninitial_fuel_l = 4050/2\r\ninitial_fuel_r = 4050/2\r\nfuel_mass = fuel_calc(initial_fuel_l, initial_fuel_r, fuel_used_l, fuel_used_r, testdata[-3])\r\n\r\n# Stationary flight condition\r\nflightdata = data_extractor()\r\nfp = flight_parameters(flightdata.get('Dadc1_bcAlt'), fuel_mass[2], flightdata.get('Ahrs1_Pitch'), flightdata.get('vane_AOA'), timedata, t0, flightdata.get('Dadc1_tas'), flightdata.get('Ahrs1_Roll'), flightdata.get('Ahrs1_bRollRate'), flightdata.get('Ahrs1_bYawRate'))\r\nhp0 = post_flight_data()[0] \t # pressure altitude in the stationary flight condition [m]\r\nV = fp[6] # true airspeed in the stationary flight condition [m/sec]\r\nalpha0 = fp[3] # angle of attack in the stationary flight condition [rad]\r\nth0 = fp[2] # pitch angle in the stationary flight condition [rad]\r\n\r\n# Aircraft mass\r\nm = fp[1] # mass [kg]\r\n\r\n# aerodynamic properties\r\ne = 0.8 # Oswald factor [ ]\r\nC_D0 = 0.04 # Zero lift drag coefficient [ ]\r\nC_La = 5.497727037013767 # Slope of CL-alpha curve [ ]\r\n\r\n# Longitudinal stability\r\nC_ma = -0.4521130159681127 #VAN KIM!!!! # longitudinal stabilty [ ]\r\nC_mde = -0.9876726725787773 # elevator effectiveness [ ]\r\n\r\n# Aircraft geometry\r\n\r\nS = 30.00\t # wing area [m^2]\r\nSh = 0.2 * S # stabiliser area [m^2]\r\nSh_S = Sh / S\t # [ ]\r\nlh = 0.71 * 5.968 # tail length [m]\r\nc = 2.0569\t # mean aerodynamic cord [m]\r\nlh_c = lh / c\t # [ ]\r\nb = 15.911\t # wing span [m]\r\nbh = 5.791\t # stabilser span [m]\r\nA = b ** 2 / S # wing aspect ratio [ ]\r\nAh = bh ** 2 / Sh # stabilser aspect ratio [ ]\r\nVh_V = 1\t # [ ]\r\nih = -2 * np.pi / 180 # stabiliser angle of incidence [rad]\r\n\r\n# Constant values concerning atmosphere and gravity\r\n\r\nrho0 = 1.2250 # air density at sea level [kg/m^3] \r\nlam = -0.0065 # temperature gradient in ISA [K/m]\r\nTemp0 = 288.15 # temperature at sea level in ISA [K]\r\nR = 287.05 # specific gas constant [m^2/sec^2K]\r\ng = 9.81 # [m/sec^2] (gravity constant)\r\n\r\n# air density [kg/m^3] \r\nrho = fp[4] \r\nW = m * g # [N] (aircraft weight)\r\n\r\n# Constant values concerning aircraft inertia\r\n\r\nmuc = m / (rho * S * c)\r\nmub = m / (rho * S * b)\r\nKs_xx = 0.019\r\nKs_zz = 0.042\r\nKs_xz = 0.002\r\nKs_yy = 1.25 * 1.114\r\n\r\n# Aerodynamic constants\r\n\r\nC_mac = 0 # Moment coefficient about the aerodynamic centre [ ]\r\nC_Nwa = C_La # Wing normal force slope [ ]\r\nC_Nha = 2 * np.pi * Ah / (Ah + 2) # Stabiliser normal force slope [ ]\r\ndepsda = 4 / (A + 2) # Downwash gradient [ ]\r\n\r\n# Lift and drag coefficient\r\n\r\nC_L = 2 * W / (rho * V ** 2 * S) # Lift coefficient [ ]\r\nC_D = C_D0 + (C_La * alpha0) ** 2 / (np.pi * A * e) # Drag coefficient [ ]\r\n\r\n# Stabiblity derivatives\r\n\r\nC_X0 = W * np.sin(th0) / (0.5 * rho * V ** 2 * S)\r\nC_Xu = -0.02792\r\nC_Xa = -0.47966\r\nC_Xadot = +0.08330\r\nC_Xq = -0.28170\r\nC_Xde = -0.03728\r\n\r\nC_Z0 = -W * np.cos(th0) / (0.5 * rho * V ** 2 * S)\r\nC_Zu = -0.37616\r\nC_Za = -5.74340\r\nC_Zadot = -0.00350\r\nC_Zq = -5.66290\r\nC_Zde = -0.69612\r\n\r\nC_mu = +0.06990\r\nC_madot = +0.17800\r\nC_mq = -8.79415\r\n\r\nC_Yb = -0.7500\r\nC_Ybdot = 0 \r\nC_Yp = -0.0304\r\nC_Yr = +0.8495\r\nC_Yda = -0.0400\r\nC_Ydr = +0.2300\r\n\r\nC_lb = -0.10260\r\nC_lp = -0.71085\r\nC_lr = +0.23760\r\nC_lda = -0.23088\r\nC_ldr = +0.03440\r\n\r\nC_nb = +0.1348\r\nC_nbdot = 0 \r\nC_np = -0.0602\r\nC_nr = -0.2061\r\nC_nda = -0.0120\r\nC_ndr = -0.0939\r\n\r\nD_c = c/V\r\nD_b = b/V\r\nmu_c = m/(rho*S*c)\r\nmu_b = m/(rho*S*b)\r\n\r\n'''Symmetrical'''\r\nPsym = np.matrix([[-2*mu_c*D_c/V, 0, 0, 0], \r\n [0, (C_Zadot-2*mu_c)*D_c, 0, 0], \r\n [0, 0, -D_c, 0], \r\n [0, C_madot*D_c, 0, -2*mu_c*Ks_yy*D_c*D_c]]) \r\n \r\nQsym = -1*np.matrix([[C_Xu/V, C_Xa, C_Z0, 0], \r\n [C_Zu/V, C_Za, C_X0, (C_Zq+2*mu_c)*D_c], \r\n [0, 0, 0, 1*D_c], \r\n [C_mu/V, C_ma, 0, C_mq*D_c]]) \r\n \r\nRsym = np.matrix([[-C_Xde], \r\n [-C_Zde], \r\n [0], \r\n [-C_mde]]) \r\n\r\n'''Asymmetrical''' \r\nPasym = np.matrix([[(C_Ybdot-2*mu_b)*D_b, 0, 0, 0], \r\n [0, -0.5*D_b, 0, 0], \r\n [0, 0, -4*mu_b*Ks_xx*D_b*D_b/2, 4*mu_b*Ks_xz*D_b*D_b/2], \r\n [C_nbdot*D_b, 0, 4*mu_b*Ks_xz*D_b*D_b/2, -4*mu_b*Ks_zz*D_b*D_b/2]]) \r\n \r\nQasym = -1*np.matrix([[C_Yb, C_L, C_Yp*D_b/2, (C_Yr-4*mu_b)*D_b/2], \r\n [0, 0, -1*D_b/2, 0],\r\n [C_lb, 0, C_lp*D_b/2, C_lr*D_b/2], \r\n [C_nb, 0, C_np*D_b/2, C_nr*D_b/2]]) \r\n \r\nRasym = np.matrix([[-C_Yda, -C_Ydr], \r\n [0,0], \r\n [-C_lda, -C_ldr], \r\n [-C_nda, -C_ndr]]) \r\n\r\n#Symmetrical Case \r\nA = np.linalg.inv(Psym)*Qsym \r\nB = np.linalg.inv(Psym)*Rsym \r\nC = np.identity(4) \r\nD = np.zeros((4,1)) #Only elevator \r\nsymsys = control.ss(A,B,C,D) \r\n\r\n#Asymmetrical Case \r\nA = np.linalg.inv(Pasym)*Qasym \r\nB = np.linalg.inv(Pasym)*Rasym \r\nC = np.identity(4) \r\nD = np.zeros((4,2)) #Because both aileron and rudder displacement \r\nasymsys = control.ss(A,B,C,D) \r\n\r\nprint(symsys,asymsys)","sub_path":"Cit_par.py","file_name":"Cit_par.py","file_ext":"py","file_size_in_byte":6336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"60369055","text":"\"\"\"\nCreated by : Team Unique Tech for ITSP, IIT Bombay\n\nThe below code is for storing the signal data coming from the electrical circuit through the RaspberryPi. \nThe code creates arrays for data collected from the RaspberryPi. \n\n\"\"\"\n\nimport numpy as np\nimport time\nfrom math import pi\nfrom adc_read import read_val\n\n# some fundamental definitions and variables\n\n# T = time interval (in s) for which the input is taken\nn = 400000 # number of samples or number of data points (will represent sound intensity in 10-bits)\n# dt = T/n time interval (in s) between two readings\n# df = 1/T fundamental frequency of the fft\n# dw = 2*pi*df fundamental angular frequency of the fft\n# ny = df*n/2 nyquist frequency (or the top frequency)\nfreq = 2000 # frequency of the sound-source \n\ndef data():\n\tmic_data_0 = np.array([]) # used to store data from mic1 for 'n' sample points\n\tmic_data_1 = np.array([]) # ----------\"\"----------- mic2 ---------\"\"----------\n\tmic_data_2 = np.array([]) # ----------\"\"----------- mic3 ---------\"\"----------\n\tmic_data_3 = np.array([]) # ----------\"\"----------- mic4 ---------\"\"----------\n\n\tt_axis = np.array([]) # used to create the time axis for data obtained through mic\n\n\ttemp = n\n\tt_start = time.time()\n\n\twhile(temp>0):\n\n\t\ttemp -= 1\n\t\t# take the input from the mics through read_val and store it in the array\n\t\tt_now = time.time()\n\t\tt_delay = t_now - t_start # calculating the delay from the start of loop (/the point after which readings were taken)\n\t\tt_axis = np.append(t_axis, t_delay) # update the t_axis array\n\t\t\n\t\n\treturn mic_data_0, mic_data_1, mic_data_2, mic_data_3\n","sub_path":"data_storage.py","file_name":"data_storage.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"69147918","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Polygon\n\n\n# 定义函数\ndef func(x):\n return 0.5 * np.exp(x) + 1\n\n\n# 定义积分区间\nx = np.linspace(0, 2)\ny = func(x)\n# 绘制函数图形\nfig, ax = plt.subplots()\nplt.plot(x, y, 'b', lw=2)\nplt.ylim(ymin=0)\n# 生成阴影部分\na, b = 0.5, 1.5\nIx = np.linspace(a, b)\nIy = func(Ix)\nverts = [(a, 0)] + list(zip(Ix, Iy)) + [(b, 0)]\npoly = Polygon(verts, facecolor='07', edgecolor='0.5')\nax.add_patch(poly)\n# 用plt.text和plt.figtext在图形上添加公式和坐标轴标签\nplt.text(0.5 * (a + b), 1, r\"$\\int_a^b f(x)\\mathrm{d}x$\", horizontalalignment='center', fontsize=20)\nplt.figtext(0.9, 0.075, '$x$')\nplt.figtext(0.075, 0.9, '$f(x)$')\n# 设置刻度标签\nax.set_xticks((a, b))\nax.set_xticklabels(('$a$', '$b$'))\nax.set_yticks([func(a), func(b)])\nax.set_yticklabels(('$f(a)$', '$(b)$'))\n\nplt.grid()\nplt.show()\n\n","sub_path":"matplotlib/view8_func.py","file_name":"view8_func.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"430703322","text":"import os\n\n\nDATABASE_URL = os.environ['DATABASE_URL']\n\nDEFAULT_FLOAT_PRECISION = 1\nDEFAULT_USE_EMOJI_PAGINATOR = True\n\nEMPTY_LINE = '\\u200b'\n\nEXCEL_COLUMN_FORMAT_DATETIME = 'YYYY-MM-DD hh:MM:ss'\nEXCEL_COLUMN_FORMAT_NUMBER = '0'\n\nGPAT = os.environ['GPAT']\n\nMAXIMUM_CHARACTERS = 1900\nMIN_ENTITY_NAME_LENGTH = 3\n\nPREFIX_DEFAULT = '/'\nPSS_ABOUT_FILES = ['src/data/about.txt', 'data/about.txt']\nPSS_LINKS_FILES = ['src/data/links.json', 'data/links.json']\n\nSETTINGS_TABLE_NAME = 'settings'\nSETTINGS_TYPES = ['boolean','float','int','text','timestamputc']\n\nUSE_EMBEDS = False\n\nVERSION = '1.2.2.5'\n\nWIKIA_BASE_ADDRESS = 'https://pixelstarships.fandom.com/wiki/'","sub_path":"src/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"65630374","text":"from django.conf.urls import url\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns=[\n url('^$',views.index,name='index'),\n url(r'^search/', views.search_results, name='search_results'),\n url(r'^profile/',views.profile,name='profile'),\n url(r'^edit/profile$',views.edit_profile,name='edit-profile'),\n url(r'^rate/', views.rate, name='rate'),\n\n url(r'^new/project$', views.new_project, name='new-project'),\n url(r'^project/(\\d+)',views.project,name ='project'),\n url(r'^projectdetails/(\\d+)',views.projectdetails,name ='projectdetails'),\n url(r'^api/project/$', views.ProjectList.as_view()),\n url(r'^api/profile/$', views.ProfileList.as_view()),\n\n\n]\n\nif settings.DEBUG:\n urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)\n","sub_path":"rate/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"199287440","text":"import os\nfrom pprint import pprint\n\nfrom lxml import etree\nfrom tqdm import tqdm\n\n\ndef main(input_dir):\n files = [ead for ead in os.listdir(input_dir) if ead.endswith(\".xml\")]\n\n analogs = {}\n\n for ead in tqdm(files):\n tree = etree.parse(os.path.join(input_dir, ead))\n extents = tree.xpath(\"//extent\")\n for extent in extents:\n analog = extent.attrib.get(\"encodinganalog\", \"\")\n analogs[analog] = analogs.get(analog, 0) + 1\n\n pprint(analogs)\n\nif __name__ == \"__main__\":\n input_dir = r'C:\\Users\\wboyle\\PycharmProjects\\vandura\\Real_Masters_all'\n main(input_dir)\n","sub_path":"one-off scripts/get_extent_encodinganalogs.py","file_name":"get_extent_encodinganalogs.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"89887132","text":"import os\nimport tempfile\nfrom test.data import (\n TEST_DATA_DIR,\n bob,\n cheese,\n context0,\n context1,\n context2,\n likes,\n michel,\n pizza,\n tarek,\n)\n\nimport pytest\nfrom rdflib import RDFS, XSD, BNode, Literal, Namespace, URIRef\nfrom rdflib.graph import DATASET_DEFAULT_GRAPH_ID, Dataset, Graph\nfrom rdflib.store import CORRUPTED_STORE, NO_STORE, VALID_STORE\n\nfrom FuXi.sqlstore.sqlitestore import SQLiteStore\n\nstore_name = \"SQLiteStore\"\npath = str(TEST_DATA_DIR / \"sqlitedb.sqlite3\")\n\n\n@pytest.fixture(scope=\"function\")\ndef sqlitedb(request):\n\n if os.path.exists(path):\n try:\n os.remove(path)\n except Exception:\n pass\n\n store = SQLiteStore(identifier=BNode(\"test\"))\n\n try:\n rt = store.open(path=path)\n assert rt == VALID_STORE, \"The underlying store is corrupt\"\n\n except Exception as e:\n os.remove(path)\n raise Exception(e)\n\n yield store\n\n try:\n os.remove(path)\n except Exception:\n pass\n\n\ndef test_store_create():\n\n path = str(TEST_DATA_DIR / \"sqlitedb.sqlite3\")\n\n sqlitedb = SQLiteStore(identifier=\"test\")\n\n try:\n rt = sqlitedb.open(path=path)\n assert rt == VALID_STORE, \"The underlying store is corrupt\"\n\n except Exception as e:\n os.remove(path)\n raise Exception(e)\n\n os.remove(path)\n\n\ndef test_graph_create_with_file_extension(sqlitedb):\n\n xpath = str(TEST_DATA_DIR / \"sqlitedb.sqlite3\")\n\n g = Dataset(store=store_name)\n\n try:\n rt = g.open(configuration=xpath)\n assert rt == NO_STORE, \"The underlying store is corrupt\"\n\n except Exception:\n\n try:\n rt = g.open(configuration=xpath)\n assert rt == CORRUPTED_STORE, \"The underlying store is NOT corrupt\"\n\n try:\n os.remove(xpath)\n except Exception as e:\n raise Exception(e)\n\n except Exception as e:\n raise Exception(e)\n\n try:\n os.remove(xpath)\n except Exception:\n pass\n\n\ndef test_graph_create(sqlitedb):\n\n path = str(TEST_DATA_DIR / \"sqlitedb\")\n\n g = Dataset(store=store_name)\n\n try:\n rt = g.open(configuration=path)\n assert rt == NO_STORE, \"The underlying store is corrupt\"\n\n except Exception as e:\n os.remove(path)\n raise Exception(e)\n\n try:\n os.remove(path)\n except Exception:\n pass\n\n\ndef test_graph_missing_db_returns_no_store():\n\n sqlitestore = SQLiteStore(identifier=\"test\")\n assert sqlitestore.open(\"nowhere\", create=False) == NO_STORE\n\n\ndef test_store_open_close_reopen():\n\n sqlitestore = SQLiteStore(identifier=\"test\")\n\n try:\n rt = sqlitestore.open(path=path)\n assert rt == VALID_STORE, \"The underlying store is corrupt\"\n\n except Exception as e:\n os.remove(path)\n raise Exception(e)\n\n sqlitestore.add((tarek, likes, pizza), context0)\n sqlitestore.commit()\n\n assert len(sqlitestore) == 1\n\n sqlitestore.close()\n\n try:\n rt = sqlitestore.open(path=path, create=False)\n assert rt == VALID_STORE, \"The underlying store is corrupt\"\n\n except Exception as e:\n os.remove(path)\n raise Exception(e)\n\n assert len(sqlitestore) == 1\n\n try:\n os.remove(path)\n except Exception:\n pass\n\n\ndef test_store_namespace_binding(sqlitedb):\n uri = \"https://example.org/\"\n pfx = \"ex\"\n\n sqlitedb.bind(pfx, Namespace(uri))\n\n assert (pfx, uri) in list(sqlitedb.namespaces())\n\n\ndef test_store_namespace(sqlitedb):\n uri = \"https://example.org/\"\n ns = URIRef(uri)\n pfx = \"ex\"\n sqlitedb.bind(pfx, ns)\n\n assert sqlitedb.namespace(pfx) == uri\n\n\ndef test_store_prefix(sqlitedb):\n uri = \"https://example.org/\"\n ns = URIRef(uri)\n pfx = \"ex\"\n sqlitedb.bind(pfx, ns)\n\n assert sqlitedb.prefix(ns) == pfx\n\n\ndef test_store_write(sqlitedb):\n\n sqlitedb.add((tarek, likes, pizza), context0)\n sqlitedb.commit()\n\n assert len(sqlitedb) == 1\n\n\ndef test_store_write_idempotency(sqlitedb):\n\n sqlitedb.add((tarek, likes, pizza), context0)\n sqlitedb.commit()\n\n assert len(sqlitedb) == 1\n assert list(sqlitedb) == [\n (\n URIRef(\"urn:example:tarek\"),\n URIRef(\"urn:example:likes\"),\n URIRef(\"urn:example:pizza\"),\n URIRef(\"urn:example:context-0\"),\n )\n ]\n\n # Idempotency of re-added statements\n sqlitedb.add((tarek, likes, pizza), context0)\n sqlitedb.commit()\n\n assert list(sqlitedb) == [\n (\n URIRef(\"urn:example:tarek\"),\n URIRef(\"urn:example:likes\"),\n URIRef(\"urn:example:pizza\"),\n URIRef(\"urn:example:context-0\"),\n ),\n ]\n\n\ndef test_store_write_after_commit(sqlitedb):\n\n sqlitedb.add((tarek, likes, pizza), context0)\n sqlitedb.commit()\n\n assert len(sqlitedb) == 1\n assert list(sqlitedb) == [\n (\n URIRef(\"urn:example:tarek\"),\n URIRef(\"urn:example:likes\"),\n URIRef(\"urn:example:pizza\"),\n URIRef(\"urn:example:context-0\"),\n )\n ]\n\n sqlitedb.add((tarek, likes, michel), context0)\n sqlitedb.commit()\n\n assert list(sqlitedb) == [\n (\n URIRef(\"urn:example:tarek\"),\n URIRef(\"urn:example:likes\"),\n URIRef(\"urn:example:michel\"),\n URIRef(\"urn:example:context-0\"),\n ),\n (\n URIRef(\"urn:example:tarek\"),\n URIRef(\"urn:example:likes\"),\n URIRef(\"urn:example:pizza\"),\n URIRef(\"urn:example:context-0\"),\n ),\n ]\n\n\ndef test_store_iter_as_quads(sqlitedb):\n\n sqlitedb.add((tarek, likes, pizza), context0)\n sqlitedb.commit()\n\n assert len(sqlitedb) == 1\n\n assert list(sqlitedb) == [\n (\n URIRef(\"urn:example:tarek\"),\n URIRef(\"urn:example:likes\"),\n URIRef(\"urn:example:pizza\"),\n URIRef(\"urn:example:context-0\"),\n )\n ]\n\n\ndef test_store_triples(sqlitedb):\n\n sqlitedb.add((tarek, likes, pizza), context0)\n sqlitedb.commit()\n\n assert len(sqlitedb) == 1\n\n assert list(sqlitedb.triples((None, None, None)))[0][:2][0] == (\n URIRef(\"urn:example:tarek\"),\n URIRef(\"urn:example:likes\"),\n URIRef(\"urn:example:pizza\"),\n )\n\n\ndef test_store_add_triple(sqlitedb):\n\n triple = (tarek, likes, pizza)\n\n sqlitedb.add(triple, context0)\n sqlitedb.commit()\n\n assert len(sqlitedb) == 1\n\n assert list(sqlitedb.triples((None, None, None)))[0][:2][0] == (\n URIRef(\"urn:example:tarek\"),\n URIRef(\"urn:example:likes\"),\n URIRef(\"urn:example:pizza\"),\n )\n\n\ndef test_store_remove_triple(sqlitedb):\n\n triple = (tarek, likes, pizza)\n\n sqlitedb.add(triple, context0)\n sqlitedb.commit()\n\n assert len(sqlitedb) == 1\n\n assert list(sqlitedb.triples((None, None, None)))[0][:2][0] == (\n URIRef(\"urn:example:tarek\"),\n URIRef(\"urn:example:likes\"),\n URIRef(\"urn:example:pizza\"),\n )\n\n sqlitedb.remove(triple, context0)\n\n assert len(sqlitedb) == 0\n\n assert list(sqlitedb.triples((None, None, None))) == []\n\n\ndef test_store_addn(sqlitedb):\n\n triple1 = (tarek, likes, pizza, context0)\n triple2 = (tarek, likes, cheese, context0)\n triple3 = (michel, likes, pizza, context1)\n triple4 = (michel, likes, cheese, context1)\n\n triples = [triple1, triple2, triple3, triple4]\n\n sqlitedb.addN(triples)\n sqlitedb.commit()\n\n assert len(sqlitedb) == 4\n\n assert sorted(list(sqlitedb)) == [\n (\n URIRef(\"urn:example:michel\"),\n URIRef(\"urn:example:likes\"),\n URIRef(\"urn:example:cheese\"),\n URIRef(\"urn:example:context-1\"),\n ),\n (\n URIRef(\"urn:example:michel\"),\n URIRef(\"urn:example:likes\"),\n URIRef(\"urn:example:pizza\"),\n URIRef(\"urn:example:context-1\"),\n ),\n (\n URIRef(\"urn:example:tarek\"),\n URIRef(\"urn:example:likes\"),\n URIRef(\"urn:example:cheese\"),\n URIRef(\"urn:example:context-0\"),\n ),\n (\n URIRef(\"urn:example:tarek\"),\n URIRef(\"urn:example:likes\"),\n URIRef(\"urn:example:pizza\"),\n URIRef(\"urn:example:context-0\"),\n ),\n ]\n\n\ndef test_store_list_all_contexts(sqlitedb):\n\n triple1 = (tarek, likes, pizza)\n\n triple2 = (michel, likes, pizza)\n\n sqlitedb.add(triple1, context=None)\n\n sqlitedb.add(triple1, context0)\n\n sqlitedb.add(triple2, context1)\n\n sqlitedb.commit()\n\n contexts = list(sqlitedb.contexts())\n\n assert contexts == [\n URIRef(\"urn:example:context-0\"),\n URIRef(\"urn:example:context-1\"),\n URIRef(\"urn:x-rdflib:default\"),\n ]\n\n\ndef test_store_contexts_using_triplepattern(sqlitedb):\n\n triple1 = (tarek, likes, pizza)\n\n triple2 = (michel, likes, pizza)\n\n sqlitedb.add(triple1, context=None)\n\n sqlitedb.add(triple1, context0)\n\n sqlitedb.add(triple2, context1)\n\n sqlitedb.commit()\n\n contexts = list(sqlitedb.contexts())\n\n contexts = list(sqlitedb.contexts(triple1))\n\n assert contexts == [\n URIRef(\"urn:example:context-0\"),\n URIRef(\"urn:x-rdflib:default\"),\n ]\n\n\ndef test_graph_escape_quoting(sqlitedb):\n\n test_string = \"That’s a Literal!!\"\n sqlitedb.add(\n (\n URIRef(\"http://example.org/foo\"),\n RDFS.label,\n Literal(test_string, datatype=XSD.string),\n ),\n context0,\n )\n sqlitedb.commit()\n\n striples = list(sqlitedb.triples((None, None, None)))\n\n assert \"That’s a Literal!!\" in str(striples)\n\n\ndef test_store_add_graph(sqlitedb):\n\n sqlitedb.add_graph(context1)\n\n assert list(sqlitedb.contexts()) == []\n\n\ndef test_store_remove_graph(sqlitedb):\n\n triple = (tarek, likes, pizza)\n\n sqlitedb.add(triple, context1)\n sqlitedb.commit()\n\n assert list(sqlitedb.contexts()) == [URIRef(\"urn:example:context-1\")]\n\n sqlitedb.remove_graph(context1)\n\n assert list(sqlitedb.contexts()) == []\n\n\ndef test_graph_namespaces(sqlitedb):\n\n graph = Graph(store=sqlitedb)\n\n no_of_default_namespaces = len(list(graph.namespaces()))\n\n graph.bind(\"exorg\", \"http://example.org/\")\n graph.bind(\"excom\", \"http://example.com/\")\n\n assert (\n len(list(graph.namespaces())) == no_of_default_namespaces + 2\n ), f\"expected {no_of_default_namespaces + 2}, got {len(list(graph.namespaces()))}\"\n\n assert (\"exorg\", URIRef(\"http://example.org/\")) in list(graph.namespaces())\n\n\ndef test_graph_parse(sqlitedb):\n\n g = Graph(store=sqlitedb)\n\n assert (\n len(g) == 0\n ), \"There must be zero triples in the graph just after store (file) creation\"\n\n data = \"\"\"\n PREFIX : \n\n :a :b :c .\n :d :e :f .\n :d :g :h .\n \"\"\"\n g.parse(data=data, format=\"ttl\")\n\n assert len(g) == 3\n\n\ndef test_open_shut():\n\n if os.path.exists(path):\n try:\n os.remove(path)\n except Exception:\n pass\n\n sqlitestore = SQLiteStore(identifier=BNode(\"test\"))\n sqlitestore.open(path, create=True)\n\n g = Graph(store=sqlitestore, identifier=DATASET_DEFAULT_GRAPH_ID)\n\n leng = len(g)\n\n assert (\n leng == 0\n ), \"There must be zero triples in the graph just after store (file) creation\"\n\n data = \"\"\"\n PREFIX : \n\n :a :b :c .\n :d :e :f .\n :d :g :h .\n \"\"\"\n\n g.parse(data=data, format=\"ttl\")\n\n assert list(g.store) == [\n (\n URIRef(\"https://example.org/a\"),\n URIRef(\"https://example.org/b\"),\n URIRef(\"https://example.org/c\"),\n URIRef(\"urn:x-rdflib:default\"),\n ),\n (\n URIRef(\"https://example.org/d\"),\n URIRef(\"https://example.org/e\"),\n URIRef(\"https://example.org/f\"),\n URIRef(\"urn:x-rdflib:default\"),\n ),\n (\n URIRef(\"https://example.org/d\"),\n URIRef(\"https://example.org/g\"),\n URIRef(\"https://example.org/h\"),\n URIRef(\"urn:x-rdflib:default\"),\n ),\n ]\n\n try:\n g.commit()\n except Exception:\n g.rollback()\n\n leng = len(g)\n\n assert (\n leng == 3\n ), \"There must be three triples in the graph after the first data chunk parse\"\n\n # Double-check store length\n lens = len(g.store)\n\n assert (\n lens == 3\n ), \"There must be three triples in the graph after the first data chunk parse\"\n\n g.close()\n g = None\n\n sqlitestore = SQLiteStore(identifier=\"test\")\n sqlitestore.open(path, create=False)\n\n # reopen the graph\n g = Dataset(store=sqlitestore)\n # g.open(path, create=False)\n\n leng = len(g)\n\n assert (\n leng == 3\n ), \"After close and reopen, we should still have the 3 originally added triples\"\n\n\ndef test_write(sqlitedb):\n\n g = Graph(store=sqlitedb)\n\n leng = len(g)\n\n assert (\n leng == 0\n ), \"There must be zero triples in the graph just after store (file) creation\"\n\n data = \"\"\"\n PREFIX : \n\n :a :b :c .\n :d :e :f .\n :d :g :h .\n \"\"\"\n g.parse(data=data, format=\"ttl\")\n\n leng = len(g)\n\n assert (\n leng == 3\n ), \"There must be three triples in the graph after the first data chunk parse\"\n\n data2 = \"\"\"\n PREFIX : \n\n :d :i :j .\n \"\"\"\n g.parse(data=data2, format=\"ttl\")\n\n leng = len(g)\n assert (\n leng == 4\n ), \"There must be four triples in the graph after the second data chunk parse\"\n\n data3 = \"\"\"\n PREFIX : \n\n :d :i :j .\n \"\"\"\n g.parse(data=data3, format=\"ttl\")\n\n leng = len(g)\n\n assert (\n leng == 4\n ), \"Four triples must remain in the graph after the thrd data chunk parse\"\n\n\ndef test_sparql_query(sqlitedb):\n\n g = Dataset(store=sqlitedb, default_union=True)\n\n data = \"\"\"\n PREFIX : \n\n :a :b :c .\n :d :e :f .\n :d :g :h .\n \"\"\"\n g.parse(data=data, format=\"ttl\")\n\n q = \"\"\"\n PREFIX : \n\n SELECT (COUNT(*) AS ?c)\n WHERE {\n :d ?p ?o .\n }\"\"\"\n\n c = 0\n for row in g.query(q):\n c = int(row.c)\n assert c == 2, \"SPARQL COUNT must return 2\"\n\n\ndef test_sparql_insert(sqlitedb):\n\n g = Graph(store=sqlitedb)\n\n data = \"\"\"\n PREFIX : \n\n :a :b :c .\n :d :e :f .\n :d :g :h .\n \"\"\"\n g.parse(data=data, format=\"ttl\")\n\n q = \"\"\"\n PREFIX : \n\n INSERT DATA {\n :x :y :z .\n }\"\"\"\n\n g.update(q)\n assert len(g) == 4, \"After extra triple insert, length must be 4\"\n\n assert len(g.store) == 4\n\n\ndef test_multigraph(sqlitedb):\n\n g = Dataset(\n store=sqlitedb,\n )\n\n data = \"\"\"\n PREFIX : \n\n :a :b :c .\n :d :e :f .\n :d :g :h .\n \"\"\"\n g.parse(data=data, format=\"ttl\")\n\n q = \"\"\"\n PREFIX : \n\n INSERT DATA {\n GRAPH :m {\n :x :y :z .\n }\n GRAPH :n {\n :x :y :z .\n }\n }\"\"\"\n\n g.update(q)\n\n q = \"\"\"\n SELECT (COUNT(?g) AS ?c)\n WHERE {\n SELECT DISTINCT ?g\n WHERE {\n GRAPH ?g {\n ?s ?p ?o\n }\n }\n }\n \"\"\"\n c = 0\n for row in g.query(q):\n c = int(row.c)\n assert c == 2, \"SPARQL COUNT must return 2 (:m & :n)\"\n\n\ndef test_graph_isopen_db(sqlitedb):\n\n assert sqlitedb.is_open() is True\n sqlitedb.close()\n assert sqlitedb.is_open() is False\n\n\ndef test_dataset_triples_context(\n sqlitedb,\n):\n\n ds = Dataset(store=sqlitedb)\n\n graph = ds.graph(context1)\n\n graph.add((michel, likes, pizza))\n graph.add((michel, likes, cheese))\n\n graph.commit()\n\n triples = list(graph.triples((None, None, None)))\n assert len(triples) == 2, len(triples)\n\n\ndef test_dataset_remove_context_reset(\n sqlitedb,\n):\n\n ds = Dataset(store=sqlitedb)\n\n graph = ds.graph(identifier=context1)\n\n graph.add((michel, likes, pizza))\n graph.add((michel, likes, cheese))\n graph.commit()\n\n triples = list(graph.triples((None, None, None)))\n\n assert len(triples) == 2, len(triples)\n\n graph.remove((michel, likes, cheese))\n graph.remove((michel, likes, pizza))\n\n graph.commit()\n\n triples = list(graph.triples((None, None, None)))\n\n assert len(triples) == 0, len(triples)\n\n\ndef test_dataset_nquads_default_graph(\n sqlitedb,\n):\n data = \"\"\"\n .\n .\n . # noqa: E501\n \"\"\"\n\n public_id = URIRef(\"http://example.org/g0\")\n\n ds = Dataset(store=sqlitedb)\n\n ds.parse(data=data, format=\"nquads\", publicID=public_id)\n\n assert len(ds) == 0 # Nothing in default graph\n\n assert len(ds.get_context(URIRef(\"http://example.org/g3\"))) == 1\n\n # Two contexts: the publicID and one from the quad\n assert len(list(ds.contexts())) == 2, f\"contexts:\\n{list(ds.contexts())}\"\n\n assert len(ds.get_context(public_id)) == 2 # 2 in publicID\n\n\ndef test_dataset_serialize(sqlitedb):\n\n ds1 = Dataset(store=sqlitedb)\n\n ds1.graph(context1).add((bob, likes, pizza))\n ds1.graph(context2).add((bob, likes, pizza))\n\n s = ds1.serialize(format=\"nquads\")\n\n assert len([x for x in s.split(\"\\n\") if x.strip()]) == 2\n\n ds2 = Dataset(store=\"SQLiteStore\")\n\n tmpdb = tempfile.mktemp(prefix=\"sqlitedbstoretest\")\n\n ds2.open(tmpdb, create=True)\n ds2.parse(data=s, format=\"nquads\")\n assert len(ds1) == len(ds2)\n assert sorted(ds1.contexts()) == sorted(ds2.contexts())\n os.remove(tmpdb)\n\n\ndef test_graph_basic(sqlitedb):\n\n ds = Dataset(store=sqlitedb, identifier=context0)\n\n data = \"\"\"\n PREFIX : \n\n :a :b :c .\n :d :e :f .\n :d :g :h .\n \"\"\"\n ds.parse(data=data, format=\"ttl\")\n\n subgraph1 = ds.get_context(context1)\n subgraph2 = ds.get_context(context2) # noqa: F841\n\n triple = (bob, likes, michel)\n\n assert subgraph1.identifier == context1\n\n assert ds.store.is_open()\n\n subgraph1.add(triple)\n\n assert len(subgraph1) == 1\n\n ds.store.add_graph(context1)\n\n assert len(list(ds.triples(triple, context=context1))) == 1\n\n assert len(list(ds.triples(triple, context=ds.identifier))) == 0\n\n assert (\n str(list(ds.store.contexts(triple)))\n == \"[rdflib.term.URIRef('urn:example:context-1')]\" # noqa: W503\n )\n\n assert (\n str(\n list(\n ds.store.contexts(\n (\n URIRef(\"urn:example:harry\"),\n URIRef(\"urn:example:likes\"),\n URIRef(\"urn:example:sally\"),\n )\n )\n )\n )\n == \"[]\" # Trigger KeyError for coverage # noqa: W503\n )\n\n assert ds.store.__len__(context=context1) == 1\n\n assert ds.store.__len__(context=None) == 4\n assert ds.store.__len__(context=None) == 4\n\n assert len(list(ds.store.contexts(triple))) == 1\n\n ds.store.remove(triple, context1)\n\n ds.store.remove((None, None, None), context1)\n\n ds.store.remove((None, None, None), context1)\n\n ds.store.remove((None, None, None), URIRef(\"urn:example:context-2\"))\n\n dsc = list(ds.contexts()) # noqa: F841\n\n assert len(list(ds.contexts())) == 0\n\n subgraph1.add((michel, likes, cheese))\n subgraph1.add((bob, likes, cheese))\n\n ds.store.remove_graph(context1)\n\n assert len(list(ds.store.contexts())) == 1\n\n assert len(list(ds.contexts())) == 0\n\n ds.store.add_graph(context2)\n\n ds.store.add(triple, context2)\n\n ds.store.add(\n (michel, likes, bob),\n context2,\n True,\n )\n\n assert len(list(ds.contexts())) == 1\n\n ds.remove((None, None, None))\n\n ds.store.remove_graph(ds.store.identifier)\n\n if hasattr(ds.store, \"unbind\"):\n nnamespaces = len(list(ds.store.namespaces()))\n ds.store.bind(\"ex\", URIRef(\"urn:exemplar:\"))\n assert len(list(ds.store.namespaces())) == nnamespaces + 1\n ds.store.unbind(\"ex\")\n assert len(list(ds.store.namespaces())) == nnamespaces\n\n ds.parse(data=open(TEST_DATA_DIR / \"timbl-card.n3\", \"r\").read(), format=\"n3\")\n assert len(ds) == 86\n\n ds.remove((None, None, None, None))\n assert len(ds) == 0\n","sub_path":"test/test_sqlitestore/test_sqlitestore_store.py","file_name":"test_sqlitestore_store.py","file_ext":"py","file_size_in_byte":20829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"104792174","text":"from blip_session import BlipSession\n\nbot_auth_key = 'source key'\nrouter_auth_key = 'destination key'\n\nbot_client = BlipSession(bot_auth_key)\nrouter_client = BlipSession(router_auth_key)\n\n\ndef merge_contact(contact, client):\n contact['identity'] = contact['identity'].replace('prd', '')\n client.force_command({\n 'method': 'merge',\n 'uri': '/contacts',\n 'type': 'application/vnd.lime.contact+json',\n 'resource': contact\n })\n\n\ndef get_context_values(identity, client):\n command = client.force_command({\n 'method': 'get',\n 'uri': f'/contexts/{identity}?withContextValues=true&$take=99999'\n })\n command = command['resource']['items']\n command.append({\n 'name': 'master-state',\n 'type': 'text/plain',\n 'value': 'prditauconsorcios@msging.net'\n })\n return command\n\n\ndef set_context_value(identity, name, value, mime_type, client):\n identity = identity.replace('prd', '')\n client.force_command({\n 'method': 'set',\n 'uri': f'/contexts/{identity}/{name}',\n 'type': mime_type,\n 'resource': value\n })\n\n\ncontacts = bot_client.process_command({\n 'method': 'get',\n 'uri': '/contacts?$take=9999'\n})['resource']['items']\nprint(f'found {len(contacts)} contacts')\n\nfor contact in contacts:\n print(f'Merging with router contact {contact[\"identity\"]}')\n merge_contact(contact, router_client)\n\ncontexts = bot_client.process_command({\n 'method': 'get',\n 'uri': '/contexts?$take=9999'\n})['resource']['items']\nprint(f'fount {len(contexts)} contexts')\n\nfor user_context in contexts:\n print(f'Merging with router context {user_context}')\n context = get_context_values(user_context, bot_client)\n print(f'Got {len(context)} context variables')\n [\n set_context_value(\n user_context, c['name'], c['value'], c['type'], router_client)\n for c in context\n ]\n\nprint('Finish!')\n","sub_path":"migrate_users.py","file_name":"migrate_users.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"271838405","text":"# from request import request_data, data_request_complete\r\n\r\n''' The df building functions have been created so that data can\r\n be added intermittently. I plan on only running the\r\n program during the day, so each morning the overnight\r\n data will be requested and then for the rest of the day\r\n only one bar at a time will be requested (upon candle close).\r\n \r\n Each sub function within update_df() runs its own loop\r\n so that it can filter the df down to only calculate\r\n new missing values.\r\n \r\n Trade alerts are controlled via... '''\r\n\r\n# while True:\r\n # request_data()\r\n # if data_request_complete == True:\r\n # update_df()\r\n\r\n\r\n# ... Function Parameters and Settings ...\r\n\r\n\r\n# Confidence Functions: \r\n\r\n# Trend strength / weakness\r\n# (threshold probably won't adapt to a large variety\r\n# of timeframe variation. 1min will need higher values\r\n# than 4h)\r\nmomentum = {'active': True,\r\n 'threshold': 2, \r\n 'weight_multiplier': 1\r\n}\r\n\r\n\r\nauction_volume = {'active': True,\r\n 'weight_multiplier': 1\r\n}\r\n\r\n# Lookback period for average daily price range\r\nadr_window = {'length': 5}\r\n\r\n\r\n# Update DataFrame Functions\r\n\r\n# do these need to be TF specific?\r\ntrade_zones = {'height_multiplier': 0.02,\r\n 'length_multiplier': 8,\r\n 'buffer_multiplier': 0.25\r\n }\r\n\r\nsr_zones = {'height_multiplier': 0.02,\r\n 'length_multiplier': 10,\r\n 'lookback_multiplier': 0.2,\r\n 'buffer_multiplier': 0.25\r\n }\r\n\r\n","sub_path":"cockpit.py","file_name":"cockpit.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"263857937","text":"# K-Means Clustering\n\n# Importing the libraries\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport csv\n\ndf = pd.read_csv('datausers.csv')\n\n#get the userID of the passenger(Frontend fetch)\nUID = 517011168906\n\n#get the index of the row which belongs to particular passenger\nindex = df[df['UID']== UID].index.values.astype(int)[0]\n#print(df.iloc[index]) # print data of the row\n#print(df[df['UID']== UID].iloc[:,11]) # print data of the row\n#print(df[df['UID']== UID].iloc[:,12]) # print data of the row\n#print(df[df['UID']== UID].iloc[:,13]) # print data of the row\n#print(df[df['UID']== UID].iloc[:,14]) # print data of the row\n#print(df[df['UID']== UID].iloc[:,10]) # print data of the row\n\n\n#get the properties of the specified user and assign it to variables\nisSmoking = df[df['UID']== UID].iloc[:,7].values[0]\nisMusicLover = df[df['UID']== UID].iloc[:,8].values[0]\nisMotionSickness = df[df['UID']== UID].iloc[:,9].values[0]\nisLikeQuietness = df[df['UID']== UID].iloc[:,10].values[0]\nisGenderPrefered = df[df['UID']== UID].iloc[:,6].values[0]\n\n\n\n#Defining rules for the filteration\n#todo add more rules - language spoken?\ndef rules(smokingFlag, musicFlag, motionFlag, quietnessFlag, genderFlag):\n\tdf.loc[(df['Smoking'] == smokingFlag) & (df['Music_Lover'] == musicFlag) & (df['Motion_Sickness'] == motionFlag) & (df['Gender_Preference'] == genderFlag) \n\t& (df['Like_Quietness'] == quietnessFlag)].to_csv('newUsers.csv', index=False);\n\t\n\t\n\n#Execute rule based mechanism \nrules(isSmoking, isMusicLover, isMotionSickness, isLikeQuietness, isGenderPrefered);\n\n\ndataset = pd.read_csv('newUsers.csv')\nX = dataset.iloc[:,[3,4]].values # read columns Age-x axis and Profession-y axis\n\n# Using the elbow method to find the optimal number of clusters\n\nfrom sklearn.cluster import KMeans\nwcss =[]\nfor i in range (1,11):\n kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter =200, n_init = 10, random_state = 0)\n kmeans.fit(X)\n wcss.append(kmeans.inertia_) #Within Cluster Sum of Squares\n\n# Plot the graph to visualize the Elbow Method to find the optimal number of cluster \n#plt.plot(range(1,11),wcss)\n#plt.title('The Elbow Method')\n#plt.xlabel('Number of clusters')\n#plt.ylabel('WCSS')\n#plt.show()\n\n# Applying KMeans to the dataset with the optimal number of cluster\n\nkmeans=KMeans(n_clusters = 3, init = 'k-means++', max_iter = 200, n_init = 10, random_state = 0)\nY_Kmeans = kmeans.fit_predict(X)\n#print(kmeans.cluster_centers_) #cluster center points\n#print(kmeans.labels_==1) #cluster center points\n# Visualising the clusters\n\n#get clusters and sort them into new file\ndataset[\"Cluster\"] = Y_Kmeans\ndataset.sort_values(by='Cluster', inplace=True)\ndataset.to_csv('final.csv', index=False)\n\n#specify the cluster where the particular passenger belongs to\nn = dataset[dataset['UID']== UID].iloc[:,11].values[0]\n\n\n#ds = X[np.where(kmeans.labels_== n)] #get particular cluster\n#print(ds)\n#print(dataset.loc[dataset['Cluster'] == n])\n\n#Initialize lists required\nuIDList= list()\nfilteredList=list()\n\ndataListOfSuitableDrivers = dataset.loc[dataset['Cluster'] == n, ['UID']]\nuIDList = dataListOfSuitableDrivers.values.tolist()\n# remove reported drivers from the list(uIDList - entries from db)\n\nprint(uIDList)\n\ndataListOfSuitableDrivers.to_csv('selectedDrivers.csv', index=False)\n#uIDList.append(dataListOfSuitableDrivers.get('UID'))\n\t\n#database call to get reported list for particular UID\n#filteredList = uIDList - [1,2,3,4,5]\n\ndataset = pd.DataFrame(filteredList)\ndataset.to_csv('selectedDrivers.csv')\n#with open(\"selectedDrivers.csv\",\"w\") as f:\n # wr = csv.writer(f,delimiter=\"\\n\")\n # wr.writerow(uIDList)\n\t\n#for x in uIDList:\n\t#print(x) #dummy printing the list\n\t\n#print(dataset[kmeans.labels_== n]) # get dataset in each cluster\n#print(dataset['UID']== UID) # get true for paticular row\n#print(dataset[dataset['UID']== UID].index.values.astype(int)[0]) # get index of row which has UID index\n\n\n\n\t\nplt.scatter(X[Y_Kmeans == 0, 0], X[Y_Kmeans == 0,1],s = 100, c='red', label = 'Cluster 1')\n\nplt.scatter(X[Y_Kmeans == 1, 0], X[Y_Kmeans == 1,1],s = 100, c='blue', label = 'Cluster 2')\n\nplt.scatter(X[Y_Kmeans == 2, 0], X[Y_Kmeans == 2,1],s = 100, c='green', label = 'Cluster 3')\n\n\nplt.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], s = 300, c = 'yellow', label = 'Centroids')\n\n \nplt.title('Clusters of drivers')\nplt.xlabel('Age')\nplt.ylabel('Profession')\nplt.legend()\nplt.show()\n","sub_path":"Viraj/New folder/old.py","file_name":"old.py","file_ext":"py","file_size_in_byte":4442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"6197304","text":"# Crie um programa onde o usuário possa digitar sete valores numéricos\n# e cadastre-os em uma lista única que mantenha separados os valores\n# pares e ímpares. No final, mostre os valores pares e ímpares em ordem\n# crescente.\n\nnumeros = [[], []]\nvalor = 0\nfor num in range(1, 8):\n valor = int(input(f\"Digite o {num}º valor: \"))\n if valor % 2 == 0:\n numeros[0].append(valor)\n else:\n numeros[1].append(valor)\nprint(f\"Valores pares: {sorted(numeros[0])}\")\nprint(f\"Valores ímpares: {sorted(numeros[1])}\")\n\n","sub_path":"e085_ListaParesImpares.py","file_name":"e085_ListaParesImpares.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"385279830","text":"import numpy as np\nimport cv2 as cv\nfrom matplotlib import pyplot as plt\nimport matplotlib.cbook as cbook\n\nclass ConstS:\n def __init__(self,_img):\n self.a=0\n self.b=255\n self.img=_img\n self.c=0\n self.d=255\n self.v=False\n\n def Formula(self,Fxy):\n return (((Fxy-self.c)*((self.b-self.a)/(self.d-self.c)))+self.a)%256\n\n def Stretch(self):\n \n \tif self.v==False:\n \t\tself.c=np.min(self.img)\n \t\tself.d=np.max(self.img)\n \t\n \trows,columns=self.img.shape\n \tnewimg=[[] for i in range(rows)]\n \tfor i in range(rows):\n \t\tfor j in range(columns):\n \t\t\tpixel=0\n \t\t\tif(self.c < self.img[i,j] < self.d):\n \t\t\t\tpixel=self.img[i,j]\n \t\t\telse:\n \t\t\t\tpixel=((self.d-self.c)/2)+self.c\n \t\t\tnewimg[i].append(self.Formula(pixel))\n \treturn np.array(newimg)\n\n def CDlimit(self,l=0):\n self.hist,bins =np.histogram(self.img.flatten(),256,[0,256])\n \n self.v=True\n self.c=np.min(self.img)\n self.d=np.max(self.img)\n\n rows,columns=self.img.shape\n l=((rows*columns)/100)*l\n \n i=self.c\n count=0\n while True:\n count=count+self.hist[i]\n if(count>int(l)):\n self.c=i\n break\n i=i+1\n i=self.d\n count=0\n while True:\n count=count+self.hist[i]\n if(count>=int(l)):\n self.d=i\n break\n i=i-1\n\ndef addOutlier(img,r,c):\n for i in range(r):\n for j in range(c):\n img[i,j]=1\n\"\"\"\nimg=cv.imread('contrast.jpg',0)\n\n#ContrastStretching sin outlier\ncontrast=ConstS(img)\ncontrast.CDlimit()\nnewimg=contrast.Stretch()\n\ncv.imwrite('outimg.jpg',newimg)\n\n#Agregando outlier a la imagen\naddOutlier(img,30,30)\ncv.imwrite('imgoutlier.jpg',img)\n\n#Aplicando ContrastStretch con limites\ncontrast1=ConstS(img)\ncontrast1.CDlimit(15)\nnewimg1=contrast1.Stretch()\n\ncv.imwrite('outimgoutlier.jpg',newimg1)\n\"\"\"\n\n","sub_path":"mysite/blog/Lab2/contrastStretching.py","file_name":"contrastStretching.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"203009231","text":"# Statements, Indentation, Comments\r\n\r\n# Multiline statements (Implicit)\r\na = 1 + 2 + 3 + \\\r\n 4 + 5 + 6 + \\\r\n 7 + 8 + 9\r\nprint(a)\r\n\r\n# Multiline statements (Explicit)\r\na = (1 + 2 + 3 +\r\n 4 + 5 + 6 +\r\n 7 + 8 + 9)\r\nprint(a)\r\n\r\n# Multiple statements on one line\r\na = 1; b = 2; c = 3\r\nprint(a, b, c)\r\n\r\n\r\n# Docstring\r\ndef test():\r\n \"\"\"I am a Docstring\r\n\r\n Returns:\r\n int -- the number 1\r\n \"\"\"\r\n return 1\r\n\r\nprint(test.__doc__)\r\n","sub_path":"archive/Python Tutorial/program3.py","file_name":"program3.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"370782773","text":"#!/usr/bin/env python3\n\"\"\"module\"\"\"\n\nimport numpy as np\n\n\nclass BidirectionalCell:\n \"\"\"class\"\"\"\n\n def __init__(self, i, h, o):\n \"\"\"constuctor\"\"\"\n self.Whf = np.random.normal(size=(i + h, h))\n self.Whb = np.random.normal(size=(i + h, h))\n self.Wy = np.random.normal(size=(2*h, o))\n self.bhf = np.zeros((1, h))\n self.bhb = np.zeros((1, h))\n self.by = np.zeros((1, o))\n\n @staticmethod\n def softmax(z):\n \"\"\"applies softmax activation\"\"\"\n return np.exp(z)/np.sum(np.exp(z), axis=1).reshape((-1, 1))\n\n def forward(self, h_prev, x_t):\n \"\"\"forward prop\"\"\"\n concat = np.hstack((h_prev, x_t))\n h_next = np.tanh(np.matmul(concat, self.Whf) + self.bhf)\n return h_next\n\n def backward(self, h_next, x_t):\n \"\"\"backward pass\"\"\"\n concat = np.hstack((h_next, x_t))\n h_prev = np.tanh(np.matmul(concat, self.Whb) + self.bhb)\n return h_prev\n\n def output(self, H):\n \"\"\"output\"\"\"\n Y = []\n t = H.shape[0]\n for n in range(t):\n Y.append(self.softmax(np.matmul(H[n, ...], self.Wy) + self.by))\n return np.asarray(Y)\n","sub_path":"supervised_learning/0x0D-RNNs/7-bi_output.py","file_name":"7-bi_output.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"620629464","text":"import time\nimport math\n\n\ntimerStart = time.time()\n\nloopMax = input(\"How many primes to find?\")\n# loopMax = 25\nloopMax = loopMax - 5\nnumber = 3\nprimes = 0\nprimeList = [2,3,5,7,9]\n\nwhile primes < loopMax: #checks the amount of primes you want.\n number = number + 1\n print(\"n: \" + str(number))\n even = float(number)%2.0\n print(\"even: \" + str(even))\n if even == 0:\n print(\"\\t even\")\n print(\"\\t not prime\")\n else:\n primeDivisors = 0\n almostPrime = 0\n for aPrime in primeList:\n print(\"\\t\\t current: \"+str(aPrime))\n divPrimes = number%aPrime # modulo of number by known primes, returns zero is there is no remainder its not prime\n print(\"\\t\\t divPrimes: \"+ str(number) + \" / \" + str(aPrime) + \"=\" + str(divPrimes))\n if divPrimes == 0: # a zero modulo means there is a divisor.\n almostPrime = almostPrime + 1\n print(\"\\t\\t\\t almostPrime: \" + str(almostPrime))\n break\n if almostPrime == 0:\n print(\"\\t\\t\\t\\t NUMBER IS PRIME: \" + str(number))\n primeList.append(number)\n primes = primes + 1\n print(\"PRIMES\" + str(primes))\n\nlistingNumber = 0\nprint(\"\\t|-----------------|\")\nprint(\"\\t| #\\t| PRIME\\t |\")\n\nfor aPrime in primeList:\n listingNumber = listingNumber + 1\n printPrime = aPrime\n print(\"\\t | \" + str(listingNumber)+ \"\\t| \"+ str(printPrime)+ \"\\t|\")\n \ntimerEnd = time.time()\n\nprint(\"| TIME TAKEN = \" + str(format(timerStart, 'e')) + \" |\")\nprint(\"| TIME TAKEN = \" + str(format(timerEnd, 'e')) + \" |\")\n\ntotal = timerEnd - timerStart\nprint(\"| TIME TAKEN = \" + str(format(total, 'e')) + \" |\")\n# print(timerEnd)\n","sub_path":"classExamples_KH/primeChecker.py","file_name":"primeChecker.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"578522261","text":"# les IMPORTS \r\nfrom pymongo import MongoClient\r\nfrom pprint import pprint\r\n\r\n# connection à MongoDB\r\nclient = MongoClient('127.0.0.1',27017)\r\ndb = client['ma_base']\r\n# db = client['admin']\r\n\r\n#Etat du server\r\n# serverStatusResult = db.command(\"serverStatus\")\r\n# pprint(serverStatusResult)\r\n\r\n# Se placer dans test dans admin de la base:\r\ndb = client['ma_base']\r\n#Création de la collection:\r\ncollec = db.create_collection(\"data_client\")\r\n\r\n#descritif de la collection :\r\n#data_user = {'_id': nick_name, 'prenom': prenom, 'nom': nom, 'sexe': sexe}\r\n\r\n# morad a posté :\r\nnick_name = 'phoenix'\r\nprenom = 'morad'\r\nnom = 'ziad'\r\nsexe = 'masculin'\r\n\r\ndata = {'_id':nick_name, 'prenom':prenom, 'nom':nom, 'sexe':sexe}\r\n\r\n#poster :\r\nclient_1 = db.insert_many([data])\r\n\r\n\r\n\r\n\r\n","sub_path":"Intro_Flask_5/tests/Intro_Flask_5.Nosql.py","file_name":"Intro_Flask_5.Nosql.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"134018106","text":"import quandl\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport seaborn as sns\nimport numpy as np\n\nstyle.use('ggplot')\n\nALWAYS_LOAD = False\n\nif ALWAYS_LOAD or not os.path.exists('main_df.csv'):\n api_key = open('api_key.txt', 'r').read()\n states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states')[0][0][1:]\n main_df = pd.DataFrame()\n for state in states:\n code_name = 'FMAC/HPI_{}'.format(state)\n df = quandl.get(code_name, api_key=api_key)\n df.rename(columns={'Value': state}, inplace=True)\n if main_df.empty:\n main_df = df\n else:\n main_df = main_df.join(df)\n main_df.to_csv('main_df.csv')\nelse:\n main_df = pd.read_csv('main_df.csv', index_col=0)\n\nmain_df.plot()\nplt.legend().remove()\nplt.show()\n\ncolumns = list(main_df.columns.values)\nmain_corr = main_df[columns[:20]].corr()\nmask = np.zeros_like(main_corr, dtype=np.bool)\nmask[np.tril_indices_from(mask)] = True\ncmap = 'YlGnBu'\ncmap = sns.diverging_palette(220, 10, as_cmap=True)\nsns.heatmap(main_corr, mask=mask, vmin=.8, square=True, annot=True, fmt=\".2g\", linewidths=.5, cmap=None, cbar=True)\nplt.show()\n","sub_path":"03_building_dataset.py","file_name":"03_building_dataset.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"15994228","text":"def MinimumSwaps(arr):\n\tarrturple = [*enumerate(arr)]\n\tarrturple.sort(key = lambda it: it[1])\n\t# print(arrturple)\n\t# initialize a directed cycle\n\tn = len(arr)\n\tv = [False for i in range(n)]\n\tres = 0\n\tfor i,turple in enumerate(arrturple):\n\t\tcycles = 0\n\t\tif v[i] or turple[0] == i:\n\t\t\tcontinue\n\t\tj = i \n\t\twhile v[j] == False:\n\t\t\tv[j] = True \n\t\t\tj = arrturple[j][0]\n\t\t\tcycles += 1\n\t\tres += cycles - 1\n\treturn res \n\n\narrtest = [2,4,5,1,3]\nprint(MinimumSwaps(arrtest))","sub_path":"minimunswaps.py","file_name":"minimunswaps.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"42886479","text":"import pyxlsb\nfrom pyxlsb import open_workbook\nfrom pyxlsb import convert_date\n\nimport re\n\nwb = open_workbook('npi17.xlsb')\n\nnets = {}\nparams = {}\nrows = wb.get_sheet('Norm_KPI').rows()\n\ni = 0\nfor row in rows:\n #print(row)\n #print(type(row))\n prev_param=''\n if i == 0:\n for Cell in row:\n param=Cell.v\n param = param.upper();\n param = param.replace(' ', ' ')\n param = param.replace(' ', '_')\n param = param.replace('__', '_')\n param = param.replace('_МГЦ', '')\n if param == 'SUMMER':\n param=prev_param.replace('_NORM','_SUMMER')\n prev_param = ''\n elif re.search('(NET|REGION|MONTH|PRIORITY|INFORMATIONAL)', param):\n next\n else:\n param=(param+'_NORM')\n prev_param = param\n params[Cell.c]=param\n #print(str(Cell.c)+param+'-')\n\n# break\n else:\n ii = 0\n norms={}\n Net=''\n for Cell in row:\n #print(str(ii))\n if params[ii] == 'MONTH':\n Day=convert_date(Cell.v).day\n StrDay=''\n if Day<10:\n StrDay='0'+str(Day)\n else:\n StrDay=str(Day)\n MM = convert_date(Cell.v).month\n StrMM = ''\n if MM<10:\n StrMM='0'+str(MM)\n else:\n StrMM=str(MM)\n Month=\"TO_DATE('\"+StrDay+'.'+StrMM+'.'+str(convert_date(Cell.v).year)+\"','DD.MM.YYYY')\"\n #print(params[ii]+' '+Month)\n norms[params[ii]] = Month\n else:\n norm_value=str(Cell.v)\n #if norm_value == 'None':\n if re.search('(^None$|^-$)', norm_value):\n norm_value=''\n elif re.search('\\*', norm_value):\n norm_value = norm_value.replace('*', '')\n norm_value = norm_value.replace(',', '.')\n norm_value = float(norm_value)\n else:\n norm_value=Cell.v\n if Net == 'Yoshkar-Ola':# Sochi Yoshkar-Ola\n if params[ii] == 'CUNSSR_2G3G_NORM': #INFORMATIONAL CUNSSR_2G3G_NORM\n print(norm_value)\n norms[params[ii]]=norm_value\n if params[ii] == 'NET':\n Net=Cell.v\n ii +=1\n #print(norms)\n nets[Net+'_'+Month]=norms\n #if Net=='Yoshkar-Ola':\n #print(norms)\n# norms{}\n\n i += 1\n\n#print(nets)\n#for param in params:\n# print (param)\n##from pyxlsb import convert_date\n##print(convert_date(41235.45578))\n# datetime.datetime(2012, 11, 22, 10, 56, 19)\n\nsql_list=[]\nsql=\"INSERT INTO NPI.TEST_PY_NORM_NPI ({param_name}) VALUES ({param_value})\"\nfor netmonth in nets:\n #print(nets[net])\n param_names = ''\n param_values = ''\n normatives = nets[netmonth]\n zpt=''\n for param in normatives:\n param_names = param_names+zpt+param\n if param == 'MONTH':\n param_values_sh = \"{param_value}\"\n else:\n param_values_sh = \"'{param_value}'\"\n param_values = param_values+zpt+param_values_sh.format(param_value=normatives[param])\n zpt = ','\n sql_list.append(sql.format(param_name=param_names,param_value=param_values))\n #print(sql.format(param_name=param_names,param_value=param_values))\n\n\nimport cx_Oracle\n\n\nip = '10.136.12.164'\nport = 1521\nSID = 'RAN'\ndsn_tns = cx_Oracle.makedsn(ip, port, SID)\nprint (dsn_tns)\ncon = cx_Oracle.connect('NPI', 'NPI', dsn_tns)\n\n#con = cx_Oracle.connect('CC/CC@10.136.12.164/RAN')\n#con = cx_Oracle.connect(\"CC\", \"CC\", \"Violet\")\n\n\nconnstr = 'NPI/NPI@10.136.12.164:1521/RAN'\ncon = cx_Oracle.connect(connstr)\n\ncur = con.cursor()\ncur.execute('TRUNCATE TABLE NPI.TEST_PY_NORM_NPI')\ncon.commit()\n\n\ng=0\nb=0\nfor sql in sql_list:\n #print(sql)\n try:\n cur.execute(sql)\n g+=1\n except cx_Oracle.DatabaseError as error:\n # Log error as appropriate\n print(sql)\n print(error)\n b+=1\n #raise #=break of script\ncon.commit()\ncur.close()\ncon.close()\n\nallR=g+b\nprint(\"RECORDS: \"+str(allR)+', SUCCESSFUL: '+str(g)+', FAILED: '+str(b))\n","sub_path":"test_xlsb_PT.py","file_name":"test_xlsb_PT.py","file_ext":"py","file_size_in_byte":4335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"222172001","text":"# Copyright 2020 Google LLC\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# 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\"\"\"Utility functions for FQE operators.\"\"\"\n\nimport re\n\n\ndef validate_rdm_string(ops: str) -> str:\n \"\"\"Check that a string for rdms are valid.\n\n Args:\n ops (str): String expression to be computed.\n\n Returns\n (str): Either 'element' or 'tensor'.\n \"\"\"\n\n qftops = ops.split()\n nops = len(qftops)\n\n assert (nops % 2) == 0\n\n if any(char.isdigit() for char in ops):\n\n creation = re.compile(r\"^[0-9]+\\^$\")\n annihilation = re.compile(r\"^[0-9]+$\")\n\n ncre = 0\n nani = 0\n\n for opr in qftops:\n if creation.match(opr):\n ncre += 1\n elif annihilation.match(opr):\n nani += 1\n else:\n raise TypeError(\"Unsupported behavior for {}\".format(ops))\n\n assert nani == ncre\n\n return \"element\"\n\n creation = re.compile(r\"^[a-z]\\^$\")\n annihilation = re.compile(r\"^[a-z]$\")\n\n ncre = 0\n nani = 0\n\n for opr in qftops:\n if creation.match(opr):\n ncre += 1\n elif annihilation.match(opr):\n nani += 1\n else:\n raise TypeError(\"Unsupported behvior for {}.\".format(ops))\n\n if nani != ncre:\n raise ValueError(\"Unequal creation and annihilation operators.\")\n\n return \"tensor\"\n\n\ndef switch_broken_symmetry(string: str) -> str:\n \"\"\"Convert the string passed in to the desired symmetry.\n\n Args:\n string (str): Input string in the original expression.\n\n Returns:\n (str): Output string in the converted format.\n \"\"\"\n new = \"\"\n if any(char.isdigit() for char in string):\n\n work = string.split()\n creation = re.compile(r\"^[0-9]+\\^$\")\n annihilation = re.compile(r\"^[0-9]+$\")\n\n for opr in work:\n if creation.match(opr):\n if int(opr[:-1]) % 2:\n val = opr[:-1]\n else:\n val = opr\n elif annihilation.match(opr):\n if int(opr) % 2:\n val = opr + \"^\"\n else:\n val = opr\n new += val + \" \"\n else:\n new = string\n\n return new.rstrip()\n","sub_path":"src/fqe/fqe_ops/fqe_ops_utils.py","file_name":"fqe_ops_utils.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"115173429","text":"'''\n思路:从左到右找到字符串中相邻右边小于左边的数,删除\nsplit()函数返回一个列表\nstrip(x)方法只能用于移除字符串头尾指定的字符\n'''\nline = input()\nline = line.split(' ')\nN = int(line[1])\nwhile N:\n N -= 1\n strlen = len(line[0])\n for i in range(strlen-1):\n n = i\n if line[0][i] < line[0][i+1]:\n line[0] = line[0][0:i] + line[0][i+1:]\n break\n if n == strlen-1:\n lien[0].strip(line[0][n])\nprint(line[0])","sub_path":"61.py","file_name":"61.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"463758754","text":"#!/usr/bin/env python3\n\nimport serial\nimport csv\nimport os\nimport time\nfrom datetime import datetime\n\n\nser=serial.Serial('/dev/ttyACM0',115200,timeout=1) # find correct device with \"ls /dev/tty*\"\nser.flush() # flushes any I/O buffer to avoid sending incomplete data at start of serial communication\n\nnow = datetime.now()\ncurrent_dt = now.strftime(\"%b-%d-%Y_%H-%M-%S\")\nif os.path.isdir('/home/pi/LIVE/segmented_data') == False:\n os.mkdir('/home/pi/LIVE/segmented_data')\n\nwhile True:\n if os.path.isdir('/home/pi/LIVE/segmented_data/'+str(current_dt))==False:\n os.mkdir('/home/pi/LIVE/segmented_data/'+str(current_dt))\n os.chdir('/home/pi/LIVE/segmented_data/'+str(current_dt))\n i=0\n while True:\n if ser.in_waiting>0: # checks if data is available\n path=\"log\" + str(i)+\".csv\"\n if os.path.exists(path)== False: \n file=open(\"log\" + str(i)+\".csv\", 'a', encoding='utf-8-sig')\n x=os.stat(path).st_size\n for x in range (0,200): # write new file every 20 seconds\n obj=csv.writer(file)\n line=ser.readline()\n line=line.decode('utf-8').split() # decodes line with utf-8 and splits into list\n print(line) \n obj.writerow(line)\n time.sleep(0.01) # sampling rate of 100Hz \n file.close()\n i=i+1\n elif os.path.exists(path)== False: #increments i if file exists\n i=i+1\n","sub_path":"data-PID/data_logging.py","file_name":"data_logging.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"226572772","text":"######################################################\r\n# File: startcmss3.py\r\n# Description: Python script to start PySpark ML script\r\n# Date: 03/9/2020\r\n######################################################\r\nimport time\r\nimport boto3\r\nimport paramiko\r\nimport json\r\n\r\n# Script will start file processing script through Lambda function\r\n# triggered by cron that starts ec2 instance\r\n\r\ndef lambda_handler(event, context):\r\n ec2 = boto3.resource('ec2', region_name='us-east-1')\r\n\r\n print('Connecting to ec2 instance')\r\n # Sleep for 90 seconds to give time for ec2 to launch\r\n time.sleep(90)\r\n\r\n # Get instance ip\r\n instance_id = 'i-0eb9a408ec2b491c8'\r\n instance = ec2.Instance(instance_id)\r\n instance_ip = instance.public_ip_address\r\n\r\n print('Downloading key')\r\n # Download key to temporary directory\r\n s3_client = boto3.client('s3')\r\n s3_client.download_file('cms-keys', 'project-436.pem', '/tmp/keyname.pem' )\r\n\r\n time.sleep(20)\r\n\r\n # Connect to ec2 instance\r\n ssh = paramiko.SSHClient()\r\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\n privkey = paramiko.RSAKey.from_private_key_file('/tmp/keyname.pem')\r\n\r\n ssh.connect(\r\n instance_ip, username='ec2-user', pkey=privkey\r\n )\r\n print('Connected to {0}'.format(instance_ip))\r\n\r\n # Start Docker service and execute Python script\r\n command = '''sudo service docker start &&\r\n sudo docker run -it bc3b86e0e25b python3 /model/pyspark_model.py /bin/bash'''\r\n try:\r\n transport = ssh.get_transport()\r\n session = transport.open_session()\r\n session.set_combine_stderr(True)\r\n session.get_pty()\r\n print('Executing {}'.format(command))\r\n session.exec_command(command)\r\n\r\n time.sleep(310)\r\n\r\n ssh.close()\r\n\r\n return\r\n {\r\n 'message': 'Script executed successfully'\r\n }\r\n except:\r\n return\r\n {\r\n 'message': 'Script failed'\r\n }\r\n","sub_path":"cms-sparkml/lambda-functions/startsparkml.py","file_name":"startsparkml.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"578898233","text":"import re, os\r\n\r\nope = os.path.exists\r\nsep = os.path.sep\r\n\r\ndef checkPath(path):\r\n if not ope(path):\r\n path = os.getcwd()\r\n else:\r\n if os.path.isfile(path):\r\n path = os.path.dirname(path)\r\n if path[-1] != sep:\r\n path += sep\r\n return path\r\n\r\ndef isValid(url):\r\n Match = r'(?Phttps?://(?:[^/]+\\.)?reddit\\.com/r/[^/]+/comments/(?P[^/?#&]+))'\r\n if re.search(Match, url):\r\n parts = [i for i in url.split('/') if i]\r\n if 6 < len(parts) < 9:\r\n return True\r\n return False\r\n \r\n'''def toDic(data):\r\n return json.loads(data)'''\r\n\r\ndef toJsonUrl(url):\r\n if isValid(url):\r\n parts = url.split('/')\r\n if len(parts) is 9:\r\n url = '/'.join(parts[:-1])\r\n return url + '.json'\r\n return None\r\n\r\ndef getUNQ(page):\r\n regex = r'https://v\\.redd\\.it/[a-zA-Z0-9]+'\r\n Match = re.findall(regex, page.text)\r\n UNQ = None\r\n if Match:\r\n UNQ = Match[0]\r\n UNQ += '/' if UNQ[-1] != '/' else UNQ\r\n return UNQ\r\n \r\ndef mpdParse(mpd):\r\n tag = r'(.*?)'\r\n extracted = re.findall(tag, mpd)\r\n return extracted\r\n\r\ndef hasAudio(lst):\r\n return any(i == 'audio' for i in lst)\r\n\r\ndef UserSelect(lst):\r\n print('\\nQualities available:')\r\n for n, i in enumerate(lst):\r\n i = i.split('_')[1]\r\n print(' [{}] {}p'.format(n + 1, i))\r\n ql = input('\\nChoose Quality: ')\r\n # If a dumbass chose nothing\r\n try:\r\n lst[int(ql) - 1]\r\n except:\r\n ql = 1\r\n return lst[int(ql) - 1]\r\n\r\ndef Clean(path):\r\n p = path + 'temp' + sep\r\n if not ope(p):\r\n return\r\n os.chdir(path)\r\n for i in os.listdir(p):\r\n os.remove(p+i)\r\n os.rmdir(p)\r\n\r\ndef Clear(text, elements=[], tgt=''):\r\n for element in elements:\r\n text = text.replace(element, tgt)\r\n return text\r\n","sub_path":"redvid/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"649137540","text":"# -*- coding: utf-8 -*-\n'''\nMain entry point for the hubble daemon\n'''\nfrom __future__ import print_function\n\n#import lockfile\nimport argparse\nimport logging\nimport time\nimport pprint\nimport os\nimport random\nimport signal\nimport sys\n\nimport salt.fileclient\nimport salt.utils\nimport salt.utils.jid\nimport salt.log.setup\nfrom hubblestack import __version__\n\nlog = logging.getLogger(__name__)\n\n__opts__ = {}\n\n\ndef run():\n '''\n Set up program, daemonize if needed\n '''\n # Don't put anything that needs config or logging above this line\n try:\n load_config()\n except Exception as e:\n print('An Error occurred while loading the config: {0}'.format(e))\n raise\n\n # Create cache directory if not present\n if not os.path.isdir(__opts__['cachedir']):\n os.makedirs(__opts__['cachedir'])\n\n if __opts__['version']:\n print(__version__)\n clean_up_process(None, None)\n sys.exit(0)\n\n if __opts__['daemonize']:\n salt.utils.daemonize()\n create_pidfile()\n\n signal.signal(signal.SIGTERM, clean_up_process)\n signal.signal(signal.SIGINT, clean_up_process)\n\n try:\n main()\n except KeyboardInterrupt:\n pass\n\n clean_up_process(None, None)\n\n\ndef main():\n '''\n Run the main hubble loop\n '''\n # Initial fileclient setup\n log.info('Setting up the fileclient/fileserver')\n try:\n fc = salt.fileclient.get_file_client(__opts__)\n fc.channel.fs.update()\n last_fc_update = time.time()\n except Exception as exc:\n log.exception('Exception thrown trying to setup fileclient. Exiting.')\n sys.exit(1)\n\n # Check for single function run\n if __opts__['function']:\n run_function()\n sys.exit(0)\n\n log.info('Starting main loop')\n while True:\n # Check if fileserver needs update\n if time.time() - last_fc_update >= __opts__['fileserver_update_frequency']:\n try:\n fc.channel.fs.update()\n last_fc_update = time.time()\n except Exception as exc:\n log.exception('Exception thrown trying to update fileclient.')\n\n try:\n log.debug('Executing schedule')\n schedule()\n except Exception as e:\n log.exception('Error executing schedule')\n time.sleep(__opts__.get('scheduler_sleep_frequency', 0.5))\n\n\ndef schedule():\n '''\n Rudimentary single-pass scheduler\n\n If we find we miss some of the salt scheduler features we could potentially\n pull in some of that code.\n\n Schedule data should be placed in the config with the following format:\n\n .. code-block:: yaml\n\n schedule:\n job1:\n function: hubble.audit\n seconds: 3600\n splay: 100\n args:\n - cis.centos-7-level-1-scored-v2-1-0\n kwargs:\n verbose: True\n show_profile: True\n returner: splunk_nova_return\n run_on_start: True\n\n Note that ``args``, ``kwargs``, and ``splay`` are all optional. However, a\n scheduled job must always have a ``function`` and a time in ``seconds`` of\n how often to run the job.\n\n function\n Function to run in the format ``.``. Technically any\n salt module can be run in this way, but we recommend sticking to hubble\n functions. For simplicity, functions are run in the main daemon thread,\n so overloading the scheduler can result in functions not being run in\n a timely manner.\n\n seconds\n Frequency with which the job should be run, in seconds\n\n splay\n Randomized splay for the job, in seconds. A random number between 0 and\n will be chosen and added to the ``seconds`` argument, to decide\n the true frequency. The splay will be chosen on first run, and will\n only change when the daemon is restarted. Optional.\n\n args\n List of arguments for the function. Optional.\n\n kwargs\n Dict of keyword arguments for the function. Optional.\n\n returner\n String with a single returner, or list of returners to which we should\n send the results. Optional.\n\n run_on_start\n Whether to run the scheduled job on daemon start. Defaults to False.\n Optional.\n '''\n schedule_config = __opts__.get('schedule', {})\n for jobname, jobdata in schedule_config.iteritems():\n # Error handling galore\n if not jobdata or not isinstance(jobdata, dict):\n log.error('Scheduled job {0} does not have valid data'.format(jobname))\n continue\n if 'function' not in jobdata or 'seconds' not in jobdata:\n log.error('Scheduled job {0} is missing a ``function`` or '\n '``seconds`` argument'.format(jobname))\n continue\n func = jobdata['function']\n if func not in __salt__:\n log.error('Scheduled job {0} has a function {1} which could not '\n 'be found.'.format(jobname, func))\n continue\n try:\n seconds = int(jobdata['seconds'])\n splay = int(jobdata.get('splay', 0))\n except ValueError:\n log.error('Scheduled job {0} has an invalid value for seconds or '\n 'splay.'.format(jobname))\n args = jobdata.get('args', [])\n if not isinstance(args, list):\n log.error('Scheduled job {0} has args not formed as a list: {1}'\n .format(jobname, args))\n kwargs = jobdata.get('kwargs', {})\n if not isinstance(kwargs, dict):\n log.error('Scheduled job {0} has kwargs not formed as a dict: {1}'\n .format(jobname, kwargs))\n returners = jobdata.get('returner', [])\n if not isinstance(returners, list):\n returners = [returners]\n\n # Actually process the job\n run = False\n if 'last_run' not in jobdata:\n if jobdata.get('run_on_start', False) and splay == 0:\n run = True\n jobdata['last_run'] = time.time()\n if 'set_splay' not in jobdata:\n jobdata['set_splay'] = random.randint(0, splay)\n jobdata['last_run'] += jobdata['set_splay']\n\n if jobdata['last_run'] < time.time() - seconds:\n run = True\n\n if run:\n log.debug('Executing scheduled function {0}'.format(func))\n jobdata['last_run'] = time.time()\n ret = __salt__[func](*args, **kwargs)\n log.debug('Job returned:\\n{0}'.format(ret))\n for returner in returners:\n returner = '{0}.returner'.format(returner)\n if returner not in __returners__:\n log.error('Could not find {0} returner.'.format(returner))\n continue\n log.debug('Returning job data to {0}'.format(returner))\n returner_ret = {'id': __grains__['id'],\n 'jid': salt.utils.jid.gen_jid(),\n 'fun': func,\n 'fun_args': args + ([kwargs] if kwargs else []),\n 'return': ret}\n __returners__[returner](returner_ret)\n\n\ndef run_function():\n '''\n Run a single function requested by the user\n '''\n # Parse the args\n args = []\n kwargs = {}\n for arg in __opts__['args']:\n if '=' in arg:\n kwarg, _, value = arg.partition('=')\n kwargs[kwarg] = value\n else:\n args.append(arg)\n\n log.debug('Parsed args: {0} | Parsed kwargs: {1}'.format(args, kwargs))\n log.info('Executing user-requested function {0}'.format(__opts__['function']))\n\n try:\n ret = __salt__[__opts__['function']](*args, **kwargs)\n except KeyError:\n log.error('Function {0} is not available, or not valid.'\n .format(__opts__['function']))\n sys.exit(1)\n\n if __opts__['return']:\n returner = '{0}.returner'.format(__opts__['return'])\n if returner not in __returners__:\n log.error('Could not find {0} returner.'.format(returner))\n else:\n log.info('Returning job data to {0}'.format(returner))\n returner_ret = {'id': __grains__['id'],\n 'jid': salt.utils.jid.gen_jid(),\n 'fun': __opts__['function'],\n 'fun_args': args + ([kwargs] if kwargs else []),\n 'return': ret}\n __returners__[returner](returner_ret)\n\n # TODO instantiate the salt outputter system?\n if(__opts__['no_pprint']):\n pprint.pprint(ret)\n else:\n print(ret)\n\n\ndef load_config():\n '''\n Load the config from configfile and load into imported salt modules\n '''\n # Parse arguments\n parsed_args = parse_args()\n\n salt.config.DEFAULT_MINION_OPTS['cachedir'] = '/var/cache/hubble'\n salt.config.DEFAULT_MINION_OPTS['pidfile'] = '/var/run/hubble.pid'\n salt.config.DEFAULT_MINION_OPTS['log_file'] = '/var/log/hubble'\n salt.config.DEFAULT_MINION_OPTS['log_level'] = None\n salt.config.DEFAULT_MINION_OPTS['file_client'] = 'local'\n salt.config.DEFAULT_MINION_OPTS['fileserver_update_frequency'] = 43200 # 12 hours\n salt.config.DEFAULT_MINION_OPTS['scheduler_sleep_frequency'] = 0.5\n\n global __opts__\n global __grains__\n global __utils__\n global __salt__\n global __pillar__\n global __returners__\n\n __opts__ = salt.config.minion_config(parsed_args.get('configfile'))\n __opts__.update(parsed_args)\n\n # Convert -vvv to log level\n if __opts__['log_level'] is None:\n # Default to 'error'\n __opts__['log_level'] = 'error'\n # Default to more verbose if we're daemonizing\n if __opts__['daemonize']:\n __opts__['log_level'] = 'info'\n # Handle the explicit -vvv settings\n if __opts__['verbose'] == 1:\n __opts__['log_level'] = 'warning'\n elif __opts__['verbose'] == 2:\n __opts__['log_level'] = 'info'\n elif __opts__['verbose'] >= 3:\n __opts__['log_level'] = 'debug'\n\n # Setup module dirs\n module_dirs = __opts__.get('module_dirs', [])\n module_dirs.append(os.path.join(os.path.dirname(__file__), 'extmods'))\n __opts__['module_dirs'] = module_dirs\n __opts__['file_roots']['base'].insert(0, os.path.join(os.path.dirname(__file__), 'files'))\n if 'roots' not in __opts__['fileserver_backend']:\n __opts__['fileserver_backend'].append('roots')\n\n # Setup logging\n salt.log.setup.setup_console_logger(__opts__['log_level'])\n salt.log.setup.setup_logfile_logger(__opts__['log_file'],\n __opts__['log_level'])\n # 384 is 0o600 permissions, written without octal for python 2/3 compat\n os.chmod(__opts__['log_file'], 384)\n os.chmod(parsed_args.get('configfile'), 384)\n\n __grains__ = salt.loader.grains(__opts__)\n __pillar__ = {}\n __opts__['grains'] = __grains__\n __opts__['pillar'] = __pillar__\n __utils__ = salt.loader.utils(__opts__)\n __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__)\n __returners__ = salt.loader.returners(__opts__, __salt__)\n\n\ndef parse_args():\n '''\n Parse command line arguments\n '''\n parser = argparse.ArgumentParser()\n parser.add_argument('-d', '--daemonize',\n action='store_true',\n help='Whether to daemonize and background the process')\n parser.add_argument('-c', '--configfile',\n default='/etc/hubble/hubble',\n help='Pass in an alternative configuration file. Default: %(default)s')\n parser.add_argument('-p', '--no-pprint',\n help='Turn off pprint for single-function output',\n action='store_false')\n parser.add_argument('-v', '--verbose',\n action='count',\n help=('Verbosity level. Use -v or -vv or -vvv for '\n 'varying levels of verbosity. Note that -vv '\n 'will be used by default in daemon mode.'))\n parser.add_argument('-r', '--return',\n default=None,\n help='Pass in a returner for single-function runs')\n parser.add_argument('--version',\n action='store_true',\n help='Show version information')\n parser.add_argument('function',\n nargs='?',\n default=None,\n help='Optional argument for the single function to be run')\n parser.add_argument('args',\n nargs='*',\n help='Any arguments necessary for a single function run')\n return vars(parser.parse_args())\n\n\ndef create_pidfile():\n '''\n Create a pidfile after daemonizing\n '''\n pid = os.getpid()\n with open(__opts__['pidfile'], 'w') as f:\n f.write(str(pid))\n\n\ndef clean_up_process(signal, frame):\n '''\n Clean up pidfile and anything else that needs to be cleaned up\n '''\n if __opts__['daemonize']:\n if os.path.isfile(__opts__['pidfile']):\n os.remove(__opts__['pidfile'])\n sys.exit(0)\n","sub_path":"hubblestack/daemon.py","file_name":"daemon.py","file_ext":"py","file_size_in_byte":13265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"190212105","text":"from cbpro import PublicClient\nfrom indicators import Indicator\nfrom util import get_time\nfrom dict import new_dict\nimport csv\nimport time\n\n\ndef append_data(file_name:str, new_data:list):\n new_file = open(file_name, \"r\")\n reader = csv.reader(new_file)\n last_line = \"\"\n index = 0\n for line in reader:\n if index < 1:\n last_line = line\n index +=1\n else:\n new_data.append(line)\n return last_line\n\n\n#token = \"SNX-USD\"\ntimes = [1]\n\nfor tim in times:\n\n for token in new_dict:\n\n file_name: str\n max_requests = 0\n new_data = []\n gra = tim * 60 # granularity in seconds\n\n if tim <= 60:\n file_name = f\"../../data_{str(tim)}m/{token}_{str(tim)}m.csv\"\n else:\n new_time = tim / 60\n file_name = f\"../../data_{str(new_time)}h/{token}_{str(new_time)}h.csv\"\n\n try:\n last_date = float(append_data(file_name, new_data)[0])\n diff = time.time() - last_date\n req = diff / gra\n max_requests = req / 300\n except FileNotFoundError:\n max_requests = ((60 / tim) * 17520) / 300\n\n indicator = Indicator()\n seconds = 300 * 60 * tim # number of seconds in a request for 300 candles\n callback = seconds # start requesting data from \"seconds\" seconds ago\n begin = 0 # stop requesting data at 0 seconds ago\n requests = 0 # number of request in the last second\n print(token)\n\n data = []\n index = 0\n # Requests data from coinbase\n while index < int(max_requests):\n\n try:\n indicator.set_candles(product=token, callback=get_time(callback), begin=get_time(begin), granularity=gra)\n print(indicator.candles)\n except Exception as e:\n print(\"failed because of\", e)\n pass\n print(index)\n requests = requests + 1\n\n if len(indicator.candles) > 0:\n for line in indicator.candles:\n data.append(line)\n\n else:\n print(indicator.candles)\n break\n\n begin = callback\n callback = callback + seconds\n index += 1\n if requests == 9:\n time.sleep(1)\n requests = 0\n\n new_str = [\"time\", \"low\", \"high\", \"open\", \"close\", \"volume\"]\n awriter = open(file_name, \"w\")\n writer = csv.writer(awriter, delimiter=',', quotechar='\"')\n writer.writerow(new_str)\n for line in data:\n writer.writerow(line)\n awriter.close()\n","sub_path":"src/cb_data.py","file_name":"cb_data.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"290316964","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n Slixmpp OMEMO plugin\n Copyright (C) 2019 Maxime “pep” Buquet \n This file is part of slixmpp-omemo.\n\n See the file LICENSE for copying permission.\n\"\"\"\n\nimport os\nfrom setuptools import setup\n\n\nMODULE_FILE_PATH = os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n 'slixmpp_omemo', 'version.py'\n)\n\ndef get_version() -> str:\n \"\"\"Returns version by looking at slixmpp_omemo/version.py\"\"\"\n\n version = {}\n with open(MODULE_FILE_PATH) as file:\n exec(file.read(), version)\n\n if '__version__' in version:\n return version['__version__']\n return 'missingno'\n\n\nDESCRIPTION = ('Slixmpp OMEMO plugin')\nVERSION = get_version()\nwith open('README.rst', encoding='utf8') as readme:\n LONG_DESCRIPTION = readme.read()\n\nCLASSIFIERS = [\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Topic :: Internet :: XMPP',\n 'Topic :: Security :: Cryptography',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n]\n\nsetup(\n name=\"slixmpp-omemo\",\n version=VERSION,\n description=DESCRIPTION,\n long_description=LONG_DESCRIPTION,\n long_description_content_type='text/x-rst',\n author='Maxime Buquet',\n author_email='pep@bouah.net',\n url='https://lab.louiz.org/poezio/slixmpp-omemo',\n license='GPLv3',\n platforms=['any'],\n packages=['slixmpp_omemo'],\n install_requires=['slixmpp', 'omemo', 'omemo-backend-signal'],\n classifiers=CLASSIFIERS,\n)\n","sub_path":"pypi_install_script/slixmpp-omemo-0.4.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"324763895","text":"from datetime import date, datetime\r\nfrom random import shuffle\r\n\r\nfrom django import template\r\nfrom django.conf import settings\r\nfrom django.core.cache import cache\r\nfrom django.db.models import Q\r\nfrom django.utils.html import format_html\r\n\r\nfrom general_view import get_grouptype\r\nfrom index.models import Broadcast\r\nfrom index.utils import markdown_safe, markdown_link_checker\r\nfrom projects.utils import get_writable_admingroups\r\nfrom studyguide.models import MenuLink\r\nfrom support.models import Promotion\r\n\r\nregister = template.Library()\r\n\r\n\r\n@register.filter(name='has_group')\r\ndef has_group(user, group_names):\r\n \"\"\"\r\n Check groups for given user.\r\n\r\n :param user:\r\n :param group_names:\r\n :return:\r\n \"\"\"\r\n if user.is_anonymous:\r\n return False\r\n if user.is_superuser:\r\n if group_names == \"students\":\r\n return False\r\n else:\r\n return True\r\n if group_names == \"any\":\r\n if user.groups.exists():\r\n return True\r\n else:\r\n return False\r\n elif group_names == \"students\":\r\n if not user.groups.exists():\r\n return True\r\n else:\r\n return False\r\n # check groups\r\n for group_name in group_names.split(';'):\r\n group = get_grouptype(group_name)\r\n if group in user.groups.all():\r\n return True\r\n return False\r\n\r\n\r\n@register.filter(name='is_writable_groupadmin')\r\ndef is_writable_groupadmin(user):\r\n return len(get_writable_admingroups(user)) != 0\r\n\r\n\r\n@register.simple_tag\r\ndef get_broadcasts(user):\r\n \"\"\"\r\n\r\n :param user:\r\n :return:\r\n \"\"\"\r\n msgs = Broadcast.objects.filter((Q(DateBegin__lte=datetime.now()) | Q(DateBegin__isnull=True)) &\r\n (Q(DateEnd__gte=datetime.now()) | Q(DateEnd__isnull=True)) &\r\n (Q(Private=user) | Q(Private__isnull=True))\r\n )\r\n if not msgs.exists():\r\n return \"No announcements\"\r\n\r\n if msgs.count() > 1:\r\n msg = \"
    \"\r\n for m in msgs:\r\n msg += \"
  • {}
  • \".format(m.Message)\r\n msg += \"
\"\r\n else:\r\n msg = msgs[0]\r\n\r\n return format_html(str(msg))\r\n\r\n\r\n@register.simple_tag\r\ndef broadcast_available(user):\r\n \"\"\"\r\n\r\n :param user:\r\n :return:\r\n \"\"\"\r\n if not user.is_authenticated:\r\n return False\r\n if Broadcast.objects.filter((Q(DateBegin__lte=datetime.now()) | Q(DateBegin__isnull=True)) &\r\n (Q(DateEnd__gte=datetime.now()) | Q(DateEnd__isnull=True)) &\r\n (Q(Private=user) | Q(Private__isnull=True))\r\n ).exists():\r\n return True\r\n else:\r\n return False\r\n\r\n\r\n@register.filter\r\ndef is_ele(user):\r\n return user.usermeta.Department == 'ELE'\r\n\r\n\r\n@register.filter\r\ndef is_current_cohort(user):\r\n meta = user.usermeta\r\n if not meta.Cohort:\r\n return False\r\n d = date.today()\r\n current_cohort = d.year\r\n if d.month < 9:\r\n current_cohort -= 1\r\n return user.usermeta.Cohort == current_cohort\r\n\r\n\r\n@register.simple_tag\r\ndef get_promotions(user):\r\n # promotions ordered by increasing number of CapacityGroups\r\n promotions = list(Promotion.objects.filter(Visible=True).prefetch_related('CapacityGroups'))\r\n if not user.groups.exists():\r\n # student\r\n try:\r\n reg = user.registration.Program.Group.all()\r\n l1 = [] # list of interesting promotions for student\r\n l2 = [] # list with other promotions\r\n for promotion in promotions:\r\n if promotion.CapacityGroups.all():\r\n if any([(cg in reg) for cg in promotion.CapacityGroups.all()]):\r\n # promotion is interesting for user\r\n l1.append(promotion)\r\n else:\r\n l2.append(promotion)\r\n else:\r\n # promotion has no preferred capacity group\r\n l2.append(promotion)\r\n shuffle(l1)\r\n shuffle(l2) # randomize the other promotions\r\n return l1 + l2\r\n except:\r\n # user has no registration\r\n pass\r\n shuffle(promotions)\r\n return promotions # shuffle is probably faster than .order_by('?')\r\n\r\n\r\n@register.simple_tag\r\ndef get_menu_links():\r\n ml = cache.get('menulinks')\r\n if not ml:\r\n ml = MenuLink.objects.all()\r\n cache.set('menulinks', ml, settings.STATIC_OBJECT_CACHE_DURATION)\r\n return ml\r\n\r\n\r\n@register.filter\r\ndef show_markdown(text):\r\n return format_html(markdown_safe(text))\r\n\r\n\r\n@register.filter\r\ndef show_markdown_restricted(text):\r\n return format_html(markdown_safe(markdown_link_checker(text)))\r\n\r\n\r\n@register.simple_tag\r\ndef get_max_upload_size():\r\n return settings.MAX_UPLOAD_SIZE\r\n","sub_path":"index/templatetags/index_tags.py","file_name":"index_tags.py","file_ext":"py","file_size_in_byte":4893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"73834718","text":"from tkinter import *\r\nfrom tkinter import tix\r\n\r\nclass App:\r\n\r\n def __init__(self, master):\r\n frame = Frame(master)\r\n frame.pack()\r\n\r\n self.button = Button(frame,text=\"QUIT\", fg=\"red\",command=frame.quit)\r\n self.button.pack(side=LEFT)\r\n\r\n self.scale = Scale(frame,label=\"Drag\",orient=HORIZONTAL,to=342)\r\n self.scale.pack(side=LEFT)\r\n\r\n self.meter = tix.Meter(frame)\r\n self.meter.pack(side=BOTTOM)\r\n\r\n self.hi_there = Button(frame, text=\"Hello\", command=self.say_hi)\r\n self.hi_there.pack(side=LEFT)\r\n\r\n def say_hi(self):\r\n print(\"HI\"+str(self.scale.get()))\r\n\r\nroot = Tk()\r\napp = App(root)\r\nroot.mainloop()\r\nroot.destroy()\r\n","sub_path":"python/helo2.py","file_name":"helo2.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"281083460","text":"import csv\nimport numpy as np\n\nimport batman_plot\nimport color\nimport evaluator\n\n\ndef evaluate(x, y):\n return evaluator.inside_boundary(x, y)\n\n\ndef write_csv(x_data, y_data):\n filename = 'batman.csv'\n with open(filename, 'w') as f:\n writer = csv.writer(f, lineterminator='\\n')\n for x, y in zip(x_data, y_data):\n inside = evaluate(x, y)\n result = 0\n if inside:\n result = 1\n writer.writerow([x, y, result])\n\nif __name__ == '__main__':\n plt = batman_plot.get_batman_plot()\n\n n = 1000\n x_range = 7\n y_range = 6\n mid = 0.5\n x_data = (np.random.rand(n) - mid) * x_range * 2\n y_data = (np.random.rand(n) - mid) * y_range * 2\n # write_csv(x_data, y_data)\n for x, y in zip(x_data, y_data):\n plt.plot(x, y, color.get_color(evaluate(x, y)) + 'o', markersize=0.5)\n plt.show()\n","sub_path":"python/scipy/misc/tim_burton/main_tim_burton.py","file_name":"main_tim_burton.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"648940033","text":"from django.shortcuts import render\nfrom django.views import View\nfrom django.http import JsonResponse, HttpResponse, Http404\n\nfrom booktest.models import BookInfo, HeroInfo\n# Create your views here.\n\nfrom booktest.serializers import BookInfoSerializer\n\n# /books/\nclass BookListView(View):\n \"\"\"\n 获取所有图书、增加图书\n \"\"\"\n def get(self, request):\n \"\"\"\n 获取所有的图书数据\n \"\"\"\n queryset = BookInfo.objects.all()\n\n # 序列化所有图书数据\n serializer = BookInfoSerializer(queryset, many=True)\n\n return JsonResponse(serializer.data, safe=False)\n\n def post(self, request):\n \"\"\"\n 新增一个图书数据\n \"\"\"\n json_bytes = request.body\n json_str = json_bytes.decode()\n book_dict = json.loads(json_str)\n\n # 反序列化-数据校验\n serializer = BookInfoSerializer(data=book_dict)\n serializer.is_valid(raise_exception=True)\n\n # 反序列化-数据保存(save内部会调用序列化器类的create方法)\n serializer.save()\n\n return JsonResponse(serializer.data, status=201)\n\n# /books/(?P\\d+)/\nclass BookDetailView(View):\n \"\"\"\n 获取、修改、删除指定图书\n \"\"\"\n def get(self, request, pk):\n \"\"\"\n 获取指定图书\n \"\"\"\n try:\n book = BookInfo.objects.get(pk=pk)\n except BookInfo.DoesNotExist:\n return HttpResponse(status=404)\n\n # 将图书数据进行序列化\n serializer = BookInfoSerializer(book)\n\n return JsonResponse(serializer.data)\n\n def put(self, request, pk):\n \"\"\"\n 修改指定图书\n \"\"\"\n try:\n book = BookInfo.objects.get(pk=pk)\n except BookInfo.DoesNotExist:\n return HttpResponse(status=404)\n\n json_bytes = request.body\n json_str = json_bytes.decode()\n book_dict = json.loads(json_str)\n\n # 反序列化-数据校验\n serializer = BookInfoSerializer(book, data=book_dict)\n serializer.is_valid(raise_exception=True)\n\n # 反序列化-数据保存(save内部会调用序列化器类的update方法)\n serializer.save()\n\n return JsonResponse(serializer.data)\n\n def delete(self, request, pk):\n \"\"\"\n 删除指定图书:\n \"\"\"\n try:\n book = BookInfo.objects.get(pk=pk)\n except BookInfo.DoesNotExist:\n return HttpResponse(status=404)\n\n book.delete()\n\n return HttpResponse(status=204)\n","sub_path":"demo/booktest/01-views.py","file_name":"01-views.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"121690402","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom rbf_net import RBFNetwork\nplt.style.use('ggplot')\n\nnp.random.seed(3)\n\nVAR = 0.1\n\n\ndef sin2(x):\n return np.sin(2 * x)\n\n\ndef square(x):\n if np.sin(2 * x) >= 0:\n return 1\n else:\n return -1\n\n\ndef sin2(x):\n return np.sin(2 * x)\n\n\ndef square(x):\n if np.sin(2 * x) >= 0:\n return 1\n else:\n return -1\n\n\ndef gen_func_data(n_train, n_test, func, noise_var=0):\n patterns = np.linspace(0, 2 * np.pi, n_train + n_test)\n noise = np.random.randn((n_train + n_test))*np.sqrt(noise_var)\n targets = np.array([func(x) for x in patterns]) + noise\n\n data = np.column_stack((patterns, targets))\n np.random.shuffle(data)\n train_data = data[:n_train]\n test_data = data[n_train:]\n\n train_patterns = train_data[:, 0]\n train_targets = train_data[:, 1]\n\n test_patterns = test_data[:, 0]\n test_targets = test_data[:, 1]\n\n return train_patterns, train_targets, test_patterns, test_targets\n\n\ndef plot_prediction(func):\n n_train = 64\n n_test = 63\n func = sin2\n\n network = RBFNetwork(n_inputs=1, n_rbf=64, n_outputs=1, n_epochs=200,\n learning_rate_start=0.1, learning_rate_end=0.001)\n train_patterns, train_targets, test_patterns, test_targets = gen_func_data(\n n_train, n_test, func, noise_var=0.001)\n\n print(network.learning_rate)\n print(network.learning_rate_decay)\n print(np.exp(-network.learning_rate_decay))\n network.fit(train_patterns, train_targets, method='sequential')\n train_preds = network.predict(train_patterns)\n print(network.learning_rate)\n plt.plot(train_patterns, train_preds, 'o', color='m', label='Estimated')\n plt.plot(train_patterns, train_targets, '+', color='c', label='Target')\n plt.legend()\n plt.show()\n\n plt.plot(network.learning_rate_record)\n plt.show()\n\n\ndef calc_mse(predictions, targets):\n return np.linalg.norm(predictions - targets)**2 / len(targets)\n\n\ndef plot_error(func):\n n_train = 64\n n_test = 63\n\n rbfs = np.arange(1, 100)\n\n train_patterns, train_targets, test_patterns, test_targets = gen_func_data(\n n_train, n_test, func, noise_var=0)\n\n n_train = len(train_patterns)\n n_test = len(test_patterns)\n mse_train = np.zeros(len(rbfs))\n mse_test = np.zeros(len(rbfs))\n\n for i, n in enumerate(rbfs):\n network = RBFNetwork(n_inputs=1, n_rbf=n, n_outputs=1, n_epochs=100)\n network.fit(train_patterns, train_targets, method='sequential')\n\n train_preds = network.predict(train_patterns)\n mse_train[i] = np.linalg.norm(train_preds - train_targets)**2 / n_train\n test_preds = network.predict(test_patterns)\n mse_test[i] = np.linalg.norm(test_preds - test_targets)**2 / n_test\n\n plt.xlabel('#RBF nodes')\n plt.ylabel('Residual error')\n plt.plot(rbfs, mse_train, 'r', label='Training set')\n plt.plot(rbfs, mse_test, 'b', label='Test set')\n plt.title('Residual error over the number of RBFs, #data-points=' +\n str(n_train)+', RBF-variance=' + str(VAR))\n plt.legend()\n plt.show()\n\n\ndef plot_convergence_comparison(func):\n n_nodes = 5\n n_trials = 10\n n_epochs = 1000\n learning_rates = [(0.1, 0.1),\n (0.05, 0.05),\n (0.01, 0.01),\n (0.005, 0.005),\n (0.001, 0.001),\n (0.1, 0.001)]\n\n mses = np.zeros((len(learning_rates), n_trials, n_epochs))\n for i, rate in enumerate(learning_rates):\n n_train = 64\n n_test = 63\n for j in range(n_trials):\n train_patterns, train_targets, test_patterns, test_targets = gen_func_data(\n n_train, n_test, func, noise_var=0.1)\n\n net = RBFNetwork(n_inputs=1, n_rbf=n_nodes, n_outputs=1, n_epochs=n_epochs,\n learning_rate_start=rate[0], learning_rate_end=rate[1])\n\n net.fit(train_patterns, train_targets, method='sequential')\n mses[i, j, :] = net.mse_record\n\n average_mses = np.mean(mses, 1)\n for i, rate in enumerate(learning_rates):\n plt.semilogx(average_mses[i, :],\n label=\"Learning rate: {}\".format(rate[0]))\n\n plt.title(\"Comparison of convergence speeds for different learning rates\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Mean Squared Error\")\n plt.legend()\n plt.show()\n\n\ndef final_test_error_comparison(func):\n n_train = 64\n n_test = 63\n n_nodes = 5\n n_trials = 10\n n_epochs = 1000\n\n mses = np.zeros((n_trials))\n\n for i in range(n_trials):\n train_patterns, train_targets, test_patterns, test_targets = gen_func_data(\n n_train, n_test, func, noise_var=0)\n\n net = RBFNetwork(n_inputs=1, n_rbf=n_nodes, n_outputs=1, n_epochs=n_epochs,\n learning_rate_start=0.1, learning_rate_end=0.001)\n\n net.fit(train_patterns, train_targets, method='sequential')\n test_preds = net.predict(test_patterns)\n mses[i] = calc_mse(test_preds, test_targets)\n\n mse_mean = np.mean(mses)\n mse_std = np.std(mses)/len(mses)\n\n print(\"Mean Square Error: {:.2f} +/- {:.2f}\".format(mse_mean, mse_std))\n\n\ndef plot_variance(func):\n VARS = [10, 1, 0.1, 0.01, 0.001]\n n_train = 64\n n_test = 63\n rbfs = np.arange(1, 100)\n noise_var = 0.1\n\n train_patterns, train_targets, test_patterns, test_targets = gen_func_data(\n n_train, n_test, func, noise_var=noise_var)\n\n for var in VARS:\n error = np.zeros(len(rbfs))\n for i, n_rbf in enumerate(rbfs):\n network = RBFNetwork(n_inputs=1, n_rbf=n_rbf,\n n_outputs=1, rbf_var=var)\n network.fit(train_patterns, train_targets, 'batch')\n preds = network.predict(train_patterns)\n mse = network.calc_mse(preds, train_targets)\n error[i] = mse\n plt.plot(rbfs, error, label='RBF variance: '+str(var))\n plt.legend()\n plt.xlabel('#RBF nodes')\n plt.ylabel('MSE')\n plt.title('Variance comparison for ' +\n func.__name__ + ' with data noise of '+str(int(noise_var*100)) + '%')\n plt.show()\n\n\ndef plot_centers(func):\n VARS = [10, 1, 0.1, 0.01, 0.001]\n n_train = 64\n n_test = 63\n rbfs = np.arange(1, 100)\n noise_var = 0.1\n\n centering = ['linspace', 'random']\n\n train_patterns, train_targets, test_patterns, test_targets = gen_func_data(\n n_train, n_test, func, noise_var=noise_var)\n\n for center in centering:\n error = np.zeros(len(rbfs))\n for i, n_rbf in enumerate(rbfs):\n network = RBFNetwork(n_inputs=1, n_rbf=n_rbf,\n n_outputs=1, centering=center)\n network.fit(train_patterns, train_targets, 'batch')\n preds = network.predict(train_patterns)\n mse = network.calc_mse(preds, train_targets)\n error[i] = mse\n plt.plot(rbfs, error, label='Centering using: '+str(center))\n plt.legend()\n plt.xlabel('#RBF nodes')\n plt.ylabel('MSE')\n plt.title('Centering comparison for ' +\n func.__name__ + ' with data noise of '+str(int(noise_var*100)) + '%')\n plt.show()\n\n\n# plot_prediction(square)\n# plot_error(sin2)\nplot_convergence_comparison(sin2)\n# final_test_error_comparison(sin2)\n# plot_variance(sin2)\n# plot_variance(square)\n# plot_centers(sin2)\n# plot_centers(square)\n","sub_path":"lab2/3_2.py","file_name":"3_2.py","file_ext":"py","file_size_in_byte":7414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"400113675","text":"import random\n\n\n# Генератор вычленения полей из массива словарей\n# Пример:\n# goods = [\n# {'title': 'Ковер', 'price': 2000, 'color': 'green'},\n# {'title': 'Диван для отдыха', 'price': 5300, 'color': 'black'}\n# ]\n# field(goods, 'title') должен выдавать 'Ковер', 'Диван для отдыха'\n# field(goods, 'title', 'price') должен выдавать {'title': 'Ковер', 'price': 2000}, {'title': 'Диван для отдыха', 'price': 5300}\n\ndef field(items, *args):\n assert len(args) > 0\n for i in items: # Лезем в словари предметов последовательно\n if len(args) == 1: # Для вывода значения по единственному ключу...\n yield i[args[0]] # ...просто отдаём значение\n else: # Если ключей больше...\n d_out = {} # ...будем отдавать словарь\n for j in args: # Берём ключи последовательно\n if i[j] is not None: # Предусмотреть возможное отсутствие пары!!!\n d_out[j] = i[j] # Добавляем в словарь соответствующую пару\n yield d_out # Отдаём\n\n\n# Генератор списка случайных чисел\n# Пример:\n# gen_random(1, 3, 5) должен выдать примерно 2, 2, 3, 2, 1\n# Hint: реализация занимает 2 строки\ndef gen_random(begin, end, num_count):\n for i in range(num_count):\n yield random.randrange(begin, end+1, 1)","sub_path":"librip/gens.py","file_name":"gens.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"374694142","text":"#from django.conf.urls import url\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.init, name=\"init\"),\n path('worldmap/', views.worldmap, name=\"worldmap\"),\n path('options/load/', views.load, name=\"load\"),\n path('options/load_A/', views.load_A, name=\"load_A\"),\n path('options/load_up/', views.load_up, name=\"load_up\"),\n path('options/load_down/', views.load_down, name=\"load_down\"),\n path('options/save_game/', views.save, name=\"save\"),\n path('options/save_A/', views.save_A, name=\"save_A\"),\n path('options/save_B', views.save_B, name=\"save_B\"),\n path('options/save_up/', views.save_up, name=\"save_up\"),\n path('options/save_down/', views.save_down, name=\"save_down\"),\n path('up/', views.up, name=\"up\"),\n path('down/', views.down, name=\"down\"),\n path('left/', views.left, name=\"left\"),\n path('right/', views.right, name=\"right\"),\n path('options/', views.options, name=\"options\"),\n path('moviedex/', views.moviedex, name=\"moviedex\"),\n path('moviedex_up/', views.moviedex_up, name=\"moviedex_up\"),\n path('moviedex_down/', views.moviedex_down, name=\"moviedex_down\"),\n path('moviedex//', views.details, name=\"details\"),\n path('battle//', views.battle, name=\"battle\"),\n path('battle_A//', views.battle_A, name=\"battle_A\"),\n]\n","sub_path":"01-piscine_python_django.a/rush00/rush00/game/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"559874482","text":"#!/usr/bin/env python\n\nimport pprint\n\ndef ts_key(x):\n if x[0] == 'E':\n return int(x[2])\n else:\n return int(x[1])\n\ndef log_key(x):\n if x[0] == 'E':\n return \" \".join(x[3:])\n else:\n return \" \".join(x[2:])\n\nwith open(\"Ltn2xXej\") as f:\n content = f.readlines()\n\nlines = [l.rstrip().split(\" \",3) for l in content]\nlines.sort(key=ts_key)\n\nfor l in ([log_key(l) for l in lines if l[0] == 'E']):\n print(l)\n","sub_path":"prob2.py","file_name":"prob2.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"364718780","text":"# -*- coding: utf-8 -*-\n\nimport flask\nimport mwapi\nimport mwoauth\nimport os\nimport random\nimport requests_oauthlib\nimport string\nimport toolforge\nimport yaml\nimport json\n\n\napp = flask.Flask(__name__)\n\nuser_agent = toolforge.set_user_agent(\n 'nordiska-depicts',\n email='tools.nordiska-depicts@tools.wmflabs.org')\n\n__dir__ = os.path.dirname(__file__)\ntry:\n with open(os.path.join(__dir__, 'config.yaml')) as config_file:\n app.config.update(yaml.safe_load(config_file))\nexcept FileNotFoundError:\n print('config.yaml file not found, assuming local development setup')\n characters = string.ascii_letters + string.digits\n random_string = ''.join(random.choice(characters) for _ in range(64))\n app.secret_key = random_string\n\nif 'oauth' in app.config:\n oauth_config = app.config['oauth']\n consumer_token = mwoauth.ConsumerToken(oauth_config['consumer_key'],\n oauth_config['consumer_secret'])\n index_php = 'https://commons.wikimedia.org/w/index.php'\n\n\n@app.template_global()\ndef csrf_token():\n if 'csrf_token' not in flask.session:\n characters = string.ascii_letters + string.digits\n random_string = ''.join(random.choice(characters) for _ in range(64))\n flask.session['csrf_token'] = random_string\n return flask.session['csrf_token']\n\n\n@app.template_global()\ndef form_value(name):\n if 'repeat_form' in flask.g and name in flask.request.form:\n return (flask.Markup(r' value=\"') +\n flask.Markup.escape(flask.request.form[name]) +\n flask.Markup(r'\" '))\n else:\n return flask.Markup()\n\n\n@app.template_global()\ndef form_attributes(name):\n return (flask.Markup(r' id=\"') +\n flask.Markup.escape(name) +\n flask.Markup(r'\" name=\"') +\n flask.Markup.escape(name) +\n flask.Markup(r'\" ') +\n form_value(name))\n\n\n@app.template_filter()\ndef user_link(user_name):\n user_href = 'https://commons.wikimedia.org/wiki/User:'\n return (flask.Markup(r'') +\n flask.Markup(r'') +\n flask.Markup.escape(user_name) +\n flask.Markup(r'') +\n flask.Markup(r''))\n\n\n@app.template_global()\ndef authentication_area():\n if 'oauth' not in app.config:\n return flask.Markup()\n\n if 'oauth_access_token' not in flask.session:\n return (flask.Markup(r'Log in'))\n\n access_token = mwoauth.AccessToken(**flask.session['oauth_access_token'])\n identity = mwoauth.identify(index_php,\n consumer_token,\n access_token)\n\n return (flask.Markup(r'Logged in as ') +\n user_link(identity['username']) +\n flask.Markup(r''))\n\n\n@app.template_global()\ndef authenticated_session():\n if 'oauth_access_token' not in flask.session:\n return None\n\n access_token = mwoauth.AccessToken(\n **flask.session['oauth_access_token'])\n auth = requests_oauthlib.OAuth1(client_key=consumer_token.key,\n client_secret=consumer_token.secret,\n resource_owner_key=access_token.key,\n resource_owner_secret=access_token.secret)\n return mwapi.Session(host='https://commons.wikimedia.org',\n auth=auth,\n user_agent=user_agent)\n\n\n@app.route('/')\ndef index():\n return flask.render_template('index.html')\n\n\n@app.route('/login')\ndef login():\n redirect, request_token = mwoauth.initiate(index_php, consumer_token, user_agent=user_agent)\n flask.session['oauth_request_token'] = dict(zip(request_token._fields, request_token))\n return flask.redirect(redirect)\n\n\n@app.route('/oauth-callback')\ndef oauth_callback():\n request_token = mwoauth.RequestToken(**flask.session.pop('oauth_request_token'))\n access_token = mwoauth.complete('https://commons.wikimedia.org/w/index.php', consumer_token, request_token, flask.request.query_string, user_agent=user_agent)\n flask.session['oauth_access_token'] = dict(zip(access_token._fields, access_token))\n return flask.redirect(flask.url_for('index'))\n\n\n@app.route('/page')\ndef page():\n if authenticated_session():\n return flask.render_template('page.html')\n else:\n return flask.redirect('/login')\n\n\n@app.route('/api/save', methods=['POST'])\ndef task():\n mwapi_auth_session = authenticated_session()\n if not mwapi_auth_session:\n return flask.abort(404)\n\n data = False\n if flask.request.method == 'POST':\n data = flask.request.get_json(force=True)\n else:\n return flask.abort(400)\n\n media_id = data['entity']\n for item in data['targets']:\n csrf_token = mwapi_auth_session.get(action='query', meta='tokens', type='csrf')['query']['tokens']['csrftoken']\n\n entity = {\n 'entity-type': 'item',\n 'numeric-id': item[1:]\n }\n edit = mwapi_auth_session.post(action='wbcreateclaim', entity=media_id, property='P180', snaktype='value', value=json.dumps(entity), token=csrf_token)\n return flask.jsonify(True)\n\ndef full_url(endpoint, **kwargs):\n scheme = flask.request.headers.get('X-Forwarded-Proto', 'http')\n return flask.url_for(endpoint, _external=True, _scheme=scheme, **kwargs)\n\n\ndef submitted_request_valid():\n \"\"\"Check whether a submitted POST request is valid.\n\n If this method returns False, the request might have been issued\n by an attacker as part of a Cross-Site Request Forgery attack;\n callers MUST NOT process the request in that case.\n \"\"\"\n real_token = flask.session.pop('csrf_token', None)\n submitted_token = flask.request.form.get('csrf_token', None)\n if not real_token:\n # we never expected a POST\n return False\n if not submitted_token:\n # token got lost or attacker did not supply it\n return False\n if submitted_token != real_token:\n # incorrect token (could be outdated or incorrectly forged)\n return False\n if not (flask.request.referrer or '').startswith(full_url('index')):\n # correct token but not coming from the correct page; for\n # example, JS running on https://tools.wmflabs.org/tool-a is\n # allowed to access https://tools.wmflabs.org/tool-b and\n # extract CSRF tokens from it (since both of these pages are\n # hosted on the https://tools.wmflabs.org domain), so checking\n # the Referer header is our only protection against attackers\n # from other Toolforge tools\n return False\n return True\n\n\n@app.after_request\ndef deny_frame(response):\n \"\"\"Disallow embedding the tool’s pages in other websites.\n\n If other websites can embed this tool’s pages, e. g. in