diff --git "a/1751.jsonl" "b/1751.jsonl" new file mode 100644--- /dev/null +++ "b/1751.jsonl" @@ -0,0 +1,716 @@ +{"seq_id":"391292686","text":"# -*- coding:UTF-8 -*-\n\n'''\nCreated on 2013-9-7\n\n@author: cfh\n'''\nimport win32api\nimport win32file\nimport win32pipe\nimport winerror\nimport pywintypes\nimport time\nimport creditutils.base_util as base\n\nimport inspect\n\ndef func_flag():\n pass\n\nglobal __modpath__\n__modpath__ = base.module_path(func_flag)\n\n\ndef get_file_line():\n return (__modpath__, inspect.currentframe().f_back.f_lineno)\n\n# 命名管道读取实现 \nclass ReadClient(object):\n MS_TO_SEC = 0.001\n WAIT_TIMEOUT = 2000\n BUFFER_SIZE = 16384\n PIPE_PATH_FORMAT = '\\\\\\\\{0}\\\\pipe\\\\{1}'\n PIPE_NAME = 'USB_DEVICE_MONITOR_WRITE_SERVER_201309122124'\n PIPE_PATH = PIPE_PATH_FORMAT.format('.', PIPE_NAME)\n MSG_HEAD_FLAG = '!PIPE_MSG_HEAD!'\n \n def __init__(self, pipePath=PIPE_PATH):\n self.pipePath = pipePath\n self.hPipe = None\n self.receiver = None\n \n def Connect(self):\n isFirstConnect = True\n while True:\n try:\n self.hPipe = win32file.CreateFile(self.pipePath, \n win32file.GENERIC_READ, \n 0, \n None, \n win32file.OPEN_EXISTING,\n 0,\n None)\n \n infoFormat = 'The named pipe {0} is connected.'\n info = infoFormat.format(self.pipePath)\n win32api.OutputDebugString(info)\n \n return self.hPipe\n \n except pywintypes.error as e:\n infoFormat = 'Unable to open named pipe {0}, w/err: {1}'\n info = infoFormat.format(self.pipePath, e.args[2]);\n win32api.OutputDebugString(info)\n \n if isFirstConnect:\n isFirstConnect = False\n \n # 如果提示没有找到文件,则等待一定时间之后再尝试打开\n if e.args[0] == winerror.ERROR_FILE_NOT_FOUND:\n time.sleep(ReadClient.WAIT_TIMEOUT*ReadClient.MS_TO_SEC)\n continue\n \n elif e.args[0] == winerror.ERROR_PIPE_BUSY:\n # All pipes instances are busy, so wait for some seconds\n try:\n win32pipe.WaitNamedPipe(self.pipePath, ReadClient.WAIT_TIMEOUT)\n continue\n except pywintypes.error as waitError:\n# if waitError.args[0] == winerror.ERROR_SEM_TIMEOUT:\n infoFormat = '{0} {1} failed, w/err: {2}'\n info = infoFormat.format(waitError.args[1], self.pipePath, waitError.args[2])\n win32api.OutputDebugString(info)\n \n return None\n \n else: # Exit if an error other than ERROR_FILE_NOT_FOUND or ERROR_PIPE_BUSY occurs\n return None\n else:\n return None\n \n def Receive(self):\n # Receive data from server\n \n bufObject = win32file.AllocateReadBuffer(ReadClient.BUFFER_SIZE)\n \n while True:\n try:\n (readRtn, data) = win32file.ReadFile(self.hPipe, bufObject)\n if readRtn != 0 and readRtn != winerror.ERROR_MORE_DATA:\n showFormat = 'ReadFile failed, w/err: {0} {1}: {2}'\n showInfo = showFormat.format(win32api.FormatMessage(win32api.GetLastError()), *get_file_line())\n win32api.OutputDebugString(showInfo)\n break\n \n data_list = data.split(ReadClient.MSG_HEAD_FLAG)\n if self.receiver:\n for item in data_list:\n if len(item) > 0:\n self.receiver(item)\n \n except pywintypes.error as e:\n showFormat = '{0} failed, w/err: {1} {2}: {3}'\n showInfo = showFormat.format(e.args[1], e.args[2], *get_file_line())\n win32api.OutputDebugString(showInfo)\n break\n \n def SetReceiver(self, receiver):\n self.receiver = receiver\n \n def Close(self):\n if self.hPipe:\n self.hPipe.Close()\n self.hPipe = None\n\nclass Consumer:\n TYPE_FLAG = 'CHANGE_TYPE' # 设备状态变化标识\n TYPE_ARRIVAL_FLAG = 'ARRIVAL' # 设备插入\n TYPE_REMOVE_FLAG = 'REMOVE' # 设备拔出\n TYPE_HEARTBEAT_FLAG = 'HEARTBEAT' # 心跳\n PIPE_MSG_COLON_ALIAS = '&!colon!&' # \":\"替换符\n PIPE_MSG_COMMA_ALIAS = '&!comma!&' # \",\"替换符\n \n VID_FLAG = 'VID'\n PID_FLAG = 'PID'\n SN_FLAG = 'SN'\n NAME_FLAG = 'FRIENDLYNAME'\n MFG_FLAG = 'MFG' # 厂商信息\n DESC_FLAG = 'DEVICEDESC'\n \n \n TYPE_ARRIVAL = 1\n TYPE_REMOVE = 2\n TYPE_HEARTBEAT = 3\n \n TYPE_MAP = {\n TYPE_ARRIVAL_FLAG: TYPE_ARRIVAL,\n TYPE_REMOVE_FLAG: TYPE_REMOVE,\n TYPE_HEARTBEAT_FLAG: TYPE_HEARTBEAT\n }\n \n HEARTBEAT_SHOW_INTERVAL = 60\n \n def __init__(self):\n self.heartbeatCnt = 0\n self.receiver = None\n \n def _replace_seperator_alias_in_data(self, data):\n return data.replace(Consumer.PIPE_MSG_COLON_ALIAS, ':').replace(Consumer.PIPE_MSG_COMMA_ALIAS, ',')\n \n def Process(self, item):\n infoDict = {}\n \n infos = item.split(',')\n for subItem in infos:\n if len(subItem) > 0:\n infoItems = subItem.split(':')\n key = self._replace_seperator_alias_in_data(infoItems[0].strip())\n val = self._replace_seperator_alias_in_data(infoItems[1].strip())\n infoDict[key] = val\n \n self._ShowDebugInfo(infoDict)\n \n try:\n msgType = Consumer.TYPE_MAP[infoDict[Consumer.TYPE_FLAG]]\n if msgType != Consumer.TYPE_HEARTBEAT:\n if self.receiver:\n self.receiver(infoDict)\n \n except KeyError as e:\n win32api.OutputDebugString(str(e))\n return\n \n def _ShowDebugInfo(self, item):\n try:\n msgType = Consumer.TYPE_MAP[item[Consumer.TYPE_FLAG]]\n except KeyError as e:\n win32api.OutputDebugString(str(e))\n return\n \n showFormat = 'Receives Message: \"{0}\"'\n if msgType == Consumer.TYPE_HEARTBEAT:\n self.heartbeatCnt += 1\n if self.heartbeatCnt % Consumer.HEARTBEAT_SHOW_INTERVAL == 0:\n showInfo = showFormat.format(item)\n else:\n showInfo = None\n else:\n showInfo = showFormat.format(item)\n\n if showInfo: \n win32api.OutputDebugString(showInfo)\n \n def SetReceiver(self, receiver):\n self.receiver = receiver\n\nBUFFER_SIZE = 65536\ndef CreateServer():\n p = win32pipe.CreateNamedPipe('\\\\\\\\.\\\\pipe\\\\test_pipe',\n win32pipe.PIPE_ACCESS_DUPLEX,\n win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT,\n 1, 65536, 65536,300, None)\n \n bufObject = win32file.AllocateReadBuffer(BUFFER_SIZE)\n data = 'Hello Pipe' \n for i in range(len(data)):\n bufObject[i] = ord(data[i])\n \n win32pipe.ConnectNamedPipe(p, None)\n \n \n win32file.WriteFile(p, bufObject[0:len(data)])\n \ndef CreateClient():\n fileHandle = win32file.CreateFile('\\\\\\\\.\\\\pipe\\\\test_pipe',\n win32file.GENERIC_READ | win32file.GENERIC_WRITE,\n 0, None,\n win32file.OPEN_EXISTING,\n 0, None)\n data = win32file.ReadFile(fileHandle, 4096)\n win32file.CloseHandle(fileHandle)\n print(data)","sub_path":"src/creditutils/pipe_util.py","file_name":"pipe_util.py","file_ext":"py","file_size_in_byte":8059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"143009674","text":"n1 = int(input('Insira o 1ª número: '))\r\nn2 = int(input('Insira o 2ª número: '))\r\nprint('-' * 36)\r\nprint('Qual opção você deseja?')\r\nprint('-' * 36)\r\nopcao = 0\r\nwhile opcao != 5:\r\n print('[1]\\33[35msomar\\33[m\\n[2]\\33[35mmultiplicar\\33[m\\n[3]\\33[35mmaior\\33[m'\r\n '\\n[4]\\33[35mnovos números\\33[m\\n[5]\\33[35msair do programa\\33[m')\r\n opcao = int(input('Digite a opção desejada: '))\r\n if opcao == 1:\r\n print('A soma de {} e {} é igual a {}'.format(n1, n2, (n1+n2)))\r\n elif opcao == 2:\r\n print('A multiplicação de {} e {} é igual a {}.'.format(n1, n2, (n1 * n2)))\r\n elif opcao == 3:\r\n if n1 > n2:\r\n print('O maior número é {}.'.format(n1))\r\n else:\r\n print('O maior número é {}.'.format(n2))\r\n elif opcao == 4:\r\n n1 = int(input('Insira um novo número: '))\r\n n2 = int(input('Insira um novo número: '))\r\n else:\r\n print('\\nVoce saiu do programa! Até logo!!')\r\n","sub_path":"Ex0059/ex0059.py","file_name":"ex0059.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"300164197","text":"def binarySearch (arr, l, r, x):\n if r >= l:\n mid = l + (r - l) // 2\n if arr[mid] == x:\n return mid\n elif arr[mid] > x:\n return binarySearch(arr, l, mid-1, x)\n else:\n return binarySearch(arr, mid + 1, r, x)\n else:\n return -1\n\ndef partition(arr,low,high):\n i = (low-1)\n pivot = arr[high]\n \n for j in range(low , high):\n if arr[j] < pivot:\n i = i+1\n arr[i],arr[j] = arr[j],arr[i]\n \n arr[i+1],arr[high] = arr[high],arr[i+1]\n return (i+1)\n \ndef quickSort(arr,low,high):\n if low < high:\n pi = partition(arr,low,high)\n quickSort(arr, low, pi-1)\n quickSort(arr, pi+1, high)\n\nn,q = list(map(int,input().split()))\narr = input().split()\nquickSort(arr,0,n-1)\nprint(' '.join(arr))\n\nfor i in range(q):\n\tx = input()\n\tres = binarySearch(arr, 0, n-1, x)\n\tprint(res)","sub_path":"ene-jun-2020/juan flores/examen2.py","file_name":"examen2.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"69385652","text":"\"\"\"\nThis module contains the class for Simple Genetic Algorithm strategy\n\"\"\"\n\nimport os\nimport pickle\nimport numpy as np\nimport random\nfrom deap import base, creator, tools\nfrom dowel import logger\n\nfrom varro.algo.strategies.strategy import Strategy\n\n\nclass StrategySGA(Strategy):\n def __init__(self, **kwargs):\n if \"name\" not in kwargs.keys():\n kwargs[\"name\"] = \"sga\"\n super().__init__(**kwargs)\n\n @staticmethod\n def init_fitness_and_inds():\n logger.start_timer()\n \"\"\"Initializes the fitness and definition of individuals\"\"\"\n\n class Fitness(base.Fitness):\n def __init__(self):\n super().__init__()\n self.__fitness_score = None\n\n @property\n def fitness_score(self):\n return self.values[0]\n\n @fitness_score.setter\n def fitness_score(self, fitness_score):\n self.__fitness_score = fitness_score\n if fitness_score:\n # WARNING:\n # Setting values breaks alot of things:\n # self.__fitness_score is reset to None\n # after setting values, so you should only\n # set values after all the scores you require are set\n self.values = (fitness_score,)\n\n @fitness_score.deleter\n def fitness_score(self):\n if hasattr(self, '__fitness_score'):\n del self.__fitness_score\n\n def delValues(self):\n super().delValues()\n if hasattr(self, '__fitness_score'):\n del self.__fitness_score\n\n creator.create(\"FitnessMin\", Fitness, weights=(-1.0,)) # Just Fitness\n creator.create(\"Individual\", np.ndarray, fitness=creator.FitnessMin)\n\n logger.stop_timer('SGA.PY Initializing fitness and individuals')\n logger.start_timer()\n\n\n def init_toolbox(self):\n \"\"\"Initializes the toolbox according to strategy\"\"\"\n # Define specific Fitness and Individual for SGA\n self.init_fitness_and_inds()\n\n # Configure the rest of the toolbox that is independent\n # of which evolutionary strategy\n super().config_toolbox()\n\n\n\n def load_es_vars(self):\n \"\"\"Loads the evolutionary strategy variables from checkpoint given after\n creating the fitness and individual templates for DEAP evolution or initializes them\n \"\"\"\n\n logger.start_timer()\n\n if self.ckpt:\n # A file name has been given, then load the data from the file\n # Load data from pickle file\n with open(self.ckpt, \"rb\") as cp_file:\n cp = pickle.load(cp_file)\n\n self.rndstate = random.seed(cp[\"rndstate\"])\n self.pop = cp[\"pop\"]\n self.curr_gen = int(cp[\"curr_gen\"])\n self.halloffame = cp[\"halloffame\"]\n self.logbook = cp[\"logbook\"]\n\n else:\n # Start a new evolution\n self.rndstate = random.seed(100) # Set seed\n self.pop = self.toolbox.population(n=self.popsize)\n self.curr_gen = 0\n self.halloffame = tools.HallOfFame(maxsize=int(self.halloffamesize*self.popsize), similar=np.array_equal)\n self.logbook = tools.Logbook()\n\n self.paretofront = None\n logger.stop_timer('SGA.PY Loading ES Vars')\n\n\n def save_ckpt(self):\n \"\"\"Saves information necessary to resume algorithm after stopping\"\"\"\n\n logger.start_timer()\n\n # Fill the dictionary using the dict(key=value[, ...]) constructor\n cp = dict(pop=self.pop,\n strategy=self.name,\n curr_gen=self.curr_gen,\n halloffame=self.halloffame,\n paretofront=self.paretofront,\n logbook=self.logbook,\n rndstate=self.rndstate)\n\n with open(os.path.join(self.ckpt_dir, '{0:09d}.pkl'.format(self.curr_gen)), \"wb\") as cp_file:\n pickle.dump(cp, cp_file)\n\n logger.stop_timer('SGA.PY Saving checkpoint')\n\n\n def compute_fitness(self, pop):\n \"\"\"Calculates the fitness scores for the entire Population\n\n Args:\n pop (list): An iterable of Individual(np.ndarrays) that represent the individuals\n\n Returns:\n Number of individuals with invalid fitness scores we updated\n \"\"\"\n\n logger.start_timer()\n\n # Evaluate the individuals with an invalid fitness or if we are at the start\n # of the evolutionary algo, AKA curr_gen == 0\n # (These are the individuals that have not been evaluated before -\n # individuals at the start of the evolutionary algorithm - or those\n # that have been mutated / the offspring after crossover with fitness deleted)\n invalid_inds = [ind for ind in pop if not ind.fitness.valid or self.curr_gen == 0]\n\n # Get fitness score for each individual with\n # invalid fitness score in population\n for ind in invalid_inds:\n\n # Load Weights into model using individual\n self.model.load_parameters(ind)\n\n # Calculate the Fitness score of the individual\n ind.fitness.fitness_score = self.fitness_score()\n\n logger.stop_timer('SGA.PY Computing fitness')\n\n return len(invalid_inds)\n\n\n def evaluate(self, pop):\n\n logger.start_timer()\n\n \"\"\"Evaluates an entire population on a dataset on the neural net / fpga\n architecture specified by the model, and calculates the fitness scores for\n each individual, sorting the entire population by fitness scores in-place\n\n Args:\n pop (list): An iterable of np.ndarrays that represent the individuals\n\n Returns:\n Average fitness score of population\n\n \"\"\"\n # Re-generates the training set for the problem (if possible) to prevent overfitting\n self.problem.reset_train_set()\n\n logger.stop_timer('SGA.PY Regenerate the training set')\n logger.start_timer()\n\n # Compute all fitness for population\n num_invalid_inds = self.compute_fitness(pop)\n logger.start_timer()\n logger.stop_timer('SGA.PY Computing all fitness for population')\n logger.start_timer()\n\n # The population is entirely replaced by the\n # evaluated offspring\n self.pop[:] = pop\n logger.stop_timer('SGA.PY Replace population with evaluated offspring')\n logger.start_timer()\n\n # Update population statistics\n self.halloffame.update(self.pop)\n # record = self.stats.compile(self.pop)\n # self.logbook.record(gen=self.curr_gen, evals=num_invalid_inds, **record)\n logger.stop_timer('SGA.PY Updating population statistics')\n\n return np.mean([ind.fitness.fitness_score for ind in pop])\n\n\n def generate_offspring(self):\n\n \"\"\"Generates new offspring using a combination of the selection methods\n specified to choose fittest individuals and custom preference\n\n Returns:\n A Tuple of (Non-alterable offspring, Alterable offspring)\n\n \"\"\"\n # Keep the elite individuals for next generation\n # without mutation or cross over\n elite_num = int(self.elitesize*self.popsize)\n elite = self.toolbox.select_elite(self.pop, k=elite_num)\n\n # Clone the selected individuals\n non_alterable_elite_offspring = list(map(self.toolbox.clone, elite))\n\n # Choose the rest of the individuals\n # to be altered\n random_inds = self.toolbox.select(self.pop, k=self.popsize-2*elite_num)\n alterable_offspring = list(map(self.toolbox.clone, random_inds)) + list(map(self.toolbox.clone, elite))\n\n return non_alterable_elite_offspring, alterable_offspring\n","sub_path":"varro/algo/strategies/sga.py","file_name":"sga.py","file_ext":"py","file_size_in_byte":7817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"647706673","text":"from ask_sdk_core.handler_input import HandlerInput\n\nBASE_URL = \"